压缩图片

本文介绍了一种基于目标宽度的图片压缩方法,通过等比缩放实现图片尺寸的调整,同时保持图片质量。文章详细展示了使用Java进行图片压缩的代码实现,包括读取原始图片、计算缩放比例、应用矩阵变换、保存压缩后的图片等步骤。
/**
 * 压缩图片
 * @param targetwidth 压缩的目标大小 例如将图片等比压缩到 1080 * xxxx 或者 xxxx * 1080 输入 1080 即可
 */
private void CompressPic(double targetwidth) {
    Bitmap bitmap =  BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().toString() +"/DCIM/pic.jpg");
    //double targetwidth = 1080;//;Math.sqrt(64.00 * 1000);// 1280
    Log.i("输出", "图片处理开始..");
    // 创建操作图片用的matrix对象
    Matrix matrix = new Matrix();
    // 计算宽高缩放率
    double x = Math.max(targetwidth / bitmap.getWidth(), targetwidth
            / bitmap.getHeight());
    // 缩放图片动作
    matrix.postScale((float) x, (float) x);
    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
            bitmap.getHeight(), matrix, true);
    String compressPicPath =  Environment.getExternalStorageDirectory().toString() +"/DCIM/pic_cmp.jpg";
    File file = new File(compressPicPath);
    if(file.exists()){
        file.delete();
    }
    try {
        FileOutputStream fos = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);
        fos.flush();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

  

转载于:https://www.cnblogs.com/Ayinger/p/11133842.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值