新建.net 6控制台项目
安装System.Drawing.Common包
代码如下
using System.Drawing;
using System.Drawing.Imaging;
namespace PngCompress02
{
internal class Program
{
static void Main(string[] args)
{
CompressPngImage(@"E:\Desktop\6.png", @"E:\Desktop\6_60.png", 60);
Console.WriteLine("完成");
}
public static void CompressPngImage(string sourcePath, string targetPath, long quality)
{
using (var image = Image.FromFile(sourcePath))
{
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
var imageCodecInfo = GetPngImageCodec();
//var imageFormat = ImageFormat.Png;
Bitmap bitmap = new Bitmap(image);
bitmap.Save(targetPath, imageCodecInfo, encoderParameters);
}
}
private static ImageCodecInfo GetPngImageCodec()
{
var codecs = ImageCodecInfo.GetImageEncoders();
foreach (var codec in codecs)
{
if (codec.FormatID == ImageFormat.Png.Guid)
{
return codec;
}
}
throw new ArgumentException("No PNG image codec found.");
}
}
}
测试结果