一般在web应用中,对客户端提交上来的图片肯定需要进行压缩的。尤其是比较大的图片,如果不经过压缩会导致页面变的很大,打开速度比较慢,当然了如果是需要高质量的图片也得需要生产缩略图。
下面贴出我自己琢磨的图片压缩算法,首先这个是未经优化的简单实现:
Bitmap bp;
if ((mg.Width / Convert.ToDouble(newSize.Width)) > (mg.Height /
Convert.ToDouble(newSize.Height)))
ratio = Convert.ToDouble(mg.Width) / Convert.ToDouble(newSize.Width);
else
ratio = Convert.ToDouble(mg.Height) / Convert.ToDouble(newSize.Height);
myThumbHeight = Math.Ceiling(mg.Height / ratio);
myThumbWidth = Math.Ceiling(mg.Width / ratio);
Size thumbSize = new Size((int)newSize.Width, (int)newSize.Height);
bp = new Bitmap(newSize.Width, newSize.Height);
x = (newSize.Width - thumbSize.Width) / 2;
y = (newSize.Height - thumbSize.Height);
System.Drawing.Graphics g = Graphics.FromImage(bp);
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
Rectangle rect = new Rectangle(x, y, thumbSize.Width, thumbSize.Height);
g.DrawImage(mg, rect, 0, 0, mg.Width, mg.Height, GraphicsUnit.Pixel);
return bp;
}
下面这个是园友写的根据设置图片质量数值来压缩图片的方法:
//以下代码为保存图片时,设置压缩质量
EncoderParameters ep = new EncoderParameters();
long[] qy = new long[1];
qy[0] = flag;//设置压缩的比例1-100
EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
ep.Param[0] = eParam;
try
{
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICIinfo = null;
for (int x = 0; x < arrayICI.Length; x++)
{
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICIinfo = arrayICI[x];
break;
}
}
if (jpegICIinfo != null)
{
iSource.Save(outPath, jpegICIinfo, ep);//dFile是压缩后的新路径
}
else
{
iSource.Save(outPath, tFormat);
}
return true;
}
catch
{
return false;
}
finally
{
iSource.Dispose();
iSource.Dispose();
}
}
新闻热点
疑难解答