android中Bitmap影象處理 修改圖片大小以及儲存時的檔案大小
阿新 • • 發佈:2019-02-03
Options options1 = new Options(); options1.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options1); options1.inSampleSize = RegisterTool.calculateInSampleSize(options1, 110, 160); //110,160:轉換後的寬和高,具體值會有些出入 options1.inJustDecodeBounds = false; Bitmap bitmap = BitmapFactory.decodeFile(filePath, options1); //filePath:檔案路徑
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio; } return inSampleSize; }
//壓縮圖片並將Bitmap儲存到本地
FileOutputStream out = new FileOutputStream(new File(filePath));
saveBitmap.compress(Bitmap.CompressFormat.JPEG, 60, out); //60代表壓縮40%