假如服務器返回給你的圖片信息是byte[] 然后你需要將起轉換成圖片顯示到你的view中去:
按以下的步驟
1.將獲取的byte數組保存 假如為temp[];
2.將temp[]轉化為bitmap,你可以使用下面的這個方法 :
/** * 將字節數組轉換為ImageView可調用的Bitmap對象 * @param bytes * @param opts 轉換屬性設置 * @return **/ public static Bitmap getPicFromBytes(byte[] bytes, BitmapFactory.Options opts) { if (bytes != null) if (opts != null) return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts); else return BitmapFactory.decodeByteArray(bytes, 0, bytes.length); return null; }
其中的這個Options是BitmapFactory.Options 大致功能就是設置你轉換成bitmap的屬性(大小 寬 高 編碼格式 預覽 等),為了防止圖片過大導致oom我們可以獲取預覽就可以了:
BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inSampleSize = 2;
3.這樣你把這個opts傳入上面的函數中,我們獲取的bitmap 就是原圖的1/4大小了。如果你還需要縮放成固定的寬高來使用 下面提供一個縮放方法:
/** * @param 圖片縮放 * @param bitmap 對象 * @param w 要縮放的寬度 * @param h 要縮放的高度 * @return newBmp 新 Bitmap對象 */ public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h){ int width = bitmap.getWidth(); int height = bitmap.getHeight(); Matrix matrix = new Matrix(); float scaleWidth = ((float) w / width); float scaleHeight = ((float) h / height); matrix.postScale(scaleWidth, scaleHeight); Bitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); return newBmp; }
這樣就能獲取到你想要的高度和寬度的圖片 是不是很方便呢