天天看點

android 手機圖庫擷取sd卡圖檔,關于Android讀取不同位置(drawable,asset,SDCard)的圖檔資源的總結...

近日做到從記憶體卡讀取圖檔的功能,在此,對擷取圖檔資源的方法稍作總結:

方式一:

已将圖檔儲存到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(兩種方法)

int id =res.getIdentifier(name, defType, defPackage); //name:圖檔的名,defType:資源類型(drawable,string。。。),defPackage:工程的包名

Drawable drawable=getResource().getDrawable(id);

方式二:

已将圖檔儲存到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)檔案輸入流

fis = new FileInputStream(new File(imgFilePath));//檔案輸入流

Bitmap bmp = BitmapFactory.decodeStream(fis);

(2)

ImageView iv = (ImageView) findViewById(R.id.image);

Bitmap bit = BitmapFactory.decodeFile("/sdcard/android.bmp");

iv.setImageBitmap(bit);

iv.setImageDrawable(Drawable.createFromPath(new File(Environment.getExternalStorageDirectory(), "camera.jpg").getAbsolutePath()));