c# 如何实现图片压缩
一般在web应用中,对客户端提交上来的图片肯定需要进行压缩的。尤其是比较大的图片,如果不经过压缩会导致页面变的很大,打开速度比较慢,当然了如果是需要高质量的图片也得需要生产缩略图。
一般在web应用中,对客户端提交上来的图片肯定需要进行压缩的。尤其是比较大的图片,如果不经过压缩会导致页面变的很大,打开速度比较慢,当然了如果是需要高质量的图片也得需要生产缩略图。
下面贴出我自己琢磨的图片压缩算法,首先这个是未经优化的简单实现:
代码如下:
publicstaticSystem.Drawing.ImageGetImageThumb(System.Drawing.ImagesourceImg,intwidth,intheight)
{
System.Drawing.ImagetargetImg=newSystem.Drawing.Bitmap(width,height);
using(System.Drawing.Graphicsg=System.Drawing.Graphics.FromImage(targetImg))
{
g.InterpolationMode=System.Drawing.Drawing2D.InterpolationMode.High;
g.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode=System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.CompositingQuality=System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.PixelOffsetMode=System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.DrawImage(sourceImg,newSystem.Drawing.Rectangle(0,0,width,height),newSystem.Drawing.Rectangle(0,0,sourceImg.Width,sourceImg.Height),System.Drawing.GraphicsUnit.Pixel);
g.Dispose();
}
returntargetImg;
}
这个方法比较简单,用到的是高质量压缩。经过这个方法压缩后,200K的图片只能压缩到160k左右。经过改写代码实现了如下的方法:
代码如下:
publicBitmapGetImageThumb(Bitmapmg,SizenewSize)
{
doubleratio=0d;
doublemyThumbWidth=0d;
doublemyThumbHeight=0d;
intx=0;
inty=0;
Bitmapbp;
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);
SizethumbSize=newSize((int)newSize.Width,(int)newSize.Height);
bp=newBitmap(newSize.Width,newSize.Height);
x=(newSize.Width-thumbSize.Width)/2;
y=(newSize.Height-thumbSize.Height);
System.Drawing.Graphicsg=Graphics.FromImage(bp);
g.SmoothingMode=SmoothingMode.HighQuality;
g.InterpolationMode=InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode=PixelOffsetMode.HighQuality;
Rectanglerect=newRectangle(x,y,thumbSize.Width,thumbSize.Height);
g.DrawImage(mg,rect,0,0,mg.Width,mg.Height,GraphicsUnit.Pixel);
returnbp;
}
这样实现的压缩使压缩率大幅度上升。其实代码并没有变多少,最主要的是在保存的时候要是用jpg格式,如果不指定格式,默认使用的是png格式。
下面这个是根据设置图片质量数值来压缩图片写的的方法:
代码如下:
publicstaticboolGetPicThumbnail(stringsFile,stringoutPath,intflag)
{
System.Drawing.ImageiSource=System.Drawing.Image.FromFile(sFile);
ImageFormattFormat=iSource.RawFormat;
//以下代码为保存图片时,设置压缩质量
EncoderParametersep=newEncoderParameters();
long[]qy=newlong[1];
qy[0]=flag;//设置压缩的比例1-100
EncoderParametereParam=newEncoderParameter(System.Drawing.Imaging.Encoder.Quality,qy);
ep.Param[0]=eParam;
try
{
ImageCodecInfo[]arrayICI=ImageCodecInfo.GetImageEncoders();
ImageCodecInfojpegICIinfo=null;
for(intx=0;x
以上就是c#如何实现图片压缩的详细内容,更多关于c#图片压缩的资料请关注毛票票其它相关文章!