有些时候会在博客中分享一些拍摄的照片,而这些拍摄照片的大小均在1.5M以上,随随便便分享点图片占用的存储空间就有点惊人。为了节省存储空间,避免尽早将剩余存储空间消耗完毕,所以就考虑压缩一下图片。这里来做下记录。
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace ImageCompress
{
class Program
{
static void Main(string[] args)
{
string path = $"{Path.Combine(Directory.GetCurrentDirectory(), "image")}";
CompressionImageProcess.CompressionImage($"{Path.Combine(path, "IMG_20200308_161707.jpg")}",$"{Path.Combine(path, "compression")}",50);
Console.WriteLine("OK");
}
}
public class CompressionImageProcess
{
public static void CompressionImage(string imagePath, string targetfolder, long quality = 100)
{
if (!File.Exists(imagePath))
{
throw new FileNotFoundException();
}
if (!Directory.Exists(targetfolder))
{
Directory.CreateDirectory(targetfolder);
}
FileInfo fileInfo = new FileInfo(imagePath);
string fileName = fileInfo.Name.Replace(fileInfo.Extension, "");
string fileFullName = Path.Combine($"{targetfolder}", $"{fileName}{fileInfo.Extension}");
var iamgeByte = CompressionImage(imagePath, quality);
MemoryStream ms = new MemoryStream(iamgeByte);
Image image = System.Drawing.Image.FromStream(ms);
image.Save(fileFullName);
ms?.Close();
ms?.Dispose();
image?.Dispose();
}
private static byte[] CompressionImage(string imagePath, long quality)
{
using (FileStream fileStream = new FileStream(imagePath, FileMode.Open))
{
using (System.Drawing.Image img = System.Drawing.Image.FromStream(fileStream))
{
using (Bitmap bitmap = new Bitmap(img))
{
ImageCodecInfo CodecInfo = GetEncoder(img.RawFormat);
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, quality);
myEncoderParameters.Param[0] = myEncoderParameter;
using (MemoryStream ms = new MemoryStream())
{
bitmap.Save(ms, CodecInfo, myEncoderParameters);
myEncoderParameters?.Dispose();
myEncoderParameter?.Dispose();
return ms.ToArray();
}
}
}
}
}
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
}
}
下图大小为1.5M,压缩质量设置了50,压缩后的大小为306.6k,压缩前后的质量清晰度还可以接受。
示例下载
图片压缩示例其实示例代码写完就觉得自己有点傻,发现WordPress图片压缩插件也有不少,以后能省则省吧!