Get images from Raw folder using only name of Images in Andriod

11:03 AM 0 Comments

Sometime we need to get images from raw folder using its name. I came across one scenario where unity developer drop images in raw folder of Android system. Developer returned me only names of that images. And i needed to show dialog of that images using frame animation. There are only three steps to get images from raw folder through its name.

Step - 1: Get resource id of image using its name


int rid = context.getResources()
        .getIdentifier("image_name","raw", context.getPackageName());

Step - 2: Get input stream of image file using that resource id


Resources res = context.getResources();
InputStream in = res.openRawResource(rid);

Step- 3: Get drawable using that input stream


Drawable image = Drawable.createFromStream(in, "image_name"); 

Code snippet :


AnimationDrawable animation = new AnimationDrawable();
for (int count = 0; count < names.length; count++) {
 try {
  int rid = context.getResources().getIdentifier(names[count],
      "raw", context.getPackageName());
  Resources res = context.getResources();
  InputStream in = res.openRawResource(rid);

  byte[] b = new byte[in.available()];
  in.read(b);
  animation.addFrame(Drawable.createFromStream(in, names[count]),
      durationPerFrame);
 } catch (Exception e) {
  e.printStackTrace();
 }
}

animation.setOneShot(false);

Karn Shah

My name is Karn Shah, I am a software developer living in Ahmedabad,India and my job/hobby is Android. I have been working on the Android platform since 2011 and I hope that sharing what I have learned will help people get proficient in Android faster!

0 comments: