0

I'm following this S.O. post about how to crop an image using a Bitmap.

As confirmed in Android documentation, there is a method createBitmap() that has the following parameters:

createBitmap(Bitmap source, int x, int y, int width, int height)

But I don't understand what this Bitmap source needs to be. I believe it must refer to the image I wish to use for my Bitmap object. The image I wish to use is stored as a drawable named rainbow, so I tried the following:

    Bitmap cropedBitmap = Bitmap.createBitmap(R.id.rainbow, 0, 0, 300, 300);

In which case Android Studio reports "Cannot resolve symbol 'rainbow'

I also tried:

      Bitmap cropedBitmap = Bitmap.createBitmap(R.drawable.rainbow, 0, 0, 300, 300);

and Android Studio reports "Cannot resolve method createBitmap(int, int, int, int, int)

I see from the documentation that the first parameter is a Bitmap. Wouldn't that be using a Bitmap to create a Bitmap? Also I don't see any constructors for the Bitmap class on its documentation page.

Any suggestions on what I'm missing or what to try next?

2 Answers 2

0

If you want to crop out a piece of the Bitmap you can load the piece directly from resource into ram with BitmapFactory.Options Quite common when you animate things in games and the images are out of a bigger sprite

Sign up to request clarification or add additional context in comments.

Comments

0

R.drawable.rainbow is integer value not a Bitmap as it is just a generated identifier number of your resources.

You need to use a method to make drawable resource id into Bitmap object as this post did.

Edit: add options and drawable call method

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Drawable drawable = getResources().getDrawable(R.drawable.rainbow);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
Bitmap cropedBitmap = Bitmap.createBitmap(bitmap, options), 0, 0, 300, 300);

7 Comments

Please don't do this. This creates two bitmaps (one while decoding and then the scaled version), with the former up for garbage collection immediately. Given scarcity of bitmap memory, not creating the temporary bitmap is quite important, however.
@dhke // hi. thanks for pointint out. then how about ((BitmapDrawable)drawable).getBitmap();? will it be same?
@dhke Is there a good alternative? If so would like to post an answer?
Right too much overhead loading with options resolve such problems
@TimothySteele I'd suggest to always use an image loader library. The code to do it properly becomes rather long and messy once you start considering imSampleSize and the like.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.