C#无损高质量压缩图片代码
程序员文章站
2023-11-05 15:07:58
本文实例为大家分享了c#无损高质量压缩图片的具体代码,供大家参考,具体内容如下
/// 无损压缩图片
///
本文实例为大家分享了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(color.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), 0, 0, 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(); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。