2

I use the following method to resize images on Android.

public Bitmap resize(Bitmap img, int Width, int Height) {

    int width = img.getWidth();     
    int height = img.getHeight();
    int newWidth = (int) Width;
    int newHeight = (int) Height;

    // calculate the scale - in this case = 0.4f
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;

    // createa matrix for the manipulation
    Matrix matrix = new Matrix();

    // resize the bit map
    matrix.postScale(scaleWidth, scaleHeight);

    // rotate the Bitmap
    //matrix.postRotate(45);

    // recreate the new Bitmap
    Bitmap resizedBitmap = Bitmap.createBitmap(img, 0, 0, width, height, matrix, true);

    return resizedBitmap;
} 

It works fine on most Android devices. But on some devices the resized image is not displaying. How might I resolve this?

4
  • are you calling this for static images or server images?? Commented Sep 2, 2013 at 14:12
  • 1
    Sounds like you've made a good start! Could you be more precise about how the bitmap is/isn't showing: examples: is it being passed into an imageView, drawable, or being drawn directly onto a canvas? Commented Sep 2, 2013 at 14:12
  • 3
    what do you mean the image is not displaying? also, is the density of both bitmaps set to be the same? Commented Sep 2, 2013 at 14:12
  • The problem occurs for Sprite bitmap with 10 frames. The width and height of each frame is 30 percentage of screenWidth and screenHeight. i use the below code to paint the bitmap, Rect destRect = new Rect(x, y, x + spriteWidth, y + spriteHeight); canvas.drawBitmap(bitmap, sourceRect, destRect, paint); Commented Sep 3, 2013 at 7:04

2 Answers 2

1

You may create a scaled bitmap with

Bitmap bitmap = Bitmap.createScaledBitmap(b, width, height, true);

Here, width and height you can provide according to the device's screen size for different devices, by reading screen sizes programmatically. Here is how you can read the screen size of a device programmatically.

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

1 Comment

I have no problem in getting the screenSize of the device.
0

Most likely, on "some devices" and depending on the requested width and height, there's not enough memory to create the resized bitmap. Check (in debugger) if the resizedBitmap is null when the image "is not displaying".

1 Comment

image is not null after resize

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.