How to resize an image to fit multiple screen densities

HGPB picture HGPB · Dec 1, 2012 · Viewed 7.3k times · Source

I need to add an avatar to a grid item.

I want to know how to handle the resizing of an image chosen from the phones gallery. Once chosen, I imagine some resizing will be needed, to fit it into the grid.

However, do I need to store a resized image for each screen density; store one xhdpi version and scale down for other devices, or be clever in some other way?

The reason is, the app stores this image to a cloud db and other people can download this image. They may see the image on different devices (hence the requirement of different image sizes). How should the managment of this image be processed?

Answer

AZ_ picture AZ_ · Apr 26, 2013

Do something like this:

 DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    Bitmap bitmapOrg = new BitmapDrawable(getResources(), new  ByteArrayInputStream(imageThumbnail)).getBitmap();

    int width = bitmapOrg.getWidth();
    int height = bitmapOrg.getHeight();

    float scaleWidth = metrics.scaledDensity;
    float scaleHeight = metrics.scaledDensity;

    // create a matrix for the manipulation
    Matrix matrix = new Matrix();
    // resize the bit map
    matrix.postScale(scaleWidth, scaleHeight);

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