Android图片压缩(质量压缩和尺寸压缩)

本文介绍了两种图片压缩的方法:质量压缩和尺寸压缩。质量压缩通过降低图片的位深和透明度来减小文件大小,适用于图片上传场景;尺寸压缩通过设置采样率减少像素点,减小图片在内存中的大小,适合制作用户头像缩略图。

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

什么是质量压缩?

质量压缩:将Bitmap对象保存到对应路径下是所占用的内存减小,但是当你重新读取压缩后的file为Bitmap时,它所占用的内存并没有改变,它会改变其图像的位深和每个像素的透明度,也就是说JPEG格式压缩后,原来图片中透明的元素将消失,所以这种格式很可能造成失真,即图片的质量压缩,会改变图片在磁盘中的大小(File文件的大小),不能改变图片在加载时,在内存中的大小。

应用场景:图片的上传。

什么是尺寸(采样率)压缩?

尺寸压缩:将Bitmap对象的像素点通过设置采样率,减少Bitmap的像素点,减小占用内存。即图片的尺寸压缩,可以改变图片在内存中的大小,不改变图片在磁盘中的大小。

应用场景:用户头像的缩略图。

质量压缩代码:

/**
*
* @description 将图片保存到本地时进行压缩, 即将图片从Bitmap形式变为File形式时进行压缩,
* 特点是: File形式的图片确实被压缩了, 但是当你重新读取压缩后的file为 Bitmap是,它占用的内存并没有改变
* 所谓的质量压缩,即为改变其图像的位深和每个像素的透明度,也就是说JPEG格式压缩后,原来图片中透明的元素将消失,所以这种格式很可能造成失真
* @date 2020年12月09日
* @param bmp
* @param file
*/
public static String compressBmpToFile(Bitmap bmp,File file) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int options = 80;
bmp.compress(CompressFormat.JPEG, options, baos);
while(baos.toByteArray().length/1024 > 100){
baos.reset();
options -= 10;
bmp.compress(Bitmap.CompressFormat.JPEG, options,baos);
}
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(baos.toByteArray());
fos.flush();
fos.close();
return file.getAbsolutePath();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();

}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}

尺寸压缩代码:

/**
*
* @description 将图片从本地读到内存时,即图片从File形式变为Bitmap形式
* 特点:通过设置采样率,减少图片的像素,达到对内存中的Bitmap进行压缩
方法说明: 该方法就是对Bitmap形式的图片进行压缩, 也就是通过设置采样率, 减少Bitmap的像素, 从而减少了它所占用的内存
* @date 2020年12月09日
* @param image
* @return
*/
private Bitmap compressBmpFromBmp(String srcPath){
BitmapFactory.Options newOptions = new BitmapFactory.Options();
newOptions.inJustDecodeBounds = true;//只读边,不读内容
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOptions);

newOptions.inJustDecodeBounds = false;
int w = newOptions.outWidth;
int h = newOptions.outHeight;
float hh = 800f;
float ww = 480f;
int be = 1;
if(w > h && w >ww){
be = (int)(newOptions.outWidth/ww);
}else if (w < h && h > hh) {
be = (int)(newOptions.outHeight/hh);
}
if(be <= 0)
be = 1;
newOptions.inSampleSize = be;//设置采样率
newOptions.inPreferredConfig = Config.ARGB_8888;//该模式是默认的,可不设
newOptions.inPurgeable = true;//同时设置才会有效
newOptions.inInputShareable = true;//当系统内存不够时候图片会自动被回收

bitmap = BitmapFactory.decodeFile(srcPath, newOptions);
return bitmap;

}

对于图片压缩过之后,还会出现图片旋转的问题,可以参考https://blog.youkuaiyun.com/yushuangping/article/details/110943206

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值