user1128677
user1128677

Reputation: 479

creating BitmapDrawable from path

i'm trying to create a Bitmap

 BitmapDrawable img = new BitmapDrawable(getResources(), "res/drawable/wrench.png");
 Bitmap wrench = img.getBitmap();
 //Bitmap wrench = BitmapFactory.decodeResource(getResources(), R.drawable.wrench);
 canvas.drawColor(Color .BLACK);
 Log.d("OLOLOLO",Integer.toString(wrench.getHeight()));
 canvas.drawBitmap(wrench, left, top, null);

but when i call wrench.getHeight() program failed with NullPoinerException. (i put the file in drawable directory) how can i solve my problem?

Upvotes: 2

Views: 5477

Answers (3)

Nesim Razon
Nesim Razon

Reputation: 9794

You can do like this:

String imageNameWithoutExtension = "wrench";
int id = getResources().getIdentifier(imageNameWithoutExtension, "drawable", getPackageName());
Bitmap dd = BitmapFactory.decodeResource(getResources(), id);
logo.setImageBitmap(dd);

Upvotes: 1

JRaymond
JRaymond

Reputation: 11782

Ok... I think I have a handle on your problem now. Like I said, you can't access your drawables via a path, so if you want a human readable interface with your drawables that you can build programatically, declare a HashMap somewhere in your class:

private static HashMap<String, Integer> images = null;

Then initialize it in your constructor:

public myClass() {
  if (images == null) {
    images = new HashMap<String, Integer>();
    images.put("Human1Arm", R.drawable.human_one_arm);
    // for all your images - don't worry, this is really fast and will only happen once
  }
}

Now for access -

String drawable = "wrench";
// fill in this value however you want, but in the end you want Human1Arm etc
// access is fast and easy:
Bitmap wrench = BitmapFactory.decodeResource(getResources(), images.get(drawable));
canvas.drawColor(Color .BLACK);
Log.d("OLOLOLO",Integer.toString(wrench.getHeight()));
canvas.drawBitmap(wrench, left, top, null);

Upvotes: 2

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132992

try this:

            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.wrench);  
            Matrix matrix=new Matrix();
            matrix.postScale(0.2f, 0.2f);
            Bitmap dstbmp=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),
            bmp.getHeight(),matrix,true);
            canvas.drawColor(Color.BLACK);  
            canvas.drawBitmap(dstbmp, 10, 10, null);  

"res/drawable/wrench.png" not valid path so either use images from sbcard if you are using images from drawable then use R.drawable.wrench

It is not possible to get the exact path for an image , that is stored in drawable.

Why not? When you compile your app to an *.apk file, all resources (ok, except from them in /raw) are compiled as well. You can only acces them, using their R. id.

Solution? Not really, you could copy them to a location on the sd card for example. No you know the location :)

Upvotes: 2

Related Questions