zoukankan      html  css  js  c++  java
  • 获取图片的采样率

    获取图片的采样率

    使用Bitmapactory解码(decode)资源的时候,系统会尝试分配内存,这个时候如果图片的内存过大,就容易产生内存泄漏的问题。可以使用设置图片的采样率的方法来限制读取到的图片的大小,也就是分辨率的大小。设置BitmapFactory.Opitions的inJustDecodeBounds属性为true,就可以在不分配内存的情况下,获取该图片的大小和类型。

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
    int imageHeight = options.outHeight;
    int imageWidth = options.outWidth;
    String imageType = options.outMimeType;

    获取到高度和宽度之后,就可以按照我们的需要的高度和宽度,来计算图片的缩放比,得出图片的采样率

    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;
    }

    获取采样率之后,重新解码图片,就可以根据需要的大小获取对应分辨率的图片

    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);
    }
  • 相关阅读:
    内存条DDR3与DDR3L的区别
    松耦合,紧耦合
    绕单轴的旋转矩阵
    IMU
    墨卡托投影、横轴墨卡托投影和通用横轴墨卡托投影
    大地基准面
    我国的大地原点
    《诗经》
    自增长主键Id的设计
    REDIS 主从复制
  • 原文地址:https://www.cnblogs.com/summerpxy/p/13648340.html
Copyright © 2011-2022 走看看