44

嗨,我有一个 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 字符串,我没有收到任何错误。但它不显示图像。可能是什么问题?谢谢

4

4 回答 4

58

请试试这个:

byte[] decodedString = Base64.decode(person_object.getPhoto(),Base64.NO_WRAP);
InputStream inputStream  = new ByteArrayInputStream(decodedString);
Bitmap bitmap  = BitmapFactory.decodeStream(inputStream);
user_image.setImageBitmap(bitmap);
于 2013-03-10T15:30:41.327 回答
6

有一个名为Picasso的库,它可以有效地从 URL 加载图像。它还可以从文件中加载图像。

例子:

  1. 将 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
    
  2. 通过生成位图将 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) {
    
               }
           });
    

毕加索还有更多选择。这是文档

于 2016-02-23T11:52:01.150 回答
6
    //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
于 2019-12-12T06:48:17.130 回答
5

这段代码适用于我

 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);
于 2018-06-11T10:11:49.930 回答