为了账号安全,请及时绑定邮箱和手机立即绑定

Android图片优化

标签:
Android

图片的优化几种方式:

  1. insampleSize,可以降低采样率

private void testPicOptimize(ImageView img) {
    String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath();
    String filePath = sdcard + "/11.jpg";

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath,options);

    int width = options.outWidth;
    options.inSampleSize = width / 200;
    options.inPreferredConfig = Bitmap.Config.RGB_565;
    options.inJustDecodeBounds = false;
    Bitmap bitmap = BitmapFactory.decodeFile(filePath,options);
    img.setImageBitmap(bitmap);
}

采样率压缩是通过设置BitmapFactory.Options.inSampleSize,来减小图片的分辨率,进而减小图片所占用的磁盘空间和内存大小。

设置的inSampleSize会导致压缩的图片的宽高都为1/inSampleSize,整体大小变为原始图片的inSampleSize平方分之一,当然,这些有些注意点:

  • 1、inSampleSize小于等于1会按照1处理

  • 2、inSampleSize只能设置为2的平方,不是2的平方则最终会减小到最近的2的平方数,如设置7会按4进行压缩,设置15会按8进行压缩。 

2. inpreferredconfig参数

BitmapFactory.Options类是BitmapFactory对图片进行解码时使用的一个配置参数类,其中定义了一系列的public成员变量,每个成员变量代表一个配置参数。参数inpreferredconfig表示图片解码时使用的颜色模式,也就是图片中每个像素颜色的表示方式。

https://img1.sycdn.imooc.com//5c08e78500012e0a11760548.jpg

3. InBitmap

private void testInBitmap(ImageView secondImg) {
    String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath();
    String filePath = sdcard + "/11.jpg";

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inBitmap = mCurrentBitmp;
    Bitmap bitmap = BitmapFactory.decodeFile(filePath,options);
    secondImg.setImageBitmap(bitmap);
}

inBitmap 这个一般用在Android3.0或者更高版本中,用来管理Bitmap的内存用的。如果设置了这个字段,那么解码图片的时候通过Option类去重用inBitmap这个已经存在的Bitmap的内存去加载新的Bitmap。这意味着,内存的重用从而改进性能,避免重新分配内存。但是运用inBitmap时必须确保一下三点:

  • 重用的Bitmap必须和即将解码的Bitmap的尺寸相同,且是JPEG或者PNG格式。

  • BitmapFactory.Options.inPreferredConfig字段设置无效,因为会被重用的Bitmap的configuration所覆盖。

  • 一定要使用解码方法返回的Bitmap,因为重用可能会失败(例如:尺寸不匹配)。


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消