图片压缩

来源:互联网 发布:无线传感器网络 孙利民 编辑:程序博客网 时间:2024/05/24 06:52
/**
     * 计算inSampleSize,用于压缩图片
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options,
            int reqWidth, int reqHeight) {
        // 源图片的宽度
        int width = options.outWidth;
        int height = options.outHeight;
        int inSampleSize = 1;


        // int min = Math.min(width, height);
        // int maxReq = Math.max(reqWidth, reqHeight);


        // if(min > maxReq) {
        //     inSampleSize = Math.round((float) min / (float) maxReq);
        // }


        // 通过之前的计算方法,在加载类似400*4000这种长图时会内存溢出
        if (width > reqWidth || height > reqHeight) {
            int widthRadio = Math.round(width * 1.0f / reqWidth);
            int heightRadio = Math.round(height * 1.0f / reqHeight);


            inSampleSize = Math.max(widthRadio, heightRadio);
        }
        if (Debug)
        {
            LogUtil.i(TAG, "calculateInSampleSize--->inSampleSize:" + inSampleSize);
        }
        return inSampleSize;
    }


    /**
     * 根据计算的inSampleSize,得到压缩后图片
     *
     * @param pathName
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static Bitmap decodeSampledBitmapFromFile(String pathName,
            int reqWidth, int reqHeight) {
        // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(pathName, options);
        // 调用上面定义的方法计算inSampleSize值
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);
        // 使用获取到的inSampleSize值再次解析图片
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(pathName, options);


        return bitmap;
    }
0 0