Android code to convert base64 string to bitmap

后端 未结 3 1244
既然无缘
既然无缘 2020-12-09 19:37

Hi stackoverflow team i have a problem in converting base64 string to bitmap in android. I am using the camera to fetch the image and i am convert the image to base64 string

相关标签:
3条回答
  • 2020-12-09 20:12

    EDIT: Accepted post has now been updated to copy my answer below, either are correct

    The accepted answer is not correct at least in JellyBean, KitKat or Lollipop. You should use the following which works for JPEG, PNG or GIF images.

    byte[] imageAsBytes = Base64.decode(myImageData.getBytes(), Base64.DEFAULT);
    ImageView image = (ImageView)this.findViewById(R.id.ImageView);
    image.setImageBitmap(
            BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
    );
    
    0 讨论(0)
  • 2020-12-09 20:20

    Assuming that your image data is in a String called myImageData, the following should do the trick:

        byte[] imageAsBytes = Base64.decode(myImageData.getBytes(), Base64.DEFAULT);
        ImageView image = (ImageView)this.findViewById(R.id.ImageView);
        image.setImageBitmap(
                BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
        );
    

    For Base64 decoding, you can use http://iharder.sourceforge.net/current/java/base64/ as Android doesn't contain Base64-support prior to 2.2.

    Note, I didn't actually run this code, so you'll have to doublecheck for errors.

    0 讨论(0)
  • 2020-12-09 20:26

    Write down the Simple method pass the Base64 String and it will return the Bitmap object

    Bitmap Base64ToBitmap(String myImageData)
        {
            byte[] imageAsBytes = Base64.decode(myImageData.getBytes(),Base64.DEFAULT);
            return BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
        }
    
    0 讨论(0)
提交回复
热议问题