bitmap xml大小 安卓_Android bitmap压缩方法

明人不说暗话,开门见山地说

Bitmap所占用的内存 = 图片长度 x 图片宽度 x 一个像素点占用的字节数。

3个参数,任意减少一个的值,就达到了压缩的效果。

所以压缩又可以分为两种方法,质量压缩和宽高压缩

1.质量压缩

bitmap.compress(Bitmap.CompressFormat.JPEG, quality, byteArrayOutputStream );

主要是通过设置quality来降低质量,0-100范围。

PS:PNG格式会忽略这个参数,所以Bitmap.CompressFormat不可以选择PNG格式

/**

* 压缩图片

*

* @param bitmap

* 被压缩的图片

* @param sizeLimit

* 大小限制

* @return

* 压缩后的图片

*/

private Bitmap compressBitmap(Bitmap bitmap, long sizeLimit) {

ByteArrayOutputStream baos = new ByteArrayOutputStream();

int quality = 100;

bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);

// 循环判断压缩后图片是否超过限制大小

while(baos.toByteArray().length / 1024 > sizeLimit) {

// 清空baos

baos.reset();

bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);

quality -= 10;

}

Bitmap newBitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(baos.toByteArray()), null, null);

return newBitmap;

}

将色彩模式换成RGB_565也会比默认的ARGB8888降低一半质量

BitmapFactory.Options options2 = new BitmapFactory.Options();

options2.inPreferredConfig = Bitmap.Config.RGB_565;

bm = BitmapFactory.decodeFile(filePath, options2);

2.宽高压缩

1)利用采样率压缩

设置inSampleSize的值(int类型)后,假如设为2,则宽和高都为原来的1/2,宽高都减少了,大小则减少了1/4。

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,int reqWidth, int reqHeight) {

final BitmapFactory.Options options = new BitmapFactory.Options();

// 先将inJustDecodeBounds设置为true不会申请内存去创建Bitmap,返回的是一个空的Bitmap,但是可以获取

//图片的一些属性,例如图片宽高,图片类型等等。

options.inJustDecodeBounds = true;

BitmapFactory.decodeResource(res, resId, options);

// 计算inSampleSize

options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

// 加载压缩版图片

options.inJustDecodeBounds = false;

// 根据具体情况选择具体的解码方法

return BitmapFactory.decodeResource(res, resId, options);

}

public 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) {

final int halfHeight = height / 2;

final int halfWidth = width / 2;

// 计算inSampleSize值

while ((halfHeight / inSampleSize) >= reqHeight

&& (halfWidth / inSampleSize) >= reqWidth) {

inSampleSize *= 2;

}

}

return inSampleSize;

}

Matrix 缩放法

Matrix matrix = new Matrix();

matrix.setScale(0.5f, 0.5f);

bm = Bitmap.createBitmap(bit, 0, 0, bit.getWidth(),

bit.getHeight(), matrix, true);

PS:这种方法可以达到只缩放宽或高的效果

3)bitmap.createScaledBitmap方法

bitmap.createScaledBitmap

bm = Bitmap.createScaledBitmap(bit, 150, 150, true);

内部实现其实是借助了matrix,算出给定的宽高压缩比,再用matrix.serScale压缩

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值