Resize image generated by BitmapFactory.decodeByteArray()

Muhammad Resna Rizki Pratama picture Muhammad Resna Rizki Pratama · Jun 8, 2012 · Viewed 8.7k times · Source

I am creating audio player,I want to show the song cover to the player, it working with small image but if the mp3 file have large image then it goes out of layout view. I'm re-sizing image to 300x300 by using below code:

BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inDensity = 300;
opt.inTargetDensity = 300;

songCoverView.setImageBitmap(BitmapFactory.decodeByteArray(songCover, 0, songCover.length, opt));

But it still shows larger and goes out of layout.

Whats wrong with this code?

Answer

Ashraf Sousa picture Ashraf Sousa · Jun 9, 2012

try Bitmap.createScaledBitmap

bitmap = Bitmap.createScaledBitmap(songCover, 300, 300, true);

And you can keep the same aspect ratio for the old image... I use the following logic:

        int width  = songCover.getWidth();
        int height = songCover.getHeight();
        float scaleHeight = (float)height/(float)300;
        float scaleWidth  = (float)width /(float)300;
        if (scaleWidth < scaleHeight) scale = scaleHeight;
        else                          scale = scaleWidth;

        bitmap = Bitmap.createScaledBitmap(songCover, (int)(width/scale), (int)(height/scale), true);