提供一個(gè)獲取Bitmap的工具類:
package com.example.administrator.bitmapfactory;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.View;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by AFinalStone on 2017/6/27.
* 郵箱:602392033@qq.com
* 使用完畢Bitmap之后,我們可以通過(guò)Bitmap.recycle()方法來(lái)釋放位圖所占的空間诵冒,當(dāng)然前提是位圖沒(méi)有被使用诞挨。
*/
public class BitmapUtil {
/**
* 從path中獲取圖片信息,在通過(guò)BitmapFactory.decodeFile(String path)方法將突破轉(zhuǎn)成Bitmap時(shí)罗侯,
* 遇到大一些的圖片弟蚀,我們經(jīng)常會(huì)遇到OOM(Out Of Memory)的問(wèn)題勾效。所以用到了我們上面提到的BitmapFactory.Options這個(gè)類胳螟。
*
* @param path 文件路徑
* @param width 想要顯示的圖片的寬度
* @param height 想要顯示的圖片的高度
* @return
*/
public static Bitmap decodeBitmap(String path, int width, int height) {
BitmapFactory.Options op = new BitmapFactory.Options();
// inJustDecodeBounds如果設(shè)置為true,僅僅返回圖片實(shí)際的寬和高,寬和高是賦值給opts.outWidth,opts.outHeight;
op.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(path, op); //獲取尺寸信息
//獲取比例大小
int wRatio = (int) Math.ceil(op.outWidth / width);
int hRatio = (int) Math.ceil(op.outHeight / height);
//如果超出指定大小唆垃,則縮小相應(yīng)的比例
if (wRatio > 1 && hRatio > 1) {
if (wRatio > hRatio) {
op.inSampleSize = wRatio;
} else {
op.inSampleSize = hRatio;
}
}
op.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeFile(path, op);
return bmp;
}
/** 從path中獲取Bitmap圖片
* @param path 圖片路徑
* @return
*/
public static Bitmap decodeBitmap(String path) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, opts);
opts.inSampleSize = computeSampleSize(opts, -1, 128*128);
opts.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, opts);
}
/**
* 以最省內(nèi)存的方式讀取本地資源的圖片
* @param context 設(shè)備上下文
* @param resId 資源ID
* @return
*/
public static Bitmap decodeBitmap(Context context, int resId){
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
//獲取資源圖片
InputStream is = context.getResources().openRawResource(resId);
return BitmapFactory.decodeStream(is,null,opt);
}
/**
* @param context 設(shè)備上下文
* @param resId 資源ID
* @param width
* @param height
* @return
*/
public static Bitmap decodeBitmap(Context context,int resId, int width, int height) {
InputStream inputStream = context.getResources().openRawResource(resId);
BitmapFactory.Options op = new BitmapFactory.Options();
// inJustDecodeBounds如果設(shè)置為true,僅僅返回圖片實(shí)際的寬和高,寬和高是賦值給opts.outWidth,opts.outHeight;
op.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeStream(inputStream, null, op); //獲取尺寸信息
//獲取比例大小
int wRatio = (int) Math.ceil(op.outWidth / width);
int hRatio = (int) Math.ceil(op.outHeight / height);
//如果超出指定大小,則縮小相應(yīng)的比例
if (wRatio > 1 && hRatio > 1) {
if (wRatio > hRatio) {
op.inSampleSize = wRatio;
} else {
op.inSampleSize = hRatio;
}
}
inputStream = context.getResources().openRawResource(resId);
op.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(inputStream, null, op);
}
/**
* @param context 設(shè)備上下文
* @param fileNameInAssets Assets里面文件的名稱
* @param width 圖片的寬度
* @param height 圖片的高度
* @return Bitmap
* @throws IOException
*/
public static Bitmap decodeBitmap(Context context, String fileNameInAssets, int width, int height) throws IOException {
InputStream inputStream = context.getAssets().open(fileNameInAssets);
BitmapFactory.Options op = new BitmapFactory.Options();
// inJustDecodeBounds如果設(shè)置為true,僅僅返回圖片實(shí)際的寬和高,寬和高是賦值給opts.outWidth,opts.outHeight;
op.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeStream(inputStream, null, op); //獲取尺寸信息
//獲取比例大小
int wRatio = (int) Math.ceil(op.outWidth / width);
int hRatio = (int) Math.ceil(op.outHeight / height);
//如果超出指定大小趁猴,則縮小相應(yīng)的比例
if (wRatio > 1 && hRatio > 1) {
if (wRatio > hRatio) {
op.inSampleSize = wRatio;
} else {
op.inSampleSize = hRatio;
}
}
inputStream = context.getAssets().open(fileNameInAssets);
op.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(inputStream, null, op);
}
/**
* @param view
* @return
* 把View轉(zhuǎn)化為Bitmap,要在子線程內(nèi)讀取
*/
public static Bitmap convertViewToBitmap(View view){
//當(dāng)所需要的drawingCache >系統(tǒng)所提供的最大DrawingCache值時(shí)刊咳,生成Bitmap就會(huì)出現(xiàn)問(wèn)題,此時(shí)獲取的Bitmap就為null儡司。
//所以需要修改所需的cache值
view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
//獲取緩存
view.setDrawingCacheEnabled(true);
Bitmap bitmap = view.getDrawingCache();
//清空畫圖緩沖區(qū)
view.setDrawingCacheEnabled(false);
return bitmap;
}
//通過(guò)畫筆和View轉(zhuǎn)化成bitmap
public static Bitmap convertViewToBitmapByCanvas(View view)
{
// Define a bitmap with the same size as the view
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
// Bind a canvas to it
Canvas canvas = new Canvas(returnedBitmap);
// Get the view's background
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
// has background drawable, then draw it on the canvas
bgDrawable.draw(canvas);
else
// does not have background drawable, then draw white background on
// the canvas
canvas.drawColor(Color.WHITE);
// draw the view on the canvas
view.draw(canvas);
// return the bitmap
return returnedBitmap;
}
//圖片不被壓縮
public static Bitmap convertViewToBitmap(View view, int bitmapWidth, int bitmapHeight){
Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
view.draw(new Canvas(bitmap));
return bitmap;
}
/**
* @param options
* @param minSideLength
* @param maxNumOfPixels
* @return
* 設(shè)置恰當(dāng)?shù)膇nSampleSize是解決該問(wèn)題的關(guān)鍵之一娱挨。BitmapFactory.Options提供了另一個(gè)成員inJustDecodeBounds。
* 設(shè)置inJustDecodeBounds為true后捕犬,decodeFile并不分配空間跷坝,但可計(jì)算出原始圖片的長(zhǎng)度和寬度,即opts.width和opts.height碉碉。
* 有了這兩個(gè)參數(shù)柴钻,再通過(guò)一定的算法,即可得到一個(gè)恰當(dāng)?shù)膇nSampleSize垢粮。
* 查看Android源碼顿颅,Android提供了下面這種動(dòng)態(tài)計(jì)算的方法。
*/
public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
int roundedSize;
if (initialSize <= 8) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
}
return roundedSize;
}
private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight;
int lowerBound = (maxNumOfPixels == -1) ? 1 :
(int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));
if (upperBound < lowerBound) {
// return the larger one when there is no overlapping zone.
return lowerBound;
}
if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
return 1;
} else if (minSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
}
}
盡量不要使用setImageBitmap或setImageResource或BitmapFactory.decodeResource來(lái)設(shè)置一張大圖,
因?yàn)檫@些函數(shù)在完成decode后粱腻,最終都是通過(guò)java層的createBitmap來(lái)完成的,需要消耗更多內(nèi)存斩跌,容易出現(xiàn)OOM異常绍些。
因此,改用先通過(guò)BitmapFactory.decodeStream方法耀鸦,創(chuàng)建出一個(gè)bitmap柬批,再將其設(shè)為ImageView的source,
decodeStream最大的秘密在于其直接調(diào)用JNI>>nativeDecodeAsset()來(lái)完成decode袖订,無(wú)需再使用java層的createBitmap氮帐,從而節(jié)省了java層的空間。
如果在讀取時(shí)加上圖片的Config參數(shù)洛姑,可以更有效減少加載的內(nèi)存上沐,從而更有效阻止拋out of Memory異常。
另外楞艾,decodeStream直接拿的圖片來(lái)讀取字節(jié)碼了参咙, 不會(huì)根據(jù)機(jī)器的各種分辨率來(lái)自動(dòng)適應(yīng), 使用了decodeStream之后硫眯,
需要在hdpi和mdpi蕴侧,ldpi中配置相應(yīng)的圖片資源, 否則在不同分辨率機(jī)器上都是同樣大辛饺搿(像素點(diǎn)數(shù)量)净宵,顯示出來(lái)的大小就不對(duì)了。
另外裹纳,以下方式也大有幫助:
InputStream is = this.getResources().openRawResource(R.drawable.pic1);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inSampleSize = 10; //width择葡,hight設(shè)為原來(lái)的十分一
Bitmap btp =BitmapFactory.decodeStream(is,null,options);
if(!bmp.isRecycle() ){
bmp.recycle() //回收?qǐng)D片所占的內(nèi)存
system.gc() //提醒系統(tǒng)及時(shí)回收
}
項(xiàng)目地址:傳送門