问题
I am stuck in a situation. I have some set of 10 images in drawable folder. During my code I have just the image name. for e.g "elephant.png" and I want the byte array of the image( drawable ) corressponding to image name.
String imageName = getResources().getResourceEntryName(GroupIconAdapter.mThumbIds[position]);
From here I get the image name and I want byte array.
Is is possible?
Thanks
回答1:
Put this images into your assests directory and you can access like this way
String url = "file:///android_asset/elephant.png";
回答2:
try as:
// get Drawable id
int drawableid =getResources().getIdentifier(GroupIconAdapter.mThumbIds[position],
"drawable",this.getPackageName());
Drawable drawable_img = getResources().getDrawable(drawableid); // get Drawable
Bitmap drawable_bitmap = ((BitmapDrawable)drawable_img).getBitmap();
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
drawable_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
// get byte array here
byte[] bytearray_of_drawable = outstream.toByteArray();
回答3:
I think this way should move right
First of all I should put my images in the assets folder and then making the drawbles for the same
String filePath="file:///android_asset/images/test.png";
Drawable d = Drawable.createFromPath(filePath);
and then doing the respective streamings to make a byte array -
Bitmap drawable_bitmap = ((BitmapDrawable)d).getBitmap();
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
drawable_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
// get byte array here
byte[] bytearray_of_drawable = outstream.toByteArray();
This way we can get the image name's drawable and corresponding byte array.
Thanks
来源:https://stackoverflow.com/questions/14055091/getting-the-byte-array-using-just-the-image-name