从获取方式分:
(1)以文件流的方式
假设在sdcard下有 test.png图片
FileInputStream fis = new FileInputStream("/sdcard/test.png");
Bitmap bitmap=BitmapFactory.decodeStream(fis);
(2)以R文件的方式
假设 res/drawable下有 test.jpg文件
Bitmap bitmap =BitmapFactory.decodeResource(getResources(), R.drawable.test);
//或者
BitmapDrawable bitmapDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.test);
Bitmap bitmap = bitmapDrawable.getBitmap();
(3)以ResourceStream的方式,不用R文件
Bitmap bitmap=BitmapFactory.decodeStream(getClass().getResourceAsStream(“/res/drawable/test.png”));
(4)以文件流+R文件的方式
InputStream in = getResources().openRawResource(R.drawable.test);
Bitmap bitmap = BitmapFactory.decodeStream(in);
//或者
InputStream in = getResources().openRawResource(R.drawable.test);
BitmapDrawable bitmapDrawable = new BitmapDrawable(in);
Bitmap bitmap = bitmapDrawable.getBitmap();
注意:openRawResource可以打开drawable, sound, 和raw资源,但不能是string和color。
从资源存放路径分:
(1)图片放在sdcard中
Bitmap imageBitmap = BitmapFactory.decodeFile(path);// (path 是图片的路径,跟目录是/sdcard)
(2)图片在项目的res文件夹下面
ApplicationInfo appInfo = getApplicationInfo();
//得到该图片的id(name 是该图片的名字,"drawable" 是该图片存放的目录,appInfo.packageName是应用程序的包)
int resID = getResources().getIdentifier(fileName, "drawable", appInfo.packageName);
Bitmap imageBitmap2 = BitmapFactory.decodeResource(getResources(), resID);
(3)图片放在src目录下
String path = "com/xiangmu/test.png"; //图片存放的路径
InputStream in = getClassLoader().getResourceAsStream(path); //得到图片流
Bitmap imageBitmap3 = BitmapFactory.decodeStream(in);
(4)图片放在Assets目录
InputStream in = getResources().getAssets().open(fileName);
Bitmap imageBitmap4 = BitmapFactory.decodeStream(in);
贴一个获取Bitmap的工具类
/**
* 获取Bitmap的工具类
*/
public class BitmapUtils {
/**
* 通过BitmapDrawable来获取Bitmap
* @param mContext
* @param fileName
* @return
*/
public static Bitmap getBitmapFromBitmapDrawable(Context mContext, String fileName) {
BitmapDrawable bmpMeizi = null;
try {
bmpMeizi = new BitmapDrawable(mContext.getAssets().open(fileName));//"pic_meizi.jpg"
Bitmap mBitmap = bmpMeizi.getBitmap();
return mBitmap;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 通过资源ID获取Bitmap
* @param res
* @param resId
* @return
*/
public static Bitmap getBitmapFromResource(Resources res, int resId) {
return BitmapFactory.decodeResource(res, resId);
}
/**
* 通过文件路径来获取Bitmap
* @param pathName
* @return
*/
public static Bitmap getBitmapFromFile(String pathName) {
return BitmapFactory.decodeFile(pathName);
}
/**
* 通过字节数组来获取Bitmap
* @param b
* @return
*/
public static Bitmap Bytes2Bimap(byte[] b) {
if (b.length != 0) {
return BitmapFactory.decodeByteArray(b, 0, b.length);
} else {
return null;
}
}
/**
* 通过输入流InputStream来获取Bitmap
* @param inputStream
* @return
*/
public static Bitmap getBitmapFromStream(InputStream inputStream) {
return BitmapFactory.decodeStream(inputStream);
}
}
感谢:
https://blog.youkuaiyun.com/u012861467/article/details/52013795
https://blog.youkuaiyun.com/lpCrazyBoy/article/details/81003043