1. 程式人生 > >壓縮圖片至指定大小

壓縮圖片至指定大小

public class BitmapUtil {
    /**
     *
     * @param bitmap
     * @param maxSize 當傳入的bitmap的大小大於maxSize時,壓縮圖片至maxSize
     * @return
     */
    public static Bitmap getCompressedBitmap(Bitmap bitmap,double maxSize) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100
, baos); byte[] b = baos.toByteArray(); //將位元組換成KB double mid = b.length / 1024; if (mid > maxSize) { double i = mid / maxSize; return compressBitmap(bitmap, bitmap.getWidth() / Math.sqrt(i), bitmap.getHeight() / Math.sqrt(i)); } return
bitmap; } private static Bitmap compressBitmap(Bitmap bitmap, double newWidth, double newHeight) { float width = bitmap.getWidth(); float height = bitmap.getHeight(); Matrix matrix = new Matrix(); float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float
) newHeight) / height; matrix.postScale(scaleWidth, scaleHeight); return Bitmap.createBitmap(bitmap, 0, 0, (int) width, (int) height, matrix, true); } }