Nik Myers
Nik Myers

Reputation: 1873

Creating scaled bitmap

I need to test a simple task. I want to create scaled bitmap by setting postScale to the Matrix and using it in the creation, here's a code:

Matrix matrix = new Matrix();
matrix.postScale(5.0f, 5.0f);
Bitmap bitmap = Bitmap.createBitmap(bitmapSrc, 500, 500, 50, 50, matrix, true);

I thought this code supposed to crop 50x50 bitmap from the source scaled in 5 times, but when i'm using this bitmap to show the result in ImageView

imageView.setImageBitmap(bitmap);

The scaling doesn't seem to work and i'm getting 50x50 bitmap from original source bitmap(without scaling).

I think i'm missing something, but i can't quite figure out what. Any help highly appreciated

Edit: I've also tried to set last parameter to false and it didn't help, but if i'm using postRotate in matrix i'm getting rotated bitmap

Upvotes: 0

Views: 398

Answers (2)

Björn Kechel
Björn Kechel

Reputation: 8453

It might be that the scaling happens too late and the crop area is out of bounds because of it. Did you try it with preScale instead of postScale?

If that does not work, you can try using coordinates within the small bitmap first, like this:

Bitmap bitmap = Bitmap.createBitmap(bitmapSrc, 100, 100, 10, 10, matrix, true);

Upvotes: 0

bijoyskochar
bijoyskochar

Reputation: 41

Android contains the function Bitmap.createScaledBitmap()... You can use this as follows:

public Bitmap getScaledBitmap(Bitmap bitmap, float scale) {
    Integer originalHeight = bitmap.getHeight();
    Integer originalWidth = bitmap.getWidth();

    Integer requiredHeight = Math.round(originalHeight * scale);
    Integer requiredWidth = Math.round(originalWidth * scale);

    return Bitmap.createScaledBitmap(bitmap, requiredWidth, requiredHeight, true);
}

You can checkout this for other relevant functions here.

Upvotes: 1

Related Questions