C# bitmap 图片编码及压缩参数

C# bitmap图片编码及压缩参数

读取图片

1
Image img = Image.FromFile(imgFile);

ImageCodecInfo 帮助方法

简写:

1
2
3
4
5
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
var codecs = ImageCodecInfo.GetImageDecoders();
return codecs.FirstOrDefault(codec => codec.FormatID == format.Guid);
}

原始

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

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

编码及压缩

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Bitmap target = new Bitmap(width, height);

// format and encoder
// the format is used by the encoder
// to generate ImageCodecInfo
ImageFormat format = ImageFormat.Jpeg;
ImageCodecInfo encoder = GetEncoder(format);

// Bitmap.Save takes the EncoderParameters,
// but what we make is a EncoderParameter, no "s" at the end.
// use EncoderParameters.Param[0] to assign
EncoderParameters pm = new EncoderParameters(1);
pm.Param[0] = new EncoderParameter(Encoder.Quality, 80L);

string filename = ...
target.Save(filename, encoder, pm);

附:裁剪图片

1
2
3
4
5
6
7
8
Rectangle cropRect = new Rectangle(x, y, width, height);

Bitmap target = new Bitmap(width, height);
Graphics g = Graphics.FromImage(target);
g.DrawImage(img,
new Rectangle(0, 0, target.Width, target.Height),
cropRect,
GraphicsUnit.Pixel);

C# bitmap 图片编码及压缩参数
https://taylorandtony.github.io/2025/01/25/csharp-images/
作者
TaylorAndTony
发布于
2025年1月25日
许可协议