新建.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.");}}
}
测试结果
既要压缩图片也要改变图片大小
实现思路:先改变图片大小后压缩处理
/// <summary>
/// 重新改变png图片的大小
/// </summary>
/// <param name="image"></param>
/// <param name="newWidth">改变成为的宽度大小</param>
/// <param name="newHeight">改变成为的高度大小</param>
/// <returns></returns>
public static byte[] ResizePngImage(Image image, int newWidth, int newHeight)
{// 确保图片格式为Png //if (image.RawFormat.Guid != ImageFormat.Png.Guid)//{// throw new InvalidOperationException("不支持的图片格式。请使用PNG格式。");//}MemoryStream memoryStream = new MemoryStream();// 创建一个新的Bitmap对象,并设置其分辨率为原始图像的分辨率 using (Bitmap newImage = new Bitmap(newWidth, newHeight)){newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);// 使用Graphics对象从原始图像绘制到新的Bitmap上 using (Graphics graphics = Graphics.FromImage(newImage)){// 设置高质量插值法以进行图像缩放 graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;// 在新图像上绘制原始图像 graphics.DrawImage(image, new Rectangle(Point.Empty, new Size(newWidth, newHeight)));}// 对于PNG图像,我们需要特别处理透明度。这里我们保存带有透明度的图像。 newImage.Save(memoryStream, ImageFormat.Png);}return memoryStream.GetBuffer();
}//压缩图片,返回图片byte[]数组 宽度高度和质量
public byte[] compressPngImage(int sW,int sH int flag)
{var iSource = System.Drawing.Image.FromFile(sFile);var pngStream = ResizePngImage(iSource, sW, sH);var pngImage = Image.FromStream(new MemoryStream(pngStream));var encoder = ImageCodecInfo.GetImageEncoders().FirstOrDefault(c => c.FormatID == ImageFormat.Png.Guid);if (encoder != null){// Set the quality parameter for the PNG encoder var encoderParameters = new EncoderParameters(1);encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, flag);// Save the resized image using the PNG encoder with the specified quality level var thumbnailStream = new MemoryStream();pngImage.Save(thumbnailStream, encoder, encoderParameters);return thumbnailStream.GetBuffer();}
}