android 读取本地超大图片

# android 如何读取本地超大图片

    ``` java
    public static Bitmap getimage(String srcPath,int size) {
    // 该对象为图片缩放操作对象
    BitmapFactory.Options newOpts = new BitmapFactory.Options();
    //开始读入图片,该参数为true时,只会在读取图片的宽高 而不产生bitmap 无论图片大小 都用他读取。
    newOpts.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空
    //读取后一定要 设置成false;
    newOpts.inJustDecodeBounds = false ;
    //获取 原图图片的长和宽
    int realw = newOpts.outWidth;
    int realh = newOpts.outHeight;
    //现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
            float hh = 800f;//这里设置高度为800f   缩放后的长
            float ww = 480f;//这里设置宽度为480f   缩放后的宽
            //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
            int options = 1;//be=1表示不缩放
            if (realw> h && realw > ww) {
                //如果宽度大的话根据宽度固定大小缩放
                options = (int) (newOpts.outWidth / ww);
            } else if (realw < realh && realh> hh) {
                //如果高度高的话根据宽度固定大小缩放
                options = (int) (newOpts.outHeight / hh);
            }
            if (options <= 0)
                options = 1;    

            newOpts.inSampleSize = options;//设置缩放比例
            //重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
            bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
                    //如果是一张超大图的话  经过以上处理 图片应该就变成了一个800x480的图片了      
            //以上是尺寸 缩放,一般这样处理后就不会oom了,如果还要oom 就进行质量压缩
            //return bitmap;
            return  compressImage(bitmap,size);
    }


    /**
     * 
     * @param image 要压缩的bitmap
     * @param size 要控制的大小(单位为kb)
     * @return
     */
    private static Bitmap compressImage(Bitmap image,int size) {
        if(image==null){
            return null;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
        int options = 100;
        LogUtil.i("图片大小1", baos.toByteArray().length);
        while ( baos.toByteArray().length >size) {  //循环判断如果压缩后图片是否大于size kb,大于继续压缩     
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        LogUtil.i("图片大小2", baos.toByteArray().length);
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return bitmap;
    }
    ```
发布了16 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/u013783167/article/details/50641429
今日推荐