如何:确定编码器支持的参数

可以调整图像参数(如质量和压缩级别),但必须知道给定图像编码器支持哪些参数。 Image 类提供的 GetEncoderParameterList 方法可以确定特定编码器支持哪些图像参数。 使用 GUID 指定编码器。 GetEncoderParameterList 方法返回 EncoderParameter 对象的数组。

示例

以下示例代码输出 JPEG 编码器支持的参数。 使用 Encoder 类概述中的参数类别列表和关联的 GUID 来确定每个参数的类别。

private void GetSupportedParameters(PaintEventArgs e)
{
    Bitmap bitmap1 = new Bitmap(1, 1);
    ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
    EncoderParameters paramList = bitmap1.GetEncoderParameterList(jpgEncoder.Clsid);
    EncoderParameter[] encParams = paramList.Param;
    StringBuilder paramInfo = new StringBuilder();

    for (int i = 0; i < encParams.Length; i++)
    {
        paramInfo.Append("Param " + i + " holds " + encParams[i].NumberOfValues +
            " items of type " +
            encParams[i].ValueType + "\r\n" + "Guid category: " + encParams[i].Encoder.Guid + "\r\n");
    }
    e.Graphics.DrawString(paramInfo.ToString(), this.Font, Brushes.Red, 10.0F, 10.0F);
}

private ImageCodecInfo GetEncoder(ImageFormat format)
{
    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

    foreach (ImageCodecInfo codec in codecs)
    {
        if (codec.FormatID == format.Guid)
        {
            return codec;
        }
    }

    return null;
}
Private Sub GetSupportedParameters(ByVal e As PaintEventArgs)
    Dim bitmap1 As New Bitmap(1, 1)
    Dim jpgEncoder As ImageCodecInfo = GetEncoder(ImageFormat.Jpeg)
    Dim paramList As EncoderParameters = _
    bitmap1.GetEncoderParameterList(jpgEncoder.Clsid)
    Dim encParams As EncoderParameter() = paramList.Param
    Dim paramInfo As New StringBuilder()

    Dim i As Integer
    For i = 0 To encParams.Length - 1
        paramInfo.Append("Param " & i & " holds " & _
            encParams(i).NumberOfValues & " items of type " & _
            encParams(i).Type.ToString() & vbCr & vbLf & "Guid category: " & _
             encParams(i).Encoder.Guid.ToString() & vbCr & vbLf)
    Next i

    e.Graphics.DrawString(paramInfo.ToString(), _
       Me.Font, Brushes.Red, 10.0F, 10.0F)
End Sub

Private Function GetEncoder(ByVal format As ImageFormat) As ImageCodecInfo

    Dim codecs As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders()

    Dim codec As ImageCodecInfo
    For Each codec In codecs
        If codec.FormatID = format.Guid Then
            Return codec
        End If
    Next codec
    Return Nothing

End Function

编译代码

此示例需要:

另请参阅