最近準備研究一下圖片緩存框架,基於這個想法以爲仍是先了解有關圖片緩存的基礎知識,今天重點學習一下Bitmap、BitmapFactory這兩個類。html
圖片緩存相關博客地址:java
Bitmap是Android系統中的圖像處理的最重要類之一。用它能夠獲取圖像文件信息,進行圖像剪切、旋轉、縮放等操做,並能夠指定格式保存圖像文件。算法
重要函數canvas
public void recycle() // 回收位圖佔用的內存空間,把位圖標記爲Dead數組
public final boolean isRecycled() //判斷位圖內存是否已釋放 緩存
public final int getWidth()//獲取位圖的寬度 app
public final int getHeight()//獲取位圖的高度框架
public final boolean isMutable()//圖片是否可修改 ide
public int getScaledWidth(Canvas canvas)//獲取指定密度轉換後的圖像的寬度 函數
public int getScaledHeight(Canvas canvas)//獲取指定密度轉換後的圖像的高度
public boolean compress(CompressFormat format, int quality, OutputStream stream)//按指定的圖片格式以及畫質,將圖片轉換爲輸出流。
format:Bitmap.CompressFormat.PNG或Bitmap.CompressFormat.JPEG
quality:畫質,0-100.0表示最低畫質壓縮,100以最高畫質壓縮。對於PNG等無損格式的圖片,會忽略此項設置。
public static Bitmap createBitmap(Bitmap src) //以src爲原圖生成不可變得新圖像
public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)//以src爲原圖,建立新的圖像,指定新圖像的高寬以及是否可變。
public static Bitmap createBitmap(int width, int height, Config config)——建立指定格式、大小的位圖
public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height)以source爲原圖,建立新的圖片,指定起始座標以及新圖像的高寬。
BitmapFactory工廠類:
public boolean inJustDecodeBounds//若是設置爲true,不獲取圖片,不分配內存,但會返回圖片的高度寬度信息。
public int inSampleSize//圖片縮放的倍數
public int outWidth//獲取圖片的寬度值
public int outHeight//獲取圖片的高度值
public int inDensity//用於位圖的像素壓縮比
public int inTargetDensity//用於目標位圖的像素壓縮比(要生成的位圖)
public byte[] inTempStorage //建立臨時文件,將圖片存儲
public boolean inScaled//設置爲true時進行圖片壓縮,從inDensity到inTargetDensity
public boolean inDither //若是爲true,解碼器嘗試抖動解碼
public Bitmap.Config inPreferredConfig //設置解碼器
public String outMimeType //設置解碼圖像
public boolean inPurgeable//當存儲Pixel的內存空間在系統內存不足時是否能夠被回收
public boolean inInputShareable //inPurgeable爲true狀況下才生效,是否能夠共享一個InputStream
public boolean inPreferQualityOverSpeed //爲true則優先保證Bitmap質量其次是解碼速度
public boolean inMutable //配置Bitmap是否能夠更改,好比:在Bitmap上隔幾個像素加一條線段
public int inScreenDensity //當前屏幕的像素密度
public static Bitmap decodeFile(String pathName, Options opts) //從文件讀取圖片
public static Bitmap decodeFile(String pathName)
public static Bitmap decodeStream(InputStream is) //從輸入流讀取圖片
public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts)
public static Bitmap decodeResource(Resources res, int id) //從資源文件讀取圖片
public static Bitmap decodeResource(Resources res, int id, Options opts)
public static Bitmap decodeByteArray(byte[] data, int offset, int length) //從數組讀取圖片
public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts)
public static Bitmap decodeFileDescriptor(FileDescriptor fd)//從文件讀取文件 與decodeFile不一樣的是這個直接調用JNI函數進行讀取 效率比較高
public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts)
枚舉變量 (位圖位數越高表明其能夠存儲的顏色信息越多,圖像越逼真,佔用內存越大)
/** * 獲取縮放後的本地圖片 * * @param filePath 文件路徑 * @param width 寬 * @param height 高 * @return */ public static Bitmap readBitmapFromFile(String filePath, int width, int height) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); float srcWidth = options.outWidth; float srcHeight = options.outHeight; int inSampleSize = 1; if (srcHeight > height || srcWidth > width) { if (srcWidth > srcHeight) { inSampleSize = Math.round(srcHeight / height); } else { inSampleSize = Math.round(srcWidth / width); } } options.inJustDecodeBounds = false; options.inSampleSize = inSampleSize; return BitmapFactory.decodeFile(filePath, options); }
/** * 獲取縮放後的本地圖片 * * @param filePath 文件路徑 * @param width 寬 * @param height 高 * @return */ public static Bitmap readBitmapFromFileDescriptor(String filePath, int width, int height) { try { FileInputStream fis = new FileInputStream(filePath); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFileDescriptor(fis.getFD(), null, options); float srcWidth = options.outWidth; float srcHeight = options.outHeight; int inSampleSize = 1; if (srcHeight > height || srcWidth > width) { if (srcWidth > srcHeight) { inSampleSize = Math.round(srcHeight / height); } else { inSampleSize = Math.round(srcWidth / width); } } options.inJustDecodeBounds = false; options.inSampleSize = inSampleSize; return BitmapFactory.decodeFileDescriptor(fis.getFD(), null, options); } catch (Exception ex) { } return null; }
測試一樣生成10張圖片兩種方式耗時比較 cpu使用以及內存佔用二者相差無幾 第二種方式效率高一點 因此建議優先採用第二種方式
start = System.currentTimeMillis(); for (int i = 0; i < testMaxCount; i++) { BitmapUtils.readBitmapFromFile(filePath, 400, 400); } end = System.currentTimeMillis(); Log.e(TAG, "BitmapFactory decodeFile--time-->" + (end - start)); start = System.currentTimeMillis(); for (int i = 0; i < testMaxCount; i++) { BitmapUtils.readBitmapFromFileDescriptor(filePath, 400, 400); } end = System.currentTimeMillis(); Log.e(TAG, "BitmapFactory decodeFileDescriptor--time-->" + (end - start));
/** * 獲取縮放後的本地圖片 * * @param ins 輸入流 * @param width 寬 * @param height 高 * @return */ public static Bitmap readBitmapFromInputStream(InputStream ins, int width, int height) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(ins, null, options); float srcWidth = options.outWidth; float srcHeight = options.outHeight; int inSampleSize = 1; if (srcHeight > height || srcWidth > width) { if (srcWidth > srcHeight) { inSampleSize = Math.round(srcHeight / height); } else { inSampleSize = Math.round(srcWidth / width); } } options.inJustDecodeBounds = false; options.inSampleSize = inSampleSize; return BitmapFactory.decodeStream(ins, null, options); }
public static Bitmap readBitmapFromResource(Resources resources, int resourcesId, int width, int height) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(resources, resourcesId, options); float srcWidth = options.outWidth; float srcHeight = options.outHeight; int inSampleSize = 1; if (srcHeight > height || srcWidth > width) { if (srcWidth > srcHeight) { inSampleSize = Math.round(srcHeight / height); } else { inSampleSize = Math.round(srcWidth / width); } } options.inJustDecodeBounds = false; options.inSampleSize = inSampleSize; return BitmapFactory.decodeResource(resources, resourcesId, options); }
此種方式至關的耗費內存 建議採用decodeStream代替decodeResource 能夠以下形式
public static Bitmap readBitmapFromResource(Resources resources, int resourcesId, int width, int height) { InputStream ins = resources.openRawResource(resourcesId); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(ins, null, options); float srcWidth = options.outWidth; float srcHeight = options.outHeight; int inSampleSize = 1; if (srcHeight > height || srcWidth > width) { if (srcWidth > srcHeight) { inSampleSize = Math.round(srcHeight / height); } else { inSampleSize = Math.round(srcWidth / width); } } options.inJustDecodeBounds = false; options.inSampleSize = inSampleSize; return BitmapFactory.decodeStream(ins, null, options); }
decodeStream、decodeResource佔用內存對比:
start = System.currentTimeMillis(); for (int i = 0; i < testMaxCount; i++) { BitmapUtils.readBitmapFromResource(getResources(), R.mipmap.ic_app_center_banner, 400, 400); Log.e(TAG, "BitmapFactory decodeResource--num-->" + i); } end = System.currentTimeMillis(); Log.e(TAG, "BitmapFactory decodeResource--time-->" + (end - start)); start = System.currentTimeMillis(); for (int i = 0; i < testMaxCount; i++) { BitmapUtils.readBitmapFromResource1(getResources(), R.mipmap.ic_app_center_banner, 400, 400); Log.e(TAG, "BitmapFactory decodeStream--num-->" + i); } end = System.currentTimeMillis(); Log.e(TAG, "BitmapFactory decodeStream--time-->" + (end - start));
BitmapFactory.decodeResource 加載的圖片可能會通過縮放,該縮放目前是放在 java 層作的,效率比較低,並且須要消耗 java 層的內存。所以,若是大量使用該接口加載圖片,容易致使OOM錯誤
BitmapFactory.decodeStream 不會對所加載的圖片進行縮放,相比之下佔用內存少,效率更高。
這兩個接口各有用處,若是對性能要求較高,則應該使用 decodeStream;若是對性能要求不高,且須要 Android 自帶的圖片自適應縮放功能,則可使用 decodeResource。
public static Bitmap readBitmapFromByteArray(byte[] data, int width, int height) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(data, 0, data.length, options); float srcWidth = options.outWidth; float srcHeight = options.outHeight; int inSampleSize = 1; if (srcHeight > height || srcWidth > width) { if (srcWidth > srcHeight) { inSampleSize = Math.round(srcHeight / height); } else { inSampleSize = Math.round(srcWidth / width); } } options.inJustDecodeBounds = false; options.inSampleSize = inSampleSize; return BitmapFactory.decodeByteArray(data, 0, data.length, options); }
/** * 獲取縮放後的本地圖片 * * @param filePath 文件路徑 * @return */ public static Bitmap readBitmapFromAssetsFile(Context context, String filePath) { Bitmap image = null; AssetManager am = context.getResources().getAssets(); try { InputStream is = am.open(filePath); image = BitmapFactory.decodeStream(is); is.close(); } catch (IOException e) { e.printStackTrace(); } return image; }
public static void writeBitmapToFile(String filePath, Bitmap b, int quality) { try { File desFile = new File(filePath); FileOutputStream fos = new FileOutputStream(desFile); BufferedOutputStream bos = new BufferedOutputStream(fos); b.compress(Bitmap.CompressFormat.JPEG, quality, bos); bos.flush(); bos.close(); } catch (IOException e) { e.printStackTrace(); } }
private static Bitmap compressImage(Bitmap image) { if (image == null) { return null; } ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] bytes = baos.toByteArray(); ByteArrayInputStream isBm = new ByteArrayInputStream(bytes); Bitmap bitmap = BitmapFactory.decodeStream(isBm); return bitmap; } catch (OutOfMemoryError e) { } finally { try { if (baos != null) { baos.close(); } } catch (IOException e) { } } return null; }
/** * 根據scale生成一張圖片 * * @param bitmap * @param scale 等比縮放值 * @return */ public static Bitmap bitmapScale(Bitmap bitmap, float scale) { Matrix matrix = new Matrix(); matrix.postScale(scale, scale); // 長和寬放大縮小的比例 Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); return resizeBmp; }
/** * 讀取照片exif信息中的旋轉角度 * * @param path 照片路徑 * @return角度 */ private static int readPictureDegree(String path) { if (TextUtils.isEmpty(path)) { return 0; } int degree = 0; try { ExifInterface exifInterface = new ExifInterface(path); int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break; } } catch (Exception e) { } return degree; }
private static Bitmap rotateBitmap(Bitmap b, float rotateDegree) { if (b == null) { return null; } Matrix matrix = new Matrix(); matrix.postRotate(rotateDegree); Bitmap rotaBitmap = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true); return rotaBitmap; }
public byte[] bitmap2Bytes(Bitmap bm) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); }
public static Drawable bitmapToDrawable(Resources resources, Bitmap bm) { Drawable drawable = new BitmapDrawable(resources, bm); return drawable; }
public static Bitmap drawableToBitmap(Drawable drawable) { Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(canvas); return bitmap; }
以前一直使用過Afinal 和Xutils 熟悉這兩框架的都知道,二者出自同一人,Xutils是Afina的升級版,AFinal中的圖片內存緩存使用的是Bitmap 然後來爲什麼Xutils將內存緩存的對象改爲了Drawable了呢?咱們一探究竟
寫個測試程序:
List<Bitmap> bitmaps = new ArrayList<>(); start = System.currentTimeMillis(); for (int i = 0; i < testMaxCount; i++) { Bitmap bitmap = BitmapUtils.readBitMap(this, R.mipmap.ic_app_center_banner); bitmaps.add(bitmap); Log.e(TAG, "BitmapFactory Bitmap--num-->" + i); } end = System.currentTimeMillis(); Log.e(TAG, "BitmapFactory Bitmap--time-->" + (end - start)); List<Drawable> drawables = new ArrayList<>(); start = System.currentTimeMillis(); for (int i = 0; i < testMaxCount; i++) { Drawable drawable = getResources().getDrawable(R.mipmap.ic_app_center_banner); drawables.add(drawable); Log.e(TAG, "BitmapFactory Drawable--num-->" + i); } end = System.currentTimeMillis(); Log.e(TAG, "BitmapFactory Drawable--time-->" + (end - start));
測試數據1000 同一張圖片
Bitmap 直接70條數據的時候掛掉
Drawable 輕鬆1000條數據經過
從測試說明Drawable 相對Bitmap有很大的內存佔用優點。這也是爲啥如今主流的圖片緩存框架內存緩存那一層採用Drawable做爲緩存對象的緣由。
小結:
圖片處理就暫時學習到這裏,之後再作補充。