方式一:
已將圖片儲存到drawable目錄下,通過圖片id獲得Drawable或者Bitmap,此方式最常用。(若只知道圖片的名稱,還可以通過圖片的名稱獲得圖片的id)
(1)通過圖片id獲得Drawable
Drawable drawable=getResource().getDrawable(R.drawable.xxx);
(2)通過圖片id獲得Bitmap
Resource res=gerResource();
Bitmap bitmap=BitmapFactory.decodeResource(res, id);
(3)通過圖片的名稱獲得圖片的id(兩種方法)
方法1: int id =res.getIdentifier(name, defType, defPackage); //name:圖片的名,defType:資源類型(drawable,string。。。),defPackage:工程的包名
方法2:
// 用反射機制來擷取資源中的圖片ID和尺
Field[] fields = R.drawable.class.getDeclaredFields()
for (Field field : fields) {
if (!”icon”.equals(field.getName()))// 除了icon之外的圖片
{
int index = 0;
try {
index = field.getInt(R.drawable.class);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 儲存圖片ID
imgList.add(index);
}
}
獲得id之後可以根據你的需要來獲得Bitmap或Drawable
方式二:
已將圖片儲存到assest目錄下,知道圖片的名稱,通過inputstream獲得圖片Drawabl
或者 Bitmap
AssetManager asm=getAssetMg();
InputStream is=asm.open(name);//name:圖片的名稱
(1)獲得Drawable
Drawable da = Drawable.createFromStream(is, null);
(2)獲得Bitmap
Bitmap bitmap=BitmapFactory.decodeStream(is);
方式三:圖片儲存在sdcard,通過圖片的路徑h
/圖片路徑
String imgFilePath = Environment.getExternalStorageDirectory().toString()
+ “/DCIM/device.png”;
(1)檔案輸入資料流
public Bitmap getBitmapFromSd(String imgFilePath) {
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(imgFilePath));//檔案輸入資料流
Bitmap bmp = BitmapFactory.decodeStream(fis);
Log.d(“sss”, bmp + “”);
return bmp;
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
try {
if(fis!=null){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
(2)隨機讀寫檔案流
RandomAccessFile raf;
File imgfile = new File(path);
try {
raf = new RandomAccessFile(imgfile, “r”);//以讀的方式讀取檔案流
}
catch (IOException ex) {
e.printStackTrace();
} finally{
try {
if(fis!=null){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
data= new byte[1024];
try {
mMiniThumbFile.seek(0);
int got = mMiniThumbFile.read(data, 0, 1024);
} catch (IOException e) {
e.printStackTrace();
}
if (data != null) {
//通過data獲得bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
建議使用隨機讀寫檔案流,可以防止讀取的檔案流過大而導致記憶體溢出