Android異步加載圖片資源,BitmapFactory.decodeStream返回null的問題

近日在做bitmap異步加載時,發現BitmapFactory.decodeStream返回null,問題就在於我們調用了兩次decodeStream。第一次用於獲取圖片的原始大小,第二次才用於decode。解決方法也較簡單,就是將byte[]作爲中間變量進行轉換。大牛原博客鏈接Android異步從網絡加載圖片BitmapFactory.decodeStream 返回null的問題


1.將獲得的inputStream轉換成byte[]

 private static byte[] inputStream2ByteArr(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len = 0;
        while ( (len = inputStream.read(buff)) != -1) {
            outputStream.write(buff, 0, len);
        }
        inputStream.close();
        outputStream.close();
        return outputStream.toByteArray();
    }


2.調用BitmapFactory.decodeByteArray,將byte[]解碼爲Bitmap

public static Bitmap decodeSampleBitMapByByteArr(InputStream inputStream,int reqWidth,int reqHeight) throws IOException{
        if (inputStream == null) {
            return null;
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        //設置該屬性可以不佔用內存,並且能夠得到bitmap的寬高等屬性,此時得到的bitmap是空
        options.inJustDecodeBounds = true;
        byte[] data = inputStream2ByteArr(inputStream);//將InputStream轉爲byte數組,可以多次讀取
       
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
        //設置計算得到的壓縮比例
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        //設置爲false,確保可以得到bitmap != null
        options.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
        
        return bitmap;
    }


3.方法中調用的calculateInSampleSize是用來設置圖片的壓縮比例的,代碼如下

 public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {
        // 源圖片的高度和寬度
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            // 計算出實際寬高和目標寬高的比率
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            // 選擇寬和高中最小的比率作爲inSampleSize的值,這樣可以保證最終圖片的寬和高
            // 一定都會大於等於目標的寬和高。
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章