using System.Collections.Generic;
using System.Drawing;
using System.IO;
namespace GxPress.Common.Tools
{
///
/// 压缩图片
///
public class CompressImage
{
///
/// 开始压缩图片
///
/// 图片路径
/// 图片格式大小 默认 50*50
public static void Execute(string fileName = "", int width = 50)
{
//获取图片的返回类型
var contentTypDict = new Dictionary {
{"jpg","image/jpeg"},
{"JPG","image/jpeg"},
{"jpeg","image/jpeg"},
{"JPEG","image/jpeg"},
{"jpe","image/jpeg"},
{"png","image/png"},
{"gif","image/gif"},
{"ico","image/x-ico"},
{"tif","image/tiff"},
{"tiff","image/tiff"},
{"fax","image/fax"},
{"wbmp","image//vnd.wap.wbmp"},
{"rp","image/vnd.rn-realpix"}
};
var imgTypeSplit = fileName.Split('.');
var contentTypeStr = "image/jpeg";
var imgType = imgTypeSplit[imgTypeSplit.Length - 1];
//未知的图片类型
if (!contentTypDict.ContainsKey(imgType.ToLower()))
return;
else
contentTypeStr = contentTypDict[imgType];
//图片不存在
if (!new FileInfo(fileName).Exists)
return;
if (fileName.Contains("50_50") || fileName.Contains("100_100"))
return;
//缩小图片
var imageName = $"_{width}_{width}.{imgType}";
var searchFileName = fileName.Replace($".{imgType}", imageName);
if (File.Exists(searchFileName))
return;
using (var imgBmp = new Bitmap(fileName))
{
//找到新尺寸
var oWidth = imgBmp.Width;
var oHeight = imgBmp.Height;
var height = oHeight;
if (width > oWidth)
width = oWidth;
else
height = width * oHeight / oWidth;
var newImg = new Bitmap(imgBmp, width, height);
newImg.SetResolution(72, 72);
var ms = new MemoryStream();
newImg.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
var bytes = ms.GetBuffer();
//保存图片
Image image = Image.FromStream(ms);
fileName = fileName.Replace($".{imgType}", imageName);
image.Save(fileName);
ms.Close();
imgBmp.Dispose();
}
}
}
}