androidr图片压缩和保存本地

//读取本地图片如果不压缩很容易OOM
//尺寸压缩
BitmapFactory.Options options = new BitmapFactory.Options();
//为true表示decodeFile时只会返回宽和高,不用加载图片
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);

// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, 500, 500);

//读取图片
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);

if (bitmap == null) {
    return;
}
//质量压缩
ByteArrayOutputStream baos = null;
baos = new ByteArrayOutputStream();
int pro = 100;
// 循环判断如果压缩后图片是否大于100kb,大于继续压缩
do {
    baos.reset();
    bitmap.compress(Bitmap.CompressFormat.JPEG, pro, baos);
    pro -= 10;
} while (baos.toByteArray().length / 1024 > 100);

imageView.setImageBitmap(bitmap);


//定义一个file,为压缩后的图片   File f = new File("图片保存路径","图片名称");
String newPath = imageView.getContext().getCacheDir().getAbsolutePath() + "/myImages.jpg";
File file = new File(newPath);
//有重名文件就删除
if (file.exists()) {
    file.delete();
}
try {
    file.createNewFile();
} catch (IOException e) {
    e.printStackTrace();
}

//将输出流写入到新文件
FileOutputStream fos = null;
try {
    fos = new FileOutputStream(file);
    fos.write(baos.toByteArray());
    fos.flush();
} catch (Exception e) {
    e.printStackTrace();
} finally {
    closeStream(fos);
    closeStream(baos);
}
private static int calculateInSampleSize(BitmapFactory.Options options,
                                         int reqWidth, int reqHeight) {

    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
        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 ? widthRatio : heightRatio;
    }
    return inSampleSize;
}

public static void closeStream(Closeable closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值