日期:2014-05-18 浏览次数:21219 次
分为两部分,一个是操作类,另外一个是测试。直接上代码了
一、测试代码
private void button1_Click(object sender, EventArgs e)
{
string newSourcePath = ImgPath;//源图存放目录
string newNewDir = MakePath; //新图存放目录
string sourceFile = Path.Combine(ImgPath, "app1.jpg"); //获取原图路径
string newFile = string.Empty; //新图路径
ImgThumbnail iz = new ImgThumbnail();
Action<ImgThumbnail.ImgThumbnailType> Thumbnail = (type =>
{
//生成质量
for (int i = 100; i >= 10; i -= 10)
{
//计算新图路径,测试命名:原图名_new_缩放类型_压缩质量.jpg
newFile = Path.Combine(newNewDir, string.Format("app1_new_{1}_{0}.jpg", i, type.ToString()));
//压缩图片
iz.Thumbnail(sourceFile, newFile, 100, 100, i, type);
}
});
Thumbnail(ImgThumbnail.ImgThumbnailType.Cut);//裁剪压缩(裁剪压缩还不好用,待调整!)
Thumbnail(ImgThumbnail.ImgThumbnailType.H); //以高度为参照压缩,不变形
Thumbnail(ImgThumbnail.ImgThumbnailType.W); //以宽度为参照压缩,不变形
Thumbnail(ImgThumbnail.ImgThumbnailType.WH); //固定宽高压缩,变形
MessageBox.Show("完成");
}
二、操作类
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace MagickNet.App
{
/// <summary>
/// 图片压缩
/// </summary>
public class ImgThumbnail
{
/// <summary>
/// 指定缩放类型
/// </summary>
public enum ImgThumbnailType
{
/// <summary>
/// 指定高宽缩放(可能变形)
/// </summary>
WH = 0,
/// <summary>
/// 指定宽,高按比例
/// </summary>
W = 1,
/// <summary>
/// 指定高,宽按比例
/// </summary>
H = 2,
/// <summary>
/// 指定高宽裁减(不变形)
/// </summary>
Cut = 3
}
#region Thumbnail
/// <summary>
/// 无损压缩图片
/// </summary>
/// <param name="sFile">原图片</param>
/// <param name="dFile">压缩后保存位置</param>
/// <param name="height">高度</param>
/// <param name="width"></param>
/// <param name="