android压缩图片质量,Android 图片质量压缩有关问题

Android 图片质量压缩问题

本帖最后由 u013064347 于 2014-01-13 10:22:47 编辑

网上看到一个图片质量压缩法,传入1M以内图片能正常压缩,但是传入2M多的图片就报内存溢出,应该怎么解决?附上代码

Bitmap images=BitmapFactory.decodeFile(filePath);//这里传入图片会报内存溢出!

public Bitmap compressImage(Bitmap image) {

ByteArrayOutputStream baos = new ByteArrayOutputStream();

image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中

int options = 90;

int longs=baos.toByteArray().length;

while (baos.toByteArray().length/1024  > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩

baos.reset();// 重置baos即清空baos

image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中

longs=baos.toByteArray().length;

options -= 10;// 每次都减少10

}

ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中

Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片

return bitmap;

}

分享到:

更多

------解决方案--------------------

// 取得图片

InputStream temp = this.getAssets().open(path);

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

// 这个参数代表,不为bitmap分配内存空间,只记录一些该图片的信息(例如图片大小),说白了就是为了内存优化

options.inJustDecodeBounds = true;

// 通过创建图片的方式,取得options的内容(这里就是利用了java的地址传递来赋值)

BitmapFactory.decodeStream(temp, null, options);

// 关闭流

temp.close();

// 生成压缩的图片

int i = 0;

Bitmap bitmap = null;

while (true) {

// 这一步是根据要设置的大小,使宽和高都能满足

if ((options.outWidth >> i <= size)

&& (options.outHeight >> i <= size)) {

// 重新取得流,注意:这里一定要再次加载,不能二次使用之前的流!

temp = this.getAssets().open(path);

// 这个参数表示 新生成的图片为原始图片的几分之一。

options.inSampleSize = (int) Math.pow(2.0D, i);

// 这里之前设置为了true,所以要改为false,否则就创建不出图片

options.inJustDecodeBounds = false;

bitmap = BitmapFactory.decodeStream(temp, null, options);

break;

}

i += 1;

}

return bitmap;

------解决方案--------------------

http://bbs.csdn.net/topics/390432950

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值