一:實現過程
使用以下代碼壓縮循環壓縮
/** * 質量壓縮方法 * * @param image * @return */ public static File compressImage(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 質量壓縮方法,這里100表示不壓縮,把壓縮后的數據存放到baos中 int options = 90; while (baos.size() > 153600) { // 循環判斷如果壓縮后圖片是否大於150kb,大於繼續壓縮 baos.reset(); // 重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 這里壓縮options%,把壓縮后的數據存放到baos中 options = options - 10;// 每次都減少10 } UtilsLog.e(options + " " + baos.size()); String sdCardDir = Environment.getExternalStorageDirectory() + "/qcjrHuaXia/"; File file = null; try { File dirFile = new File(sdCardDir); if (!dirFile.exists()) { //如果不存在,那就建立這個文件夾 dirFile.mkdirs(); } String fileName = String.valueOf(System.currentTimeMillis()); file = new File(sdCardDir, fileName + ".jpg"); FileOutputStream fos = new FileOutputStream(file); baos.writeTo(fos); fos.flush(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } UtilsLog.e(" options123-->" + file.length()); return file; }
代碼雖然只控制了不能大於150Kb,但是出來的圖片大小幾乎都符合我需求的100kb~150Kb范圍內,因為他每次都壓縮質量不是很大。
二:遇到的問題
雖然上面內實現圖片壓縮,但是超過1MB的圖片,壓縮會很慢。然而現在手機拍出的圖片幾乎都是6MB左右的樣子。
所以為了優化節省壓縮時間,我采用了,
先通過在github上找的圖片壓縮工具CompressHelper,(附上地址 https://github.com/nanchen2251/CompressHelper)
先把超過1MB的圖片壓縮一下,更改了默認的壓縮設置防止其壓縮率太大.
public File compressToFile(File file, int num) { return BitmapUtil.compressImage(context, Uri.fromFile(file), 1080, 1920, compressFormat, bitmapConfig, num, destinationDirectoryPath, fileNamePrefix, fileName); }
之后在把這個壓縮后的圖片,在進行循環壓縮,就很快了。
需求達成。