本文实例为大家分享了C#无损高质量压缩图片的具体代码,供大家参考,具体内容如下
/// 无损压缩图片 /// <param name="sfile">原图片</param> /// <param name="dfile">压缩后保存位置</param> /// <param name="dHeight">高度</param> /// <param name="DWIDth"></param> /// <param name="flag">压缩质量(数字越小压缩率越高) 1-100</param> /// <returns></returns> public static bool GetPicthumbnail(string sfile,string dfile,int dHeight,int DWIDth,int flag) { System.Drawing.Image iSource = System.Drawing.Image.Fromfile(sfile); ImageFormat tFormat = iSource.RawFormat; int sW = 0,sH = 0; //按比例缩放 Size tem_size = new Size(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; } Bitmap ob = new Bitmap(DWIDth,dHeight); Graphics g = Graphics.FromImage(ob); g.Clear(@R_403_6004@.WhiteSmoke); g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(iSource,new Rectangle((DWIDth - sW) / 2,(dHeight - sH) / 2,sW,sH),iSource.WIDth,iSource.Height,GraphicsUnit.Pixel); g.dispose(); //以下代码为保存图片时,设置压缩质量 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) { ob.Save(dfile,jpegICIinfo,ep);//dfile是压缩后的新路径 } else { ob.Save(dfile,tFormat); } return true; } catch { return false; } finally { iSource.dispose(); ob.dispose(); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
总结以上是内存溢出为你收集整理的C#无损高质量压缩图片代码全部内容,希望文章能够帮你解决C#无损高质量压缩图片代码所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)