之前一直做web项目,对图片的处理一般仅限于做缩略图,裁切,水印等,最近在给APP写API,里边有使用图片的功能,但是APP开发的同事抱怨说图片太大,加载太慢
首先,检查原图大小,一看3M多,做缩略图,做完还是有1M多,怎么办?
网上搜质量压缩的方法,功夫不负苦心人啊,还真被我搜到了
不多说,贴代码做记录
/// <summary> /// 图片质量压缩 /// </summary> /// <param name="stream">图片流</param> /// <param name="flag">压缩比例 1-100 </param> /// <returns></returns> public static Stream GetPicThumbnail(Stream stream, int flag) { var newStream = new MemoryStream(); System.Drawing.Image iSource = System.Drawing.Image.FromStream(stream); ImageFormat tFormat = iSource.RawFormat; //以下代码为保存图片时,设置压缩质量 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) { iSource.Save(newStream, jpegICIinfo, ep);//dFile是压缩后的新路径 } else { iSource.Save(newStream, tFormat); } } catch (Exception ex) { } finally { iSource.Dispose(); iSource.Dispose(); } return newStream; }
/// <summary> /// 压缩比例 /// </summary> /// <param name="length"></param> /// <param name="refSize"></param> /// <returns></returns> public static int GetFlag(long length, int refSize) { var size = (int)length / 1024; var flag = 100; if (size > refSize) { flag = refSize * 100 / size; if (flag < 20) flag = 20; } return flag; }
压缩完成之后,再看图片大小,80K,好了,可以了,收工