最近项目遇到一个问题,就是图片压缩发送后,失真度太大,对方看不清图片。

当然,凡是压缩就会产生一定的失真度,只是度的大小问题而已,下面介绍一种,图片变小而尽量减少失真度的较好的方法(网上找的。实践之后觉得还行)。

/**
 * 根据路径获得图片并压缩返回bitmap用于显示
 * 
 * @param imagesrc
 * @return
 */
public static Bitmap getSmallBitmap(String filePath) {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize2(options, 480, 800);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    return BitmapFactory.decodeFile(filePath, options);
}
private static 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) {

// Calculate ratios of height and width to requested height and
// width
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);

// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }

        return inSampleSize;
    }

 

public static String save(String mCurrentPhotoPath) {

        String path = null ;
        File f = new File(mCurrentPhotoPath);
        try {

            Bitmap bm = getSmallBitmap(mCurrentPhotoPath);

            // 获取保存图片的目录
            File dir = new File(
                    Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    "jiankewang");
            // 获取保存 隐患检查的图片文件夹名称
            if (!dir.exists()) {
                dir.mkdirs();
            }
            
            FileOutputStream fos = new FileOutputStream(new File(
                    dir, "small_" + f.getName()));

            path = dir + "/small_" + f.getName();
            bm.compress(Bitmap.CompressFormat.JPEG, 90, fos);

        } catch (Exception e) {
            
        }

    return  path ;
}

 

posted on 2016-02-02 18:33  灯火、阑珊处  阅读(626)  评论(0编辑  收藏  举报