Android 调整BitmapFactory.decodeByteArray()生成的图像的大小

Android 调整BitmapFactory.decodeByteArray()生成的图像的大小,android,image-resizing,bitmapfactory,Android,Image Resizing,Bitmapfactory,我正在创建音频播放器,我想向播放器显示歌曲封面,它可以处理小图像,但如果mp3文件有大图像,则它将退出布局视图。我正在使用以下代码将图像大小调整为300x300: BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inDensity = 300; opt.inTargetDensity = 300; songCoverView.setImageBitmap(BitmapFactory.decodeByteArray(son

我正在创建音频播放器,我想向播放器显示歌曲封面,它可以处理小图像,但如果mp3文件有大图像,则它将退出布局视图。我正在使用以下代码将图像大小调整为300x300:

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

songCoverView.setImageBitmap(BitmapFactory.decodeByteArray(songCover, 0, songCover.length, opt));
但它仍然显示更大,超出了布局

这个代码有什么问题吗?

试试看

bitmap=bitmap.createScaledBitmap(songCover,300300,true)

你可以为旧图像保持相同的纵横比。。。我使用以下逻辑:

        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);       
int-width=songCover.getWidth();
int height=songCover.getHeight();
浮标高度=(浮标)高度/(浮标)300;
浮动比例宽度=(浮动)宽度/(浮动)300;
如果(比例宽度<比例高度)比例=比例高度;
else比例=标度宽度;
位图=位图。createScaledBitmap(歌曲封面,(int)(宽度/比例),(int)(高度/比例),true);

发现Android中存在一个bug:decodeByteArray不知何故忽略了一些输入选项。一种已知的解决方法是使用decodeStream,将输入数组包装到ByteArrayInputStream中,如下所示:

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

songCoverView.setImageBitmap(BitmapFactory.decodeStream(new ByteArrayInputStream(songConver), null, opt));

可以使用位图的属性

Bitmap bitmap = Bitmap.createScaledBitmap(image, (int)x, (int)y, true);

但是,如果图像比例不是1:1,则图像看起来像是被迫使用该像素。对于示例,如html中的“最大宽度和最大高度”。@MuhammadResnaRizkiPratama,我在答案中添加了一个示例,向您展示如何保持旧的纵横比。代码示例实际上使用了decodeByteArray–显然,这是我的错误。更正了。