图片按指定比例缩放并压缩至指定大小,解决保存图片文件体积过大bug。

本文介绍了一种图片尺寸及文件大小压缩的方法,通过指定图片的宽高比例和文件大小限制,实现对原始图片的有效压缩。该方法适用于服务器对上传图片进行预处理的需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:服务器指定图片尺寸大小,并且限制图片文件大小,因此在选择图片后需要进行操作,方法如下:

保存图片的时候,会发现实际文件大小大于当前设置的大小,这个问题在最后面解决,先上正确的代码:


1、指定图片尺寸及文件大小及源图片位置及新图片位置:

float hh = 800f;
float ww = 480f;
int filesize = 100;//单位是K

//源文件位置
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/soon/a.png";
//保存新的文件位置
String  savepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/soon/b.png";


2、图片处理方法及调用:

  需要先创建文件夹:

 String file = Environment.getExternalStorageDirectory().getAbsolutePath();
    String filename = "soon";
    File appDir = new File(file, filename);
    if (!appDir.exists()) {
        appDir.mkdirs();
    }

b31.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        compressThreeOne(path);

    }
});

public void compressThreeOne(String srcPath) {
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeFile(srcPath, opts);
    opts.inJustDecodeBounds = false;
    int w = opts.outWidth;
    int h = opts.outHeight;
    int size = 0;
    if (w <= ww && h <= hh) {
        size = 1;
    } else {
        double scale = w >= h ? w / ww : h / hh;
        double log = Math.log(scale) / Math.log(2);
        double logCeil = Math.ceil(log);
        size = (int) Math.pow(2, logCeil);
    }
    opts.inSampleSize = size;
    bitmap = BitmapFactory.decodeFile(srcPath, opts);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int quality = 100;
    bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
    System.out.println(baos.toByteArray().length);
    while (baos.toByteArray().length > filesize * 1024) {
        baos.reset();
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        quality -= 5;
        System.out.println(baos.toByteArray().length);
    }
    try {
        baos.writeTo(new FileOutputStream(savepath));
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            baos.flush();
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3、文件大小与获取图片大小不一致的问题:

  之前在压缩和缩放后,将图片保存至本地,发现了这个问题,:

 之前的方法如下:

public void saveImageToGallery(Bitmap bmp) {
    // 首先保存图片
    String file = Environment.getExternalStorageDirectory().getAbsolutePath();
    String filename = "soon";
    File appDir = new File(file, filename);
    if (!appDir.exists()) {
        appDir.mkdirs();
    }
    String fileName = "b.jpg";
    File currentFile = new File(appDir, fileName);
    FileOutputStream fos = null;
    try {
        //   currentFile.createNewFile();
        fos = new FileOutputStream(currentFile);
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


结果总会比预算的文件大几倍。

正确的方法是:

baos.writeTo(new FileOutputStream(savepath));




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值