從網(wǎng)上收集后自己寫的一個(gè)方法;
1.首先是一個(gè)根據(jù)分辨率壓縮的類,首先對(duì)圖片進(jìn)行一次壓縮
/** * 根據(jù)分辨率壓縮圖片比例 * * @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.第二就是循環(huán)對(duì)圖片的壓縮,直到壓縮到指定的大小以下為止(重要!)
/** * 根據(jù)分辨率壓縮 * * @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);//質(zhì)量壓縮方法,這里100表示不壓縮,把壓縮后的數(shù)據(jù)存放到baos中 Log.i(TAG, "圖片分辨率壓縮后:" + baos.toByteArray().length / 1024 + "KB"); while (baos.toByteArray().length > ImageSize * 1024) { //循環(huán)判斷如果壓縮后圖片是否大于ImageSize kb,大于繼續(xù)壓縮 subtract = setSubstractSize(baos.toByteArray().length / 1024); baos.reset();//重置baos即清空baos options -= subtract;//每次都減少10 bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//這里壓縮options%,把壓縮后的數(shù)據(jù)存放到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 }在這其中
/** * 根據(jù)圖片的大小設(shè)置壓縮的比例,提高速度 * * @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; } }這個(gè)方法用來動(dòng)態(tài)設(shè)置每次壓縮的比例,主要用于提升壓縮的時(shí)間,這其中的數(shù)值是我大概測試出來的可以修改成你認(rèn)為比較合適的
3.最后
壓縮圖片費(fèi)時(shí)又費(fèi)內(nèi)存,很明顯執(zhí)行的時(shí)候需要在子線程中完成,如果需要的話可以加一個(gè)壓縮完成的監(jiān)聽
下載地址:CommonUtils.rar
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注