c# 文件服务器压缩图片,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

{

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();c3c241ec0d3b8400f4b8b7a8df17fe9e.png

//以下代码为保存图片时,设置紧缩质量

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

{

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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值