C#批量压缩图片(BMP/PNG/JPG)

程序员懒吧?呵呵。
只要能找到一个好用的,我是绝对不会自己写一个出来的。因为WordPress的图库插件NextGEN Gallery破算法不能压缩太大的文件,PHP执行内存不足,同样的照片跑在同一环境下的Gallery2处理起来很轻松,还能一下执行N张呢…
没办法只好先把照片压缩下在传上去了。找个好几个批量压缩软件都不如意,没办法只好自己写一个了。

界面是这样子的:

[singlepic=15854,700,510]

核心算法其实非常简单:

[code=’c#’]
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时用
///

/// 文件类型 /// 得到指定mimeType的ImageCodecInfo
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) /// 成功标志
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[0] = 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;
}
}
}
}
[/code]

比较有技术含量的是那个Exif信息的读取,一会儿我写一篇说说那个怎么做。

下载地址:http://download.nocoo.us/Download/Archive/JPGCompact.rar

8 comments

  1. 想问一下,您有没有在ARM上做图像压缩的经验啊?
    要想把C#改成C编程容易么。。。。好像ARM上可以用通过交叉编译后的C程序!

  2. 不好意思,我从来没做过硬件,所以,没有在ARM上的经验~
    把C#改成C是绝对不可能的事情,你可以死心啦。连Framework都是C++啊。

  3. 能不能把源码发给我呢。不慎感激!邮箱地址:zhuj.ice@gmail.com

  4. 你好,可以给我一份源代码吗?我想学习学习,呵呵。多谢了。lxhsip@gmail.com

  5. 这个没有对PNG压缩的代码啊。

    汗,你所说的压缩只是对图片的一个大小放缩而已。

    而且,你保存时,只能保存为jpg,如果png那就不成了。

发表评论