Reading image resources from different locations (drawable, asset, SDCard) in Android

Source: Internet
Author: User

Reading image resources from different locations (drawable, asset, SDCard) in Android

Method 1:

You have saved the image to the drawable directory and obtained the Drawable or Bitmap by using the image id. This method is most commonly used. (If you only know the image name, you can also obtain the image id through the image name)

(1) Obtain Drawable by image id

Drawable drawable = getResource (). getDrawable (R. drawable. xxx );

(2) Obtain Bitmap by image id

Resource res = gerResource ();

Bitmap bitmap = BitmapFactory. decodeResource (res, id );

(3) obtain the image id using the image name (two methods)

Int id = res. getIdentifier (name, defType, defPackage); // name: image name, defType: resource type (drawable, string ...), DefPackage: project package name

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


Method 2:

You have saved the image to the assest directory. You can use inputstream to obtain the image Drawabl.

Or Bitmap

AssetManager asm = getAssetMg ();

InputStream is = asm. open (name); // name: image name

(1) Obtain Drawable
Drawable da = Drawable. createFromStream (is, null );

(2) Obtain Bitmap
Bitmap bitmap = BitmapFactory. decodeStream (is );


Method 3: Save the image to sdcard.

/Image path
String imgFilePath = Environment. getExternalStorageDirectory (). toString ()
+ "/DCIM/device.png ";

(1) file input stream

FS = new FileInputStream (new File (imgFilePath); // File input stream

Bitmap bmp = BitmapFactory. decodeStream (FCM );

(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 ()));

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.