嗨我有一个Base64格式的字符串。我想将它转换为位图,然后将其显示到ImageView。这是代码:
ImageView user_image;
Person person_object;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_profile_screen);
// ImageViews
user_image = (ImageView) findViewById(R.id.userImageProfile);
Bundle data = getIntent().getExtras();
person_object = data.getParcelable("person_object");
// getPhoto() function returns a Base64 String
byte[] decodedString = Base64.decode(person_object.getPhoto(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
user_image.setImageBitmap(decodedByte);
}
此代码成功获取Base64字符串,我没有收到任何错误。但它不显示图像。 可能是什么问题? 感谢
答案 0 :(得分:37)
请试试这个:
byte[] decodedString = Base64.decode(person_object.getPhoto(),Base64.NO_WRAP);
InputStream inputStream = new ByteArrayInputStream(decodedString);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
user_image.setImageBitmap(bitmap);
答案 1 :(得分:6)
有一个名为 Picasso 的库可以有效地从URL加载图像。它还可以从文件加载图像。
示例:
在不生成位图的情况下将URL加载到ImageView中:
Picasso.with(context) // Context
.load("http://abc.imgur.com/gxsg.png") // URL or file
.into(imageView); // An ImageView object to show the loaded image
通过生成位图将URL加载到ImageView中:
Picasso.with(this)
.load(artistImageUrl)
.into(new Target() {
@Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
/* Save the bitmap or do something with it here */
// Set it in the ImageView
theView.setImageBitmap(bitmap)
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
毕加索还有更多选择。 Here is the documentation
答案 2 :(得分:1)
此代码与我合作
ImageView carView = (ImageView) v.findViewById(R.id.car_icon);
byte[] decodedString = Base64.decode(picture, Base64.NO_WRAP);
InputStream input=new ByteArrayInputStream(decodedString);
Bitmap ext_pic = BitmapFactory.decodeStream(input);
carView.setImageBitmap(ext_pic);
答案 3 :(得分:1)
//decode base64 string to image
imageBytes = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
image.setImageBitmap(decodedImage);
//setImageBitmap is imp