BitmapUtils

来源:互联网 发布:edg那个知恩是谁 编辑:程序博客网 时间:2024/06/04 22:47


package com.zdsoft.testthree.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Created by Administrator on 2017/3/24.
 */
public class BitmapUtils {

    /**
     *尺寸压缩
     * @param imgPath 文件路径
     * @param pixelW  压缩后的宽度
     * @param pixelH  压缩后的高度
     * @return
     */
    public static Bitmap ratio(String imgPath, float pixelW, float pixelH) {
        //是用来装载图片的属性的
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片,此时把options.inJustDecodeBounds 设回true,即只读边不读内容
        newOpts.inJustDecodeBounds = true;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        // 获得图片的信息,但是返回的bitmap对象是空对象
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath,newOpts);

        newOpts.inJustDecodeBounds = false;
        //获得图片的宽度可高度
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // 想要缩放的目标尺寸
        float hh = pixelH;// 设置高度为240f时,可以明显看到图片缩小了
        float ww = pixelW;// 设置宽度为120f,可以明显看到图片缩小了
        // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (w / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据高度固定大小缩放
            be = (int) (h / hh);
        }
        if (be <= 0)
        {
            be = 1;
        }
        newOpts.inSampleSize = be;//设置缩放比例
        // 开始压缩图片,注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(imgPath, newOpts);
        // 压缩好比例大小后再进行质量压缩
//        return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大,反而耗资源,删除
        return bitmap;
    }


    /**
     * 质量压缩
     * @param path   文件路径
     * @param maxSize 压缩后的文件大小 500kb
     * @return
     * @throws IOException
     */
    public static ByteArrayOutputStream compress(String path, int maxSize) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        // 压缩比 100表示不压缩 100%
        int options = 100;
        Bitmap image = BitmapFactory.decodeFile(path);
        // Store the bitmap into output stream(no compress)
        image.compress(Bitmap.CompressFormat.JPEG, options, os);
        // 循环压缩
        while ( os.toByteArray().length / 1024 > maxSize) {
            // Clean up os
            os.reset();
            // interval 10
            options -= 10;
            image.compress(Bitmap.CompressFormat.JPEG, options, os);
        }
        return  os;
    }

}

0 0