Android 圖片壓縮

通過本地的圖片URL,獲取壓縮的圖片文件,提高上傳速度:

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;

import java.io.*;

/**
 * Created by Jiaxuon 2016/3/22.
 */
public class ImageFactory {
    private ImageFactory() {
    }

    private static ImageFactory mInstance = null;

    public static ImageFactory getInstance() {
        if (mInstance == null) {
            mInstance = new ImageFactory();
        }
        return mInstance;
    }

    /**
     * 通過文件本地URL,獲取壓縮後的圖片
     *
     * @param path
     * @param fileName
     * @param width
     * @param height
     * @return
     */
    public File getZoomImageFile(String path, String fileName, int width, int height) {
        byte[] bytes = compressImage(getZoomBitmap(path, width, height));
        File file = getImageFileFromBytes(bytes, fileName);
        return file;
    }

    /**
     * 通過文件本地URL,獲取壓縮後的圖片 ,默認圖片寬高是720*1280
     *
     * @param fileName
     * @param path
     * @return
     */
    public File getZoomImageFile(String path, String fileName) {
        byte[] bytes = compressImage(getZoomBitmap(path, 720, 1280));
        File file = getImageFileFromBytes(bytes, fileName);
        return file;
    }

    /**
     * 根據byte數組,生成文件
     */
    public File getImageFileFromBytes(byte[] bfile, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File tempFile = null;
        try {
            tempFile = File.createTempFile(fileName, ".jpg");
            fos = new FileOutputStream(tempFile);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            tempFile.deleteOnExit();
        }
        return tempFile;
    }

    /**
     * 將給定的bitmap文件壓縮到指定大小
     *
     * @param image
     * @return
     */
    private byte[] compressImage(Bitmap image) {
        if (image == null) return null;

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//質量壓縮方法,這裏100表示不壓縮,把壓縮後的數據存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) {  //循環判斷如果壓縮後圖片是否大於100kb,大於繼續壓縮
            options -= 10;//每次都減少10
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//這裏壓縮options%,把壓縮後的數據存放到baos中
        }
        return baos.toByteArray();
    }

    /**
     * 得到縮放的bitmap
     */
    public Bitmap getZoomBitmap(String path, int width, int height) {
        Bitmap bitmap = null;
        int sampleSize = 1;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;// 不加載bitmap到內存中
        BitmapFactory.decodeFile(path, options);
        sampleSize = calculateInSampleSize(options, width, height);
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inSampleSize = sampleSize;
        options.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(path, options);
        bitmap = rotaingImageView(readPictureDegree(path), bitmap);

        return bitmap;

    }

    /**
     * 得到options.inSampleSize的值
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    private int calculateInSampleSize(BitmapFactory.Options options,
                                      int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            // Calculate the largest inSampleSize value that is a power of 2 and
            // keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

    /**
     * 讀取圖片屬性:旋轉的角度
     *
     * @param path 圖片絕對路徑
     * @return degree旋轉的角度
     */
    private int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /*
     * 旋轉圖片
     *
     * @param angle
     *
     * @param bitmap
     *
     * @return Bitmap
     */
    private Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        if (bitmap == null)
            return null;
        // 旋轉圖片 動作
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        // matrix.setRotate(0);
        // 創建新的圖片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }

}


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