Android圖片緩存之Bitmap詳解(一)
前言:
最近準(zhǔn)備研究一下圖片緩存框架,基于這個(gè)想法覺得還是先了解有關(guān)圖片緩存的基礎(chǔ)知識(shí),今天重點(diǎn)學(xué)習(xí)一下Bitmap、BitmapFactory這兩個(gè)類。
Bitmap:
Bitmap是Android系統(tǒng)中的圖像處理的最重要類之一。用它可以獲取圖像文件信息,進(jìn)行圖像剪切、旋轉(zhuǎn)、縮放等操作,并可以指定格式保存圖像文件。
重要函數(shù)
•public void recycle() // 回收位圖占用的內(nèi)存空間,把位圖標(biāo)記為Dead
•public final boolean isRecycled() //判斷位圖內(nèi)存是否已釋放
•public final int getWidth()//獲取位圖的寬度
•public final int getHeight()//獲取位圖的高度
•public final boolean isMutable()//圖片是否可修改
•public int getScaledWidth(Canvas canvas)//獲取指定密度轉(zhuǎn)換后的圖像的寬度
•public int getScaledHeight(Canvas canvas)//獲取指定密度轉(zhuǎn)換后的圖像的高度
•public boolean compress(CompressFormat format, int quality, OutputStream stream)//按指定的圖片格式以及畫質(zhì),將圖片轉(zhuǎn)換為輸出流。
format:Bitmap.CompressFormat.PNG或Bitmap.CompressFormat.JPEG
quality:畫質(zhì),0-100.0表示最低畫質(zhì)壓縮,100以最高畫質(zhì)壓縮。對(duì)于PNG等無損格式的圖片,會(huì)忽略此項(xiàng)設(shè)置。
•public static Bitmap createBitmap(Bitmap src) //以src為原圖生成不可變得新圖像
•public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)//以src為原圖,創(chuàng)建新的圖像,指定新圖像的高寬以及是否可變。
•public static Bitmap createBitmap(int width, int height, Config config)——?jiǎng)?chuàng)建指定格式、大小的位圖
•public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height)以source為原圖,創(chuàng)建新的圖片,指定起始坐標(biāo)以及新圖像的高寬。
BitmapFactory工廠類:
Option 參數(shù)類:
•public boolean inJustDecodeBounds//如果設(shè)置為true,不獲取圖片,不分配內(nèi)存,但會(huì)返回圖片的高度寬度信息。
•public int inSampleSize//圖片縮放的倍數(shù)
•public int outWidth//獲取圖片的寬度值
•public int outHeight//獲取圖片的高度值
•public int inDensity//用于位圖的像素壓縮比
•public int inTargetDensity//用于目標(biāo)位圖的像素壓縮比(要生成的位圖)
•public byte[] inTempStorage //創(chuàng)建臨時(shí)文件,將圖片存儲(chǔ)
•public boolean inScaled//設(shè)置為true時(shí)進(jìn)行圖片壓縮,從inDensity到inTargetDensity
•public boolean inDither //如果為true,解碼器嘗試抖動(dòng)解碼
•public Bitmap.Config inPreferredConfig //設(shè)置解碼器
•public String outMimeType //設(shè)置解碼圖像
•public boolean inPurgeable//當(dāng)存儲(chǔ)Pixel的內(nèi)存空間在系統(tǒng)內(nèi)存不足時(shí)是否可以被回收
•public boolean inInputShareable //inPurgeable為true情況下才生效,是否可以共享一個(gè)InputStream
•public boolean inPreferQualityOverSpeed //為true則優(yōu)先保證Bitmap質(zhì)量其次是解碼速度
•public boolean inMutable //配置Bitmap是否可以更改,比如:在Bitmap上隔幾個(gè)像素加一條線段
•public int inScreenDensity //當(dāng)前屏幕的像素密度
工廠方法:
•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) //從數(shù)組讀取圖片
•public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts)
•public static Bitmap decodeFileDescriptor(FileDescriptor fd)//從文件讀取文件 與decodeFile不同的是這個(gè)直接調(diào)用JNI函數(shù)進(jìn)行讀取 效率比較高
•public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts)
Bitmap.Config inPreferredConfig :
枚舉變量 (位圖位數(shù)越高代表其可以存儲(chǔ)的顏色信息越多,圖像越逼真,占用內(nèi)存越大)
•public static final Bitmap.Config ALPHA_8 //代表8位Alpha位圖 每個(gè)像素占用1byte內(nèi)存
•public static final Bitmap.Config ARGB_4444 //代表16位ARGB位圖 每個(gè)像素占用2byte內(nèi)存
•public static final Bitmap.Config ARGB_8888 //代表32位ARGB位圖 每個(gè)像素占用4byte內(nèi)存
•public static final Bitmap.Config RGB_565 //代表8位RGB位圖 每個(gè)像素占用2byte內(nèi)存
Android中一張圖片(BitMap)占用的內(nèi)存主要和以下幾個(gè)因數(shù)有關(guān):圖片長度,圖片寬度,單位像素占用的字節(jié)數(shù)。
一張圖片(BitMap)占用的內(nèi)存=圖片長度*圖片寬度*單位像素占用的字節(jié)數(shù)
圖片讀取實(shí)例:
1.)從文件讀取方式一
/** * 獲取縮放后的本地圖片 * * @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); }
2.)從文件讀取方式二 效率高于方式一
/** * 獲取縮放后的本地圖片 * * @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張圖片兩種方式耗時(shí)比較 cpu使用以及內(nèi)存占用兩者相差無幾 第二種方式效率高一點(diǎn) 所以建議優(yōu)先采用第二種方式
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));
3.)從輸入流中讀取文件
/** * 獲取縮放后的本地圖片 * * @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); }
4.)從資源文件中讀取文件
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); }
此種方式相當(dāng)?shù)暮馁M(fèi)內(nèi)存 建議采用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占用內(nèi)存對(duì)比:
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 加載的圖片可能會(huì)經(jīng)過縮放,該縮放目前是放在 java 層做的,效率比較低,而且需要消耗 java 層的內(nèi)存。因此,如果大量使用該接口加載圖片,容易導(dǎo)致OOM錯(cuò)誤。
BitmapFactory.decodeStream 不會(huì)對(duì)所加載的圖片進(jìn)行縮放,相比之下占用內(nèi)存少,效率更高。
這兩個(gè)接口各有用處,如果對(duì)性能要求較高,則應(yīng)該使用 decodeStream;如果對(duì)性能要求不高,且需要 Android 自帶的圖片自適應(yīng)縮放功能,則可以使用 decodeResource。
5. )從二進(jìn)制數(shù)據(jù)讀取圖片
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); }
6.)從assets文件讀取圖片
/** * 獲取縮放后的本地圖片 * * @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; }
圖片縮放:
/** * 根據(jù)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; }
獲取圖片旋轉(zhuǎn)角度:
/** * 讀取照片exif信息中的旋轉(zhuǎn)角度 * * @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; }
圖片旋轉(zhuǎn)角度:
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; }
圖片轉(zhuǎn)二進(jìn)制:
public byte[] bitmap2Bytes(Bitmap bm) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); }
Bitmap轉(zhuǎn)Drawable
public static Drawable bitmapToDrawable(Resources resources, Bitmap bm) { Drawable drawable = new BitmapDrawable(resources, bm); return drawable; }
Drawable轉(zhuǎn)Bitmap
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; }
Drawable、Bitmap占用內(nèi)存探討
之前一直使用過Afinal 和Xutils 熟悉這兩框架的都知道,兩者出自同一人,Xutils是Afina的升級(jí)版,AFinal中的圖片內(nèi)存緩存使用的是Bitmap 而后來為何Xutils將內(nèi)存緩存的對(duì)象改成了Drawable了呢?我們一探究竟
寫個(gè)測試程序:
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));
測試數(shù)據(jù)1000 同一張圖片
從測試說明Drawable 相對(duì)Bitmap有很大的內(nèi)存占用優(yōu)勢。這也是為啥現(xiàn)在主流的圖片緩存框架內(nèi)存緩存那一層采用Drawable作為緩存對(duì)象的原因。
小結(jié):圖片處理就暫時(shí)學(xué)習(xí)到這里,以后再做補(bǔ)充。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Flutter加載圖片流程之ImageProvider源碼示例解析
這篇文章主要為大家介紹了Flutter加載圖片流程之ImageProvider源碼示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04深入分析Android NFC技術(shù) android nfc開發(fā)
本篇文章我們對(duì)android開發(fā)中nfc技術(shù)做了全面的原理分析以及實(shí)現(xiàn)過程,需要的讀者們一起參考一下吧。2017-11-11Kotlin構(gòu)造函數(shù)與成員變量和init代碼塊執(zhí)行順序詳細(xì)講解
這篇文章主要介紹了Kotlin構(gòu)造函數(shù)與成員變量和init代碼塊執(zhí)行順序,kotlin里面的構(gòu)造函數(shù)分為主構(gòu)造函數(shù)和次構(gòu)造函數(shù)。主構(gòu)造函數(shù)只能有一個(gè),次構(gòu)造函數(shù)個(gè)數(shù)不限制,可以有一個(gè)或者多個(gè)2022-11-11在Android里完美實(shí)現(xiàn)基站和WIFI定位
眾所周知的,在OPhone和大部分國產(chǎn)的Android定制機(jī)里不支持最簡單實(shí)用的基站和WIFI定位,只能使用速度慢而耗電的GPS定位,但OPhone和華為/中興生產(chǎn)的一些Android定制機(jī)卻占據(jù)了一定的市場,因此導(dǎo)致了很多使用了定位技術(shù)的Andorid應(yīng)用挺尷尬的。2014-07-07Android?AMS啟動(dòng)App進(jìn)程原理分析
這篇文章主要介紹了Android?AMS啟動(dòng)App進(jìn)程原理,系統(tǒng)fork函數(shù)是如何創(chuàng)建進(jìn)程,文中有詳細(xì)的代碼示例,對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2023-05-05Android編程實(shí)現(xiàn)擦除Bitmap中某一塊的方法
這篇文章主要介紹了Android編程實(shí)現(xiàn)擦除Bitmap中某一塊的方法,涉及Android操作Bitmap顏色像素值調(diào)整的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11Android App在線程中創(chuàng)建handler的方法講解
這篇文章主要介紹了Android App在線程中創(chuàng)建handler的方法講解,文中同時(shí)講解了handler和線程的關(guān)系以及使用Handler時(shí)一些需要注意的地方,需要的朋友可以參考下2016-03-03