C#批量压缩图片(BMP/PNG/JPG)
程序员懒吧?呵呵。 只要能找到一个好用的,我是绝对不会自己写一个出来的。因为WordPress的图库插件NextGEN Gallery破算法不能压缩太大的文件,PHP执行内存不足,同样的照片跑在同一环境下的Gallery2处理起来很轻松,还能一下执行N张呢... 没办法只好先把照片压缩下在传上去了。找个好几个批量压缩软件都不如意,没办法只好自己写一个了。
界面是这样子的:
核心算法其实非常简单:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Drawing.Imaging; using System.IO;
namespace JPGCompact { public partial class MainForm : Form { /// /// 保存JPG时用 /// /// 文件类型 /// <returns>得到指定mimeType的ImageCodecInfo</returns> private static ImageCodecInfo GetCodecInfo(string mimeType) { ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders(); foreach (ImageCodecInfo ici in CodecInfo) { if (ici.MimeType == mimeType) return ici; } return null; }
///
/// 保存为JPEG格式,支持压缩质量选项
///
/// 原始位图
/// 新文件地址
/// 压缩质量,越大越好,文件也越大(0-100)
/// <returns>成功标志</returns>
public static bool SaveAsJPEG(Bitmap bmp, string FileName, int Qty)
{
try
{
EncoderParameter p;
EncoderParameters ps;
ps = new EncoderParameters(1);
p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Qty);
ps.Param = p;
bmp.Save(FileName, GetCodecInfo("image/jpeg"), ps);
return true;
}
catch
{
return false;
}
}
private bool CompressPicture(string sourcePath, string targetPath)
{
try
{
// 大小比率
double sizeRate = double.Parse(cbSizeRate.Text) / 100;
// 品质比率
int qualityRate = int.Parse(cbQualityRate.Text);
Image sourceImage = Image.FromFile(sourcePath);
// 调整图片大小
Bitmap bmp = new Bitmap(
sourceImage,
new Size(
(int)(sourceImage.Width * sizeRate),
(int)(sourceImage.Height * sizeRate)));
// 压缩图片
SaveAsJPEG(bmp, targetPath, qualityRate);
GC.Collect();
return true;
}
catch
{
return false;
}
}
}
}
比较有技术含量的是那个Exif信息的读取,一会儿我写一篇说说那个怎么做。
下载地址:http://download.nocoo.us/Download/Archive/JPGCompact.rar