get bitmap information from bitmap stored in drawable folder
I wanna read in a bitmap that I have in my drawable folder and store it as a Bitmap variable so that I can set it as a background. Would the best way to do this be using a "file reader"? like
Bitmap decodeFile (String pathName)开发者_JAVA技巧 method
Or is there a way to just set it like this:
Bitmap bmp = R.drawable."bitmapFileName";
(I have tried this but returns an int, just wondering if I was on the right track)
Any help would be great :)
The R.drawable."bitmapFileName"
is, indeed, just an integer, for it is an index (static integer) at your project's R class (see more here). You can load your bitmap from the resources's folder like this:
Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.yourBitmap);
I found this code at the Android Development Community.
I usually use the assets folder
InputStream is = parentActivity.getResources().getAssets().open(iconFile);
Bitmap bmp = BitmapFactory.decodeStream(is);
BitmapDrawable bitmapDrawable = new BitmapDrawable(is);
then just yourView.setBackgroundDrawable(bitmapDrawable);
It is possible to load a drawable or bitmap by name. Here is an example:
public Drawable getImageByName(String nameOfTheDrawable, Activity a){
Drawable drawFromPath;
int path = a.getResources().getIdentifier(nameOfTheDrawable,
"drawable", "com.mycompany.myapp");
Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap source = BitmapFactory.decodeResource(a.getResources(), path, options);
drawFromPath = new BitmapDrawable(source);
return drawFromPath;
}
You can of course return Bitmap instead a drawable.
Drawbale d = getImageByName("mageFileName", this);
/*
* You can get Bitmap from drawable resource id in the following way
*/
BitmapDrawable drawable = (BitmapDrawable)context.getResources()
.getDrawable(drawableId);
bitmap = drawable.getBitmap();
精彩评论