志在指尖
用双手敲打未来

C#高质量无损压缩图片代码同享

///无损紧缩图片
///
///原图片地址
///紧缩后保存图片地址
///紧缩质量(数字越小紧缩率越高)1-100
///紧缩后图片的最大巨细
///是否是第一次调用
///
publicstaticboolCompressImage(stringsFile,stringdFile,intflag=90,intsize=300,boolsfsc=true)
{
ImageiSource=Image.FromFile(sFile);
ImageFormattFormat=iSource.RawFormat;
//如果是第一次调用,原始图画的巨细小于要紧缩的巨细,则直接仿制文件,并且回来true
FileInfofirstFileInfo=newFileInfo(sFile);
if(sfsc==true&&firstFileInfo.Length<size*1024)
{
firstFileInfo.CopyTo(dFile);
returntrue;
}
intdHeight=iSource.Height/2;
intdWidth=iSource.Width/2;
intsW=0,sH=0;
//按份额缩放
Sizetem_size=newSize(iSource.Width,iSource.Height);
if(tem_size.Width>dHeight||tem_size.Width>dWidth)
{
if((tem_size.Width*dHeight)>(tem_size.Width*dWidth))
{
sW=dWidth;
sH=(dWidth*tem_size.Height)/tem_size.Width;
}
else
{
sH=dHeight;
sW=(tem_size.Width*dHeight)/tem_size.Height;
}
}
else
{
sW=tem_size.Width;
sH=tem_size.Height;
}
Bitmapob=newBitmap(dWidth,dHeight);
Graphicsg=Graphics.FromImage(ob);
g.Clear(Color.WhiteSmoke);
g.CompositingQuality=System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode=System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(iSource,newRectangle((dWidth-sW)/2,(dHeight-sH)/2,sW,sH),0,0,iSource.Width,iSource.Height,GraphicsUnit.Pixel);
g.Dispose();c#
//以下代码为保存图片时,设置紧缩质量
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<arrayICI.Length;x++)
{
if(arrayICI[x].FormatDescription.Equals(“JPEG”))
{
jpegICIinfo=arrayICI[x];
break;
}
}
if(jpegICIinfo!=null)
{
ob.Save(dFile,jpegICIinfo,ep);//dFile是紧缩后的新途径
FileInfofi=newFileInfo(dFile);
if(fi.Length>1024*size)
{
flag=flag-10;
CompressImage(sFile,dFile,flag,size,false);
}
}
else
{
ob.Save(dFile,tFormat);
}
returntrue;
}
catch
{
returnfalse;
}
finally
{
iSource.Dispose();
ob.Dispose();
}
}

未经允许不得转载:IT技术网站 » C#高质量无损压缩图片代码同享
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

志在指尖 用双手敲打未来

登录/注册IT技术大全

热门IT技术

C#基础入门   SQL server数据库   系统SEO学习教程   WordPress小技巧   WordPress插件   脚本与源码下载