Android 讀取不同位置(drawable,asset,SDCard)的圖片資源

來源:互聯網
上載者:User

方式一:

已將圖片儲存到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);

建議使用隨機讀寫檔案流,可以防止讀取的檔案流過大而導致記憶體溢出

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.