在 Android 應(yīng)用中加載位圖比較復(fù)雜,原因有很多種:
- 位圖很容易就會(huì)耗盡應(yīng)用的內(nèi)存預(yù)算撰洗。例如短条,Pixel 手機(jī)上的相機(jī)拍攝的照片最大可達(dá) 4048x3036 像素(1200 萬(wàn)像素)剑辫。如果使用的位圖配置為
[ARGB_8888](https://developer.android.com/reference/android/graphics/Bitmap.Config)
(Android 2.3(API 級(jí)別 9)及更高版本的默認(rèn)設(shè)置)阱飘,將單張照片加載到內(nèi)存大約需要 48MB 內(nèi)存(404830364 字節(jié))摘昌。如此龐大的內(nèi)存需求可能會(huì)立即耗盡該應(yīng)用的所有可用內(nèi)存速妖。 -
在界面線程中加載位圖會(huì)降低應(yīng)用的性能,導(dǎo)致響應(yīng)速度變慢第焰,甚至?xí)?dǎo)致系統(tǒng)顯示 ANR 消息买优。因此,在使用位圖時(shí)挺举,必須正確地管理線程處理。
單個(gè)像素的字節(jié)大小
單個(gè)像素的字節(jié)大小由Bitmap的一個(gè)可配置的參數(shù)Config來(lái)決定烘跺。 Bitmap中湘纵,存在一個(gè)枚舉類Config,定義了Android中支持的Bitmap配置:
不同config單個(gè)像素字節(jié)大小.png
Bitmap加載方式
Bitmap 的加載方式有 Resource 資源加載滤淳、本地(SDcard)加載梧喷、網(wǎng)絡(luò)加載等加載方式。
- 從本地(SDcard)文件讀取
方式一
/**
- 獲取縮放后的本地圖片 *
- @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;
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;
}
- 從輸入流中讀取文件(網(wǎng)絡(luò)加載)
/**
- 獲取縮放后的本地圖片 *
- @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);
}
3.Resource資源加載
Res資源加載方式:
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);
}
BitmapFactory.decodeResource 加載的圖片可能會(huì)經(jīng)過(guò)縮放,該縮放目前是放在 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 霎烙。
4.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;
}
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);
}
Bitmap | Drawable | InputStream | Byte[ ] 之間進(jìn)行轉(zhuǎn)換
1.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 的獲取方式: Drawable drawable=getResources().getDrawable(R.drawable.ic_launcher);
2.Bitmap轉(zhuǎn)換成Drawable
public static Drawable bitmapToDrawable(Resources resources, Bitmap bm) {
Drawable drawable = new BitmapDrawable(resources, bm);
return drawable;
}
3.Bitmap轉(zhuǎn)換成byte[ ]
public byte[] bitmap2Bytes(Bitmap bm) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
4.byte[]轉(zhuǎn)換成Bitmap
Bitmapbitmap=BitmapFactory.decodeByteArray(byte,0,b.length);
5.InputStream轉(zhuǎn)換成Bitmap
InputStreamis=getResources().openRawResource(id); Bitmapbitmap=BitmaoFactory.decodeStream(is);
6.InputStream轉(zhuǎn)換成byte[]
InputStream is = getResources().openRawResource(id);//也可以通過(guò)其他方式接收一個(gè) InputStream對(duì)象
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] b = new byte[10242];
int len = 0;
while ((len = is.read(b, 0, b.length)) != -1) {
baos.write(b, 0, len);
baos.flush(); }
byte[] bytes = baos.toByteArray();
Bitmap常用操作
1.將Bitmap保存為本地文件:
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();
} }
2.圖片壓縮:
private static Bitmap compressImage(Bitmap image) {
if (image == null) {
return null;
}
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 50, 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;
}
3.圖片縮放:
/** - 根據(jù)scale生成一張圖片
- @param bitmap
- @param scale 等比縮放值 * @return
/
public static Bitmap bitmapScale(Bitmap bitmap, float scale) {
Matrix matrix = new Matrix();
matrix.postScale(scale, scale); // 長(zhǎng)和寬放大縮小的比例
Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
return resizeBmp;
}
4.獲取圖片旋轉(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;
}
5.設(shè)置圖片旋轉(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;
}
6.通過(guò)圖片id獲得Bitmap:
Bitmapbitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
7.通過(guò) assest 獲取 獲得Drawable bitmap:
InputStream in = this.getAssets().open("ic_launcher");
Drawable da = Drawable.createFromStream(in, null);
Bitmap mm = BitmapFactory.decodeStream(in);
8.通過(guò) sdcard 獲得 bitmap
1 Bitmapbit=BitmapFactory.decodeFile("/sdcard/android.jpg");
9.view轉(zhuǎn)Bitmap
publicstaticBitmapconvertViewToBitmap(Viewview,intbitmapWidth,int bitmapHeight){
Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
view.draw(new Canvas(bitmap));
return bitmap;
}
10.將控件轉(zhuǎn)換為bitmap
public static Bitmap convertViewToBitMap(View view){ // 打開(kāi)圖像緩存
view.setDrawingCacheEnabled(true);
// 必須調(diào)用measure和layout方法才能成功保存可視組件的截圖到png圖像文件
// 測(cè)量View大小
view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
// 發(fā)送位置和尺寸到View及其所有的子View
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); // 獲得可視組件的截圖
Bitmap bitmap = view.getDrawingCache();
return bitmap;
}
public static Bitmap getBitmapFromView(View view){
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(returnedBitmap); Drawable bgDrawable = view.getBackground(); if (bgDrawable != null)
bgDrawable.draw(canvas); else
canvas.drawColor(Color.WHITE); view.draw(canvas);
return returnedBitmap;
}
11.放大縮小圖片
public static Bitmap zoomBitmap(Bitmap bitmap,int w,int h){ int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidht = ((float)w / width);
float scaleHeight = ((float)h / height);
matrix.postScale(scaleWidht, scaleHeight);
Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix,
true);
return newbmp;
}
12.獲得圓角圖片的方法
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap,float roundPx){
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap .getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
13.對(duì) bitmap 進(jìn)行裁剪
public Bitmap bitmapClip(Context context , int id , int x , int y){
Bitmap map = BitmapFactory.decodeResource(context.getResources(), id); map = Bitmap.createBitmap(map, x, y, 120, 120);
return map;
}
Bitmap內(nèi)存模型
內(nèi)存模型.png
Bitmap的內(nèi)存回收
- 在Android2.3.3之前推薦使用Bitmap.recycle()方法進(jìn)行Bitmap的內(nèi)存回收撬讽。
備注:只有當(dāng)確定這個(gè)Bitmap不被引用的時(shí)候才能調(diào)用此方法,否則會(huì)有“Canvas: trying to use a recycled bitmap”這個(gè)錯(cuò)誤悬垃。 - Android3.0之后
Android3.0之后游昼,并沒(méi)有強(qiáng)調(diào)Bitmap.recycle();而是強(qiáng)調(diào)Bitmap的復(fù)用
Save a bitmap for later use
使用LruCache對(duì)Bitmap進(jìn)行緩存**,當(dāng)再次使用到這個(gè)Bitmap的時(shí)候直接獲取盗忱,而不用重走編碼流程酱床。
Use an existing bitmap
Android3.0(API 11之后)引入了BitmapFactory.Options.inBitmap字段,設(shè)置此字段之后解 碼方法會(huì)嘗試復(fù)用一張存在的Bitmap趟佃。這意味著B(niǎo)itmap的內(nèi)存被復(fù)用扇谣,避免了內(nèi)存的回收 及申請(qǐng)過(guò)程,顯然性能表現(xiàn)更佳闲昭。不過(guò)罐寨,使用這個(gè)字段有幾點(diǎn)限制:
聲明可被復(fù)用的Bitmap必須設(shè)置inMutable為true;
Android4.4(API 19)之前只有格式為jpg、png序矩,同等寬高(要求苛刻)鸯绿,inSampleSize為1的 Bitmap才可以復(fù)用;
Android4.4(API 19)之前被復(fù)用的Bitmap的inPreferredConfig會(huì)覆蓋待分配內(nèi)存的Bitmap設(shè) 置的inPreferredConfig;
Android4.4(API 19)之后被復(fù)用的Bitmap的內(nèi)存必須大于需要申請(qǐng)內(nèi)存的Bitmap的內(nèi)存; Android4.4(API 19)之前待加載Bitmap的Options.inSampleSize必須明確指定為1
獲取Bitmap的大小 - getByteCount()
getByteCount()方法是在API12加入的,代表存儲(chǔ)Bitmap的色素需要的最少內(nèi)存簸淀。API19開(kāi)始 getAllocationByteCount()方法代替了getByteCount()瓶蝴。 - getAllocationByteCount()
API19之后,Bitmap加了一個(gè)Api:getAllocationByteCount();代表在內(nèi)存中為Bitmap分配的內(nèi)存大
小租幕。
public final int getAllocationByteCount() {
if (mBuffer == null) {
//mBuffer代表存儲(chǔ)Bitmap像素?cái)?shù)據(jù)的字節(jié)數(shù)組舷手。
return getByteCount();
}
return mBuffer.length; } - getByteCount()與getAllocationByteCount()的區(qū)別
一般情況下兩者是相等的
通過(guò)復(fù)用Bitmap來(lái)解碼圖片,如果被復(fù)用的Bitmap的內(nèi)存比待分配內(nèi)存的Bitmap大,那么 getByteCount()表示新解碼圖片占用內(nèi)存的大小(并非實(shí)際內(nèi)存大小,實(shí)際大小是復(fù)用的那個(gè) Bitmap的大小)劲绪,getAllocationByteCount()表示被復(fù)用Bitmap真實(shí)占用的內(nèi)存大小(即mBuffer 的長(zhǎng)度)
Bitmap占用內(nèi)存大小計(jì)算
Bitmap作為位圖男窟,需要讀入一張圖片每一個(gè)像素點(diǎn)的數(shù)據(jù)盆赤,其主要占用內(nèi)存的地方也正是這些像素?cái)?shù) 據(jù)。對(duì)于像素?cái)?shù)據(jù)總大小歉眷,我們可以猜想為:像素總數(shù)量 × 每個(gè)像素的字節(jié)大小牺六,而像素總數(shù)量在矩形 屏幕表現(xiàn)下,應(yīng)該是:橫向像素?cái)?shù)量 × 縱向像素?cái)?shù)量汗捡,結(jié)合得到:
Bitmap內(nèi)存占用 ≈ 像素?cái)?shù)據(jù)總大小 = 橫向像素?cái)?shù)量 × 縱向像素?cái)?shù)量 × 每個(gè)像素的字節(jié)大小
if (env->GetBooleanField(options, gOptions_scaledFieldID)) {
const int density = env->GetIntField(options, gOptions_densityFieldID);
const int targetDensity = env->GetIntField(options, gOptions_targetDensityFieldID);
const int screenDensity = env->GetIntField(options, gOptions_screenDensityFieldID);
if (density != 0 && targetDensity != 0 && density != screenDensity) {
scale = (float) targetDensity / density;
}
}
...
int scaledWidth = decoded->width();
int scaledHeight = decoded->height();
if (willScale && mode != SkImageDecoder::kDecodeBounds_Mode) {
scaledWidth = int(scaledWidth * scale + 0.5f);
scaledHeight = int(scaledHeight * scale + 0.5f);
}
...
if (willScale) {
const float sx = scaledWidth / float(decoded->width());
const float sy = scaledHeight / float(decoded->height());
bitmap->setConfig(decoded->getConfig(), scaledWidth, scaledHeight);
bitmap->allocPixels(&javaAllocator, NULL);
bitmap->eraseColor(0);
SkPaint paint;
paint.setFilterBitmap(true);
SkCanvas canvas(bitmap);
canvas.scale(sx, sy);
canvas.drawBitmap(decoded, 0.0f, 0.0f, &paint);
}
從上述代碼中淑际,我們看到bitmap最終通過(guò)canvas繪制出來(lái),而canvas在繪制之前凉唐,有一個(gè)scale的操作庸追,scale的值由
scale=(float)targetDensity/density;
這一行代碼決定,即縮放的倍率和targetDensity和density相關(guān)台囱,而這兩個(gè)參數(shù)都是從傳入的options中 獲取到的
inDensity:Bitmap位圖自身的密度淡溯、分辨率
inTargetDensity: Bitmap最終繪制的目標(biāo)位置的分辨率
inScreenDensity: 設(shè)備屏幕分辨率
其中inDensity和圖片存放的資源文件的目錄有關(guān),同一張圖片放置在不同目錄下會(huì)有不同的值:
可以驗(yàn)證幾個(gè)結(jié)論:
- 圖片放在drawable中簿训,等同于放在drawable-mdpi中咱娶,原因?yàn)?drawable目錄不具有屏幕密度特
性,所以采用基準(zhǔn)值强品,即mdpi - 圖片放在某個(gè)特定drawable中膘侮,比如drawable-hdpi,如果設(shè)備的屏幕密度高于當(dāng)前drawable目
錄所代表的密度的榛,則圖片會(huì)被放大琼了,否則會(huì)被縮小 放大或縮小比例 = 設(shè)備屏幕密度 / drawable目錄所代表的屏幕密度
因此,關(guān)于Bitmap占用內(nèi)存大小的公式夫晌,從之前:
Bitmap內(nèi)存占用 ≈ 像素?cái)?shù)據(jù)總大小 = 橫向像素?cái)?shù)量 × 縱向像素?cái)?shù)量 × 每個(gè)像素的字節(jié)大小
可以更細(xì)化為:
Bitmap內(nèi)存占用 ≈ 像素?cái)?shù)據(jù)總大小 = 圖片寬 × 圖片高× (設(shè)備分辨率/資源目錄分辨率)^2 × 每個(gè)像 素的字節(jié)大小
高效加載大型位圖雕薪,請(qǐng)參考官網(wǎng)
https://developer.android.com/topic/performance/graphics/load-bitmap
緩存位圖,請(qǐng)參考官網(wǎng)
https://developer.android.com/topic/performance/graphics/cache-bitmap
管理位圖晓淀,請(qǐng)參考官網(wǎng)
https://developer.android.com/topic/performance/graphics/manage-memory
本篇參考了http://www.reibang.com/p/3f6f6e4f1c88