Android圖片壓縮—可按照圖片大小壓縮

簡介:最近在做圖片上傳的相關功能,需要對圖片的大小和尺寸進行壓縮處理。

好處:(1)提升性能(2)節省流量

一、圖片大小循環壓縮

/**
     * 壓縮圖片文件到指定大小
     *
     * @param filePath
     */
    public static void compressBmpToFile(String filePath) {
        Bitmap bitmap = BitmapFactory.decodeFile(filePath);
        if (null == bitmap) {
            return;
        }
        final int BYTE_LEN = 1024;
        //文件最大爲200KB
        final int MAX_FILE_SIZE = 256;
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int quality = 90;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        while (baos.toByteArray().length / BYTE_LEN > MAX_FILE_SIZE) {
            baos.reset();
            quality -= 10;
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            float size = calculteBitmapSize(bitmap);
        }
        try {
            final FileOutputStream fos = new FileOutputStream(new File(filePath));
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
/**
     * 計算bitmap的大小
     *
     * @param bitmap
     * @return bitmap的大小單位KB
     */
    public static float calculteBitmapSize(Bitmap bitmap) {
        if (null == bitmap) {
            return 0.0f;
        }
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        final float size = (baos.toByteArray().length / 1024);
        try {
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return size;
    }

二、圖片尺寸壓縮

/**
     * 壓縮圖片的尺寸
     *
     * @param srcPath
     * @return
     */
    public static Bitmap compressImageFromFile(String srcPath) {
        final BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //只讀邊,不讀內容
        newOpts.inJustDecodeBounds = true;
        // 獲取這個圖片的寬和高,注意此處的bitmap爲null
        BitmapFactory.decodeFile(srcPath, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        float hh = 800f;
        float ww = 480f;
        int be = 1;
        if (w > h && w > ww) {
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0) {
            be = 1;
        }
        //設置採樣率
        newOpts.inSampleSize = be;
        //該模式是默認的,可不設
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        // 同時設置纔會有效
        newOpts.inPurgeable = true;
        //當系統內存不夠時候圖片自動被回收
        newOpts.inInputShareable = true;
        final Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return bitmap;
    }

三、Luban壓縮

Github:Luban圖片壓縮

四、圖片選擇器

PictureSelector圖片選擇器

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章