安卓里一个很好用的图片压缩方法

先说使用方法
根据图片的大小来定图片的压缩比例,然后下面代码中的90越小,图片清晰度越小,相应图片大小也越小
if ((!filepath.equals(“”)) && (Util.getImageSize(filepath) != 0.0)) {
new Thread(new Runnable() {

            @Override
            public void run() {
                Bitmap b = null;
                try {
                    Log.d("wly",
                            " 图片大小压缩前的 = " + Util.getImageSize(filepath));

                    int a = (int) Math.sqrt(Util.getImageSize(filepath) / 50);

if (a <= 1) {
b = Util.getCompressBitmapFromOrigalPath(filepath,
false, a);
} else {
b = Util.getCompressBitmapFromOrigalPath(filepath,
true, a);
}
Log.d(“wly”,
” a = ” + a + “=====Util.getImageSize(filepath)==” + Util.getImageSize(filepath)
+ “=======” + Math.sqrt(Util.getImageSize(filepath) / 50));

                    mZoomImgPath = Util.saveThumbNailPic(b, filepath);
                    Log.d("wly",
                            " 图片大小压缩后的 = " + Util.getImageSize(mZoomImgPath));
                } catch (Exception exception) {
                    exception.printStackTrace();
                } finally {
                    if (b != null && !b.isRecycled()) {
                        b.recycle();
                    }
                }
                mHandler.sendEmptyMessage(3);
            }
        }).start();
    } else {
        showToast(PostCardActivity.this, "请选择图片~");
    }

压缩图片的方法代码

/**
* 压缩图片
*
* @param path
* @param isScale
* @return
*/
public static Bitmap getCompressBitmapFromOrigalPath(String path,
boolean isScale, int scale) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
int degree = getBitmapDegree(path);
Bitmap retatedBitmap = null;
if (!isScale) {
return null;
} else {
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
Bitmap bitmapCompress = BitmapFactory.decodeFile(path, options);
if (degree != 0) {
retatedBitmap = rotateBitmapByDegree(bitmapCompress, degree);
} else {
retatedBitmap = bitmapCompress;
}
}

        return retatedBitmap;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

/**
 * 读取图片的旋转的角度
 *
 * @param path 图片绝对路径
 * @return 图片的旋转角度
 */
private static int getBitmapDegree(String path) {
    int degree = 0;
    try {
        // 从指定路径下读取图片,并获取其EXIF信息
        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 bm     需要旋转的图片
 * @param degree 旋转角度
 * @return 旋转后的图片
 */
private static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
    Bitmap returnBm = null;

    // 根据旋转角度,生成旋转矩阵
    Matrix matrix = new Matrix();
    matrix.postRotate(degree);
    try {
        // 将原始图片按照旋转矩阵进行旋转,并得到新的图片
        returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                bm.getHeight(), matrix, true);
    } catch (OutOfMemoryError e) {
    }
    if (returnBm == null) {
        returnBm = bm;
    }
    if (bm != returnBm) {
        bm.recycle();
    }
    return returnBm;
}

/**
 * Bitmap对象保存为图片文件; p 为原来路径如果不压缩返回原路径
 */
public static String saveThumbNailPic(Bitmap bitmap, String p) {
    String thumbPathDir = Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/smsmms/";// 存放压缩的目录
    File file = new File(thumbPathDir, "zoom.jpg");
    if (file.exists()) {
        file.delete();
    }
    if (bitmap == null) {
        // copyFile(p, file.getAbsolutePath());
        // return file.getAbsolutePath();
        return p;
    }
    BufferedOutputStream bos = null;
    try {
        File folder = new File(thumbPathDir);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        if (!file.exists()) {
            Log.d("dqvv", "Create the file:" + file.getPath());
            file.createNewFile();
        }
        bos = new BufferedOutputStream(new FileOutputStream(file));
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bos);
        bos.flush();
        Log.d("dqvv", "this compress file compressed success ");
    } catch (IOException e) {
        e.printStackTrace();
        Log.d("dqvv", "this compress file compressed fail ");
    } finally {
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    return file.getAbsolutePath();
}

public static double getImageSize(String path) {
    if (TextUtils.isEmpty(path)) {
        return 0;
    }
    File f = new File(path);
    Log.d("dqvv", "getImageSize " + f.canRead() + "," + f.canWrite());
    if (f.exists()) {
        long size = f.length();
        long size_k = size / 1024;
        double mb = size_k * 1.0 / 1024;
        Log.d("wly", " mb " + mb + "MB");
        if (mb > 1) {
            BigDecimal b = new BigDecimal(mb);
            double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .doubleValue();
            return f1 * 1024;
            // return f1 + "MB";
        } else
            return size_k;
        // return size_k + "KB";
    }
    return 0;
    // return 0 + "KB";
}

猜你喜欢

转载自blog.csdn.net/u013165058/article/details/53023554