如何:判斷編碼器所支援的參數
您可以調整影像參數,例如品質與壓縮層級,但您必須知道指定的影像編碼器支援哪些參數。 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
編譯程式碼
這個範例需要:
Windows Forms 應用程式。
PaintEventArgs,這是 PaintEventHandler 的參數。