以前一直作web項目,對圖片的處理通常僅限於作縮略圖,裁切,水印等,最近在給APP寫API,裏邊有使用圖片的功能,可是APP開發的同事抱怨說圖片太大,加載太慢web
首先,檢查原圖大小,一看3M多,作縮略圖,作完仍是有1M多,怎麼辦?ide
網上搜質量壓縮的方法,功夫不負苦心人啊,還真被我搜到了spa
很少說,貼代碼作記錄3d
/// <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,好了,能夠了,收工code