国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

android 將圖片壓縮到指定的大小的示例

2019-12-12 03:43:25
字體:
來源:轉載
供稿:網友

從網上收集后自己寫的一個方法;

1.首先是一個根據分辨率壓縮的類,首先對圖片進行一次壓縮

  /**  * 根據分辨率壓縮圖片比例  *  * @param imgPath  * @param w  * @param h  * @return  */ private static Bitmap compressByResolution(String imgPath, int w, int h) {  BitmapFactory.Options opts = new BitmapFactory.Options();  opts.inJustDecodeBounds = true;  BitmapFactory.decodeFile(imgPath, opts);  int width = opts.outWidth;  int height = opts.outHeight;  int widthScale = width / w;  int heightScale = height / h;  int scale;  if (widthScale < heightScale) { //保留壓縮比例小的   scale = widthScale;  } else {   scale = heightScale;  }  if (scale < 1) {   scale = 1;  }  Log.i(TAG,"圖片分辨率壓縮比例:" + scale);  opts.inSampleSize = scale;  opts.inJustDecodeBounds = false;  Bitmap bitmap = BitmapFactory.decodeFile(imgPath, opts);  return bitmap; }

2.第二就是循環對圖片的壓縮,直到壓縮到指定的大小以下為止(重要!)

 /**  * 根據分辨率壓縮  *  * @param srcPath 圖片路徑  * @param ImageSize 圖片大小 單位kb  * @return  */ public static boolean compressBitmap(String srcPath, int ImageSize, String savePath) {  int subtract;  Log.i(TAG, "圖片處理開始..");  Bitmap bitmap = compressByResolution(srcPath, 1024, 720); //分辨率壓縮  if (bitmap == null) {   Log.i(TAG, "bitmap 為空");   return false;  }  ByteArrayOutputStream baos = new ByteArrayOutputStream();  int options = 100;  bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//質量壓縮方法,這里100表示不壓縮,把壓縮后的數據存放到baos中  Log.i(TAG, "圖片分辨率壓縮后:" + baos.toByteArray().length / 1024 + "KB");  while (baos.toByteArray().length > ImageSize * 1024) { //循環判斷如果壓縮后圖片是否大于ImageSize kb,大于繼續壓縮   subtract = setSubstractSize(baos.toByteArray().length / 1024);   baos.reset();//重置baos即清空baos   options -= subtract;//每次都減少10   bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//這里壓縮options%,把壓縮后的數據存放到baos中   Log.i(TAG, "圖片壓縮后:" + baos.toByteArray().length / 1024 + "KB");  }  Log.i(TAG, "圖片處理完成!" + baos.toByteArray().length / 1024 + "KB");  try {   FileOutputStream fos = new FileOutputStream(new File(savePath));//將壓縮后的圖片保存的本地上指定路徑中   fos.write(baos.toByteArray());   fos.flush();   fos.close();  } catch (Exception e) {   e.printStackTrace();  }  if (bitmap != null) {   bitmap.recycle();  }  return true; //壓縮成功返回ture }

在這其中 

 /**  * 根據圖片的大小設置壓縮的比例,提高速度  *  * @param imageMB  * @return  */ private static int setSubstractSize(int imageMB) {  if (imageMB > 1000) {   return 60;  } else if (imageMB > 750) {   return 40;  } else if (imageMB > 500) {   return 20;  } else {   return 10;  } }

這個方法用來動態設置每次壓縮的比例,主要用于提升壓縮的時間,這其中的數值是我大概測試出來的可以修改成你認為比較合適的

3.最后

壓縮圖片費時又費內存,很明顯執行的時候需要在子線程中完成,如果需要的話可以加一個壓縮完成的監聽

下載地址:CommonUtils_jb51.rar

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 滨州市| 准格尔旗| 金坛市| 水城县| 大埔区| 木里| 茶陵县| 仙桃市| 德保县| 射阳县| 渑池县| 中卫市| 海伦市| 松原市| 嘉兴市| 铜山县| 奈曼旗| 溆浦县| 金溪县| 岱山县| 华蓥市| 龙游县| 镇远县| 财经| 临沭县| 周至县| 富阳市| 治县。| 奉新县| 岱山县| 玉溪市| 灌阳县| 驻马店市| 罗甸县| 昭觉县| 图们市| 宜兴市| 彰化县| 都匀市| 报价| 霍山县|