Android压缩大图官方写法

前言:之前写多媒体的时候,加载图片使用的Picasso框架,但图片列表很多依然有oom的问题,原来的图片分辨率(5024*4280)太大了,遂要压缩图片

对于一张5024*4280的图片(ARGB_8888 )来说,系统要分配多少内存呢?计算方法如下
5024*4280*4byte 约等 82.026M,吓人不
对于android设备来说,丢失一点像素点肉眼基本看不出来(肉眼八倍镜除外),所以如下是官方提供的demo

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

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

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

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    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;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) >= reqHeight
                && (halfWidth / inSampleSize) >= reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

用法如下

mImageView.setImageBitmap(
    decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));

网上有人说decodeStream会比decodeResource更节省内存,官方并无相关说明,需要用哪种方法解析Bitmap就用哪个方法吧,主要还是在于压缩图片

压缩原理就我的理解是先不分配图片的内存,待针对不同的设备(中密度,高密度,超高密度等)计算好压缩比例后再分配内存

ps:Picasso加载图片有一个fit()方法会根据imageview的大小自动压缩图片,就不需要上面的步骤了

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 180,847评论 25赞 708
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 14,702评论 2赞 59
  • 7.1 压缩图片 一、基础知识 1、图片的格式 jpg:最常见的图片格式。色彩还原度比较好,可以支持适当压缩后保持...
    AndroidMaster阅读 2,790评论 0赞 13
  • #幸福是需要修出来的~每天进步1%~幸福实修13班~16静静 杭州# 20171228(31/60) 【幸福三朵玫...
    静静1007阅读 316评论 4赞 5
  • 风雨祭歌 风云卷袭冷人心,黄纸漫天飘落叶。 万人肃穆立碑前,举国默哀面朝川。 苍天无情风云掠,匹夫情义乌雷垂。 人...
    范范子诗阅读 287评论 0赞 0

友情链接更多精彩内容