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;
    }

}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值