.net Graphics 生成的图片文件非常大,如何解决这一问题?
我用.net 的Graphics 做裁剪图片的功能,发现.net生成出来的图片比我的原始图片大小大了5倍左右(原始图片129kb,高宽:1003*600;生成的图片764kb,高宽:1003*600)。
之前还不清楚为什么网页的图片加载很慢,后来认真一看,原来图片大小已经扩大了好多倍。
请高人指点,.net如何处理图片裁剪,既能不影响图片质量,又能保证生成图片大小?
源代码是这样的:
System.Drawing.Image originalImage = System.Drawing.Image.FromFile(imgPath);
//新建一个bmp图片
System.Drawing.Image bitmap = new System.Drawing.Bitmap(thumWidth, thumHeight);
//新建一个画板
System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmap);
//设置高质量查值法
graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//清空画布并以透明背景色填充
graphic.Clear(System.Drawing.Color.Transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
graphic.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, thumWidth, thumHeight), new System.Drawing.Rectangle(x, y, originalWidth, originalHeight), System.Drawing.GraphicsUnit.Pixel);
//开始返回图片
System.IO.MemoryStream ms = new System.IO.MemoryStream();
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
try
{
bitmap.Save(newname);
}
catch { }
originalImage.Dispose();
bitmap.Dispose();
graphic.Dispose();
try
{
Graphics g = Graphics.FromImage(b);
g.InterpolationMode = InterpolationMode.High;
g.SmoothingMode = SmoothingMode.HighQuality;
g.CompositingQuality = CompositingQuality.HighQuality;
//清除整个绘图面并以透明背景色填充
g.Clear(Color.Transparent);
if (width < height)
g.DrawImage(image, new Rectangle(0, 0, newSize, newSize), new Rectangle(0, (height - width) / 2, width, width), GraphicsUnit.Pixel);
else
g.DrawImage(image, new Rectangle(0, 0, newSize, newSize), new Rectangle((width - height) / 2, 0, height, height), GraphicsUnit.Pixel);
SaveImage(b, newFileName, GetCodecInfo("image/" + GetFormat(fileName).ToString().ToLower()));
}
finally
{
image.Dispose();
b.Dispose();
}
}
/// <summary>
/// 保存图片
/// </summary>
/// <param name="image">Image 对象</param>
/// <param name="savePath">保存路径</param>
/// <param name="ici">指定格式的编解码参数</param>
private static void SaveImage(Image image, string savePath, ImageCodecInfo ici)
{
//设置 原图片 对象的 EncoderParameters 对象
EncoderParameters parameters = new EncoderParameters(1);
parameters.Param[0] = new EncoderParameter(Encoder.Quality, ((long)100));
image.Save(savePath, ici, parameters);
parameters.Dispose();
}
/// <summary>
/// 获取图像编码解码器的所有相关信息
/// </summary>
/// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>
/// <returns>返回图像编码解码器的所有相关信息</returns>
private static ImageCodecInfo GetCodecInfo(string mimeType)
{
ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo ici in CodecInfo)
{
if (ici.MimeType == mimeType)
return ici;
}
return null;
}