zoukankan      html  css  js  c++  java
  • Android 加载图片优化(一)

    高效加载大图片Bitmap

    由于设备限制等原因当一张质量非常高的图片显示在设备终端上我们可能不需要将它完美的展示在应用上 而是展示符合我们设备显示分辨率的图片就好,即显示缩率图。

    如果我们完全展示一张或多张高深度大尺寸图片我们会发现系统非常吃力而且还会内存溢出。今天介绍的就是合理展示图片后续还会介绍线程加载图片,内存缓存图片,磁盘缓存图片

    1.通过 BitmapFactory.Options  在图片加载到内存之前先读取图片的边界

    1 BitmapFactory.Options options = new BitmapFactory.Options();
    2 options.inJustDecodeBounds = true;   //只加载边界
    3 BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
    4 int imageHeight = options.outHeight;
    5 int imageWidth = options.outWidth;
    6 String imageType = options.outMimeType;

    2.计算一个压缩比例

    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) {
            if (width > height) {
                inSampleSize = Math.round((float)height / (float)reqHeight);
            } else {
                inSampleSize = Math.round((float)width / (float)reqWidth);
            }
        }
        return inSampleSize;
    }

    3.利用BitmapFacoty.decode(...,BitmapOptions option)方法加载图片

    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);
    }
  • 相关阅读:
    tomcat使用不同的jdk版本 liunx 装两个jdk
    接下来自己的研究对象
    钉钉小程序开发的所有坑
    java 在web应用中获取本地目录和服务器上的目录不一致的问题
    Python2.7更新pip:UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 7: ordinal not in range(128)
    vue项目中禁止移动端双击放大,双手拉大放大的方法
    JZ56 删除链表中重复的结点
    JZ55 链表中环的入口结点
    JZ54 字符流中第一个不重复的字符
    JZ53 表示数值的字符串
  • 原文地址:https://www.cnblogs.com/qingducx/p/5156288.html
Copyright © 2011-2022 走看看