Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize image generated by BitmapFactory.decodeByteArray()

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?

like image 740
Muhammad Resna Rizki Pratama Avatar asked Dec 08 '22 23:12

Muhammad Resna Rizki Pratama


2 Answers

Turns out that there's a bug in Android: decodeByteArray somehow ignores some input options. A known workaround is using decodeStream with input array wrapped into ByteArrayInputStream instead, like this:

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

songCoverView.setImageBitmap(BitmapFactory.decodeStream(new ByteArrayInputStream(songConver), null, opt));
like image 67
Vlas Voloshin Avatar answered Jan 14 '23 13:01

Vlas Voloshin


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);       
like image 31
Ashraf Sousa Avatar answered Jan 14 '23 14:01

Ashraf Sousa