秋梦无痕

一场秋雨无梦痕,春夜清风冻煞人。冬来冷水寒似铁,夏至京北蟑满城。

Avatar

图片压缩及缩略图的实现

主要是实现我最近作的网站([url]www.heiyou.com[/url])中要实现的上传图片的处理功能,没有考虑更多的需求。

源代码:
using System.Drawing;
using System.Drawing.Imaging;

namespace ifyr.util{
class ImageHandler {
static void Main(string[] args) {
Image sourceImage = Image.FromFile(@"e:\source.jpg");

Compress(sourceImage, @"e:\target.jpg");
CreateThumb(sourceImage, 120, 160, @"e:\thumb.jpg");

sourceImage.Dispose();
}

/// <summary>
/// 将图片转换成200k以下的图片
/// 即生成800*800以内像素,65%品质的JPEG格式图片
/// 请先判断图片大小,如果小于200k,则不需压缩,以免损失图片质量
/// 可以改写为输出到OutputStream
/// </summary>
/// <param name="sourceImage">原图</param>
/// <param name="filename">压缩图片的保存文件名</param>
public static void Compress(Image sourceImage, string filename) {
int targetWidth = 800;
int targetHeight = 800;

if(sourceImage.Height <= 800 && sourceImage.Width <= 800) {
targetHeight = sourceImage.Height;
targetWidth = sourceImage.Width;
} else if(sourceImage.Height > sourceImage.Width) {
targetWidth = sourceImage.Width * 800 / sourceImage.Height;
} else {
targetHeight = sourceImage.Height * 800 / sourceImage.Width;
}

// 缩放图片
Image targetImage = Image.FromHbitmap(new Bitmap(targetWidth, targetHeight, PixelFormat.Format32bppRgb).GetHbitmap());
Graphics g = Graphics.FromImage(targetImage);
g.DrawImage(sourceImage, 0, 0, targetWidth, targetHeight);
g.Dispose();
// 设置输出格式
EncoderParameters encParams = new EncoderParameters(1);
encParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 65L);
ImageCodecInfo codeInfo = null;
ImageCodecInfo[] codeInfos = ImageCodecInfo.GetImageEncoders();
foreach(ImageCodecInfo info in codeInfos) {
if(info.MimeType.Equals("image/jpeg")) {
codeInfo = info;
break;
}
}
if(codeInfo != null) {
targetImage.Save(filename, codeInfo, encParams);
}
targetImage.Dispose();
}

/// <summary>
/// 生成缩略图
/// 可以改写成输出到OutputSteam
/// </summary>
/// <param name="sourceImage">原图</param>
/// <param name="thumbWidth">缩略图宽度</param>
/// <param name="thumbHeight">缩略图高度</param>
/// <param name="filename">缩略图的保存文件名</param>
public static void CreateThumb(Image sourceImage, int thumbWidth, int thumbHeight, string filename) {
int tw = thumbWidth;
int th = thumbHeight;

if(sourceImage.Height < th && sourceImage.Width < tw) {
th = sourceImage.Height;
tw = sourceImage.Width;
} else if(sourceImage.Height / th > sourceImage.Width / tw) {
tw = sourceImage.Width * th / sourceImage.Height;
} else {
th = sourceImage.Height * tw / sourceImage.Width;
}

// 将图片缩放到一个空白背景的图片上,生成大小一致的缩略图
Image thumbImage = Image.FromHbitmap(new Bitmap(thumbWidth, thumbHeight, PixelFormat.Format32bppRgb).GetHbitmap());
Graphics g = Graphics.FromImage(thumbImage);
SolidBrush brush = new SolidBrush(Color.White);
g.FillRectangle(brush, 0, 0, thumbWidth, thumbHeight);
g.DrawImage(sourceImage, (thumbWidth - tw) / 2, (thumbHeight - th) / 2, tw, th);
g.Dispose();

thumbImage.Save(filename, ImageFormat.Jpeg);
thumbImage.Dispose();
}
}
}

评论已关闭