Get images from Raw folder using only name of Images in Andriod
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);
0 comments: