在Android中向ImageView显示byte []

fir*_*iel 18 android

是否有可能做到这一点?我正在读取一个包含图像的Base64字符串的XML文件.我打算使用Base64.decode来获取图像字符串的字节数组.我对如何在ImageView中使用它感到困惑.我是否必须首先创建一个'drawable'类,然后将其设置为ImageView的src属性?

谢谢!

Rob*_*oll 51

如果其他人偶然发现这个问题,这里是代码

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

public class ModelAssistant {

    public static void setImageViewWithByteArray(ImageView view, byte[] data) {
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        view.setImageBitmap(bitmap);
    }
}
Run Code Online (Sandbox Code Playgroud)


Rom*_*Guy 30

您可以使用BitmapFactory.decodeByteArray()来执行解码.

  • 这里是一个清晰示例代码的链接:http://www.higherpass.com/Android/Tutorials/Working-With-Images-In-Android/2/ (4认同)

Chi*_*moy 5

// Convert bytes data into a Bitmap
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
ImageView imageView = new ImageView(ConversationsActivity.this);
// Set the Bitmap data to the ImageView
imageView.setImageBitmap(bmp);

// Get the Root View of the layout
ViewGroup layout = (ViewGroup) findViewById(android.R.id.content);
// Add the ImageView to the Layout
layout.addView(imageView);
Run Code Online (Sandbox Code Playgroud)

我们使用 Bitmap.decodeByteArray() 将我们的字节数据转换为 Bitmap,然后将其设置为新创建的 ImageView。