主要修改图片dpi值,原理:电脑一般dpi为96,图片dpi超过这个值后,图片清晰度没多大变化,降低图片dpi值就能大幅度降低图片大小,如图片dpi为180,将其降到96后,图片宽高比例不变,图片大小也会降到很小。
class ImageHelper
{/// <summary>
/// 图片压缩(若width或height其中一个为值为零,则按原比例宽高压缩);
/// </summary>
/// <param name="postFile">原图片路径</param>
/// <param name="saveFilePath">压缩图片存储文件夹路径</param>
/// <param name="width">压缩图片宽度</param>
/// <param name="height">压缩图片高度</param>
/// <param name="imgResolution">单位分辨率(dpi)</param>
public static void Compress(string postFile, string saveFilePath,int width,int height, float imgResolution)
{
if(File.Exists(postFile))
{
System.Drawing.Image img = null;
Bitmap bit = null;
try
{
img = System.Drawing.Image.FromFile(postFile);
bit = new Bitmap(img);
bit.SetResolution(imgResolution, imgResolution);//设置dpi
if (width != 0 && height != 0)
{
bit.SetPixel(width, height, Color.Transparent);//设置宽高
}
if (File.Exists(postFile))
{
string saveFile = saveFilePath + Path.GetFileNameWithoutExtension(postFile) + "_";
string extension = Path.GetExtension(postFile);
if (extension != null)
{
string imgFormat = extension.ToLower();
switch (imgFormat)
{
case ".jpg":
bit.Save(saveFile + ".jpg", ImageFormat.Jpeg); break;
case ".jpeg":
bit.Save(saveFile + ".jpeg", ImageFormat.Jpeg); break;
case ".png":
bit.Save(saveFile + ".png", ImageFormat.Png); break;
case ".bmp":
bit.Save(saveFile + ".bmp", ImageFormat.Bmp); break;
};
}
}
}
catch(Exception e)
{
throw new Exception(e.ToString());
}
finally
{
if (img != null)
{
img.Dispose();
}
if (bit != null)
{
bit.Dispose();
}
}
}
}
}
}