標籤:java android 圖片 壓縮 bitmap
這兩天改進最佳化項目中圖片上傳的代碼,考慮到可能有7、8M的比較大的圖片,因為要先進行壓縮。所以設計到檔案的壓縮,儲存與清空刪除操作。在這裡記下筆記。
/** * 壓縮並另存新檔,每次先清空再儲存 */private void compressFile(){//清空儲存目錄下的舊照片String saveDir = Environment.getExternalStorageDirectory()+ "/bag/uploadPictures";File imageDir = new File(saveDir);if (imageDir.exists()) {clearFolder(imageDir);}else{imageDir.mkdirs();}//判斷圖片大小,大於300k則壓縮for (int i = 0; i < imagePathList.size(); i++) {Bitmap bitmap = compressImage(imagePathList.get(i));imagePathList.set(i, saveImage(saveDir,bitmap));}}/**儲存圖片,輸入儲存目錄和bitmap,以日期命名,返回儲存路徑 * * @param path * @param bitmap * @return */private String saveImage(String path ,Bitmap bitmap){ Date dt = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String imageName =sdf.format(dt)+".jpg"; File file = new File(path,imageName ); if (file.exists()) { file.delete(); } try { FileOutputStream out = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); out.flush(); out.close(); Log.d(TAG, "圖片已經儲存"); return path+"/"+imageName; } catch (FileNotFoundException e) { Log.d(TAG, "檔案不存在"); e.printStackTrace(); return ""; } catch (IOException e) { Log.d(TAG, "IO異常"+e.toString()); e.printStackTrace(); return ""; }}/** * 壓縮圖片 * @param imagePath * @return */private Bitmap compressImage(String imagePath) {PhotoUpBitmapCache bitmapCache = new PhotoUpBitmapCache();//取1280*720大小Bitmap image = bitmapCache.revitionImage(imagePath, 1280,720);//用下面這個行代碼會造成OOM,所以必須用Android 內建的方法去先壓縮再匯入//Bitmap image = BitmapFactory.decodeFile(imagePath);ByteArrayOutputStream baos = new ByteArrayOutputStream();image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//品質壓縮方法,這裡100表示不壓縮,把壓縮後的資料存放到baos中int options = 100;while ( baos.toByteArray().length /1024 > 300) {//迴圈判斷如果壓縮後圖片是否大於100kb,大於繼續壓縮baos.reset();//重設baos即清空baosimage.compress(Bitmap.CompressFormat.JPEG, options, baos);//這裡壓縮options%,把壓縮後的資料存放到baos中options -= 5;//每次都減少5%}ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把壓縮後的資料baos存放到ByteArrayInputStream中Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream資料產生圖片 Log.d(TAG, "檔案壓縮成功");return bitmap;}/** * 清空檔案夾裡面所有子檔案 */ private void clearFolder(File file) { if(file.isDirectory()){ File[] childFiles = file.listFiles(); if (childFiles == null || childFiles.length == 0) { return; } for (int i = 0; i < childFiles.length; i++) { childFiles[i].delete(); } return ; } }
Android筆記之 檔案儲存、壓縮與清空刪除