/** * 壓縮圖片(質量壓縮) * @param bitmap */ public static File comPRessImage(Bitmap bitmap) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//質量壓縮方法,這里100表示不壓縮,把壓縮后的數據存放到baos中 int options = 100; while (baos.toByteArray().length / 1024 > 500) { //循環判斷如果壓縮后圖片是否大于500kb,大于繼續壓縮 baos.reset();//重置baos即清空baos options -= 10;//每次都減少10 bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//這里壓縮options%,把壓縮后的數據存放到baos中 long length = baos.toByteArray().length; } SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); Date date = new Date(System.currentTimeMillis()); String filename = format.format(date); File file = new File(Environment.getExternalStorageDirectory(),filename+".png"); try { FileOutputStream fos = new FileOutputStream(file); try { fos.write(baos.toByteArray()); fos.flush(); fos.close(); } catch (IOException e) { BAFLogger.e(TAG,e.getMessage()); e.printStackTrace(); } } catch (FileNotFoundException e) { BAFLogger.e(TAG,e.getMessage()); e.printStackTrace(); } recycleBitmap(bitmap); return file; }//釋放
public static void recycleBitmap(Bitmap... bitmaps) { if (bitmaps==null) { return; } for (Bitmap bm : bitmaps) { if (null != bm && !bm.isRecycled()) { bm.recycle(); } } }
新聞熱點
疑難解答