安卓选择图片或拍照获取的照片过大时,裁剪图片

开发的过程中,经常会选择上传图片,有时图片过大,需要裁剪。

以下是图片裁剪的方法。

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(path, options); // 此时返回的bitmap为null,此句代码不可删除,切记
int outHeight = options.outHeight;
int outWidth = options.outWidth;
int heightRatio = Math.round((float) outHeight / (float) 800);
int widthRatio = Math.round((float) outWidth / (float) 480);
int SampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
int upwidth = Math.round((float) outWidth / (float) SampleSize);
int upheight = Math.round((float) outHeight / (float) SampleSize);

//参数说明,要压缩的图片路径,压缩后的图片路径,宽,高,图片质量
transImage(path, GlobalFilePath.CACHE_IMAGE + uuid + ".jpg", upwidth, upheight, 90);
    

//压缩图片大小
public void transImage(String fromFile, String toFile, int width, int height, int quality) {
    try {
        Bitmap bitmap = BitmapFactory.decodeFile(fromFile);
        int bitmapWidth = bitmap.getWidth();
        int bitmapHeight = bitmap.getHeight();
        // 缩放图片的尺寸
        float scaleWidth = (float) width / bitmapWidth;
        float scaleHeight = (float) height / bitmapHeight;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 产生缩放后的Bitmap对象
        Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, false);
        // save file
        File myCaptureFile = new File(toFile);
        FileOutputStream out = new FileOutputStream(myCaptureFile);
        if (resizeBitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)) {
            out.flush();
            out.close();
        }
        if (!bitmap.isRecycled()) {
            bitmap.recycle();//记得释放资源,否则会内存溢出
        }
        if (!resizeBitmap.isRecycled()) {
            resizeBitmap.recycle();
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

以上方法就是压缩图片大小的方法。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值