我有一个代表位图图像的Base64字符串。

我需要将字符串转换为位图图像再次使用它在ImageView在我的Android应用程序

怎么做呢?

这是我用来将图像转换为base64字符串的代码:

//proceso de transformar la imagen BitMap en un String:
//android:src="c:\logo.png"
Resources r = this.getResources();
Bitmap bm = BitmapFactory.decodeResource(r, R.drawable.logo);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object   
byte[] b = baos.toByteArray();
//String encodedImage = Base64.encode(b, Base64.DEFAULT);
encodedImage = Base64.encodeBytes(b);

当前回答

你可以使用其他内置的方法来恢复你的代码。

byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 

其他回答

这是一个很好的例子:

String base64String = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAA...";
String base64Image = base64String.split(",")[1];
byte[] decodedString = Base64.decode(base64Image, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imageView.setImageBitmap(decodedByte);

样本见于:https://freakycoder.com/android-notes-44-how-to-convert-base64-string-to-bitmap-53f98d5e57af

这是过去唯一对我有用的代码。

你可以使用其他内置的方法来恢复你的代码。

byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 

这是一个非常老的线程,但认为分享这个答案,因为它花了很多我的开发时间来管理BitmapFactory.decodeByteArray()的NULL返回@Anirudh已经面临。

如果encodedImage字符串是一个JSON响应,只需使用Base64。URL_SAFE而不是Base64。DEAULT

byte[] decodedString = Base64.decode(encodedImage, Base64.URL_SAFE);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

这个解决方案对我来说很有效。如果你没有收到,请让我知道。

private void bytesToImage(ImageView imageView, String base64String) {
        if (!base64String.isEmpty()) {
            byte[] bytes = Base64.decode(base64String, Base64.DEFAULT);
            Bitmap decodedByte = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    
           Glide.with(this).load(decodedByte).into(imageView);
    
            
        }

我找到了一个简单的解决方法

要将位图转换为Base64,请使用此方法。

private String convertBitmapToBase64(Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
    byte[] byteArray = byteArrayOutputStream .toByteArray();
    return Base64.encodeToString(byteArray, Base64.DEFAULT);
}

从Base64转换为位图或还原。

private Bitmap convertBase64ToBitmap(String b64) {
    byte[] imageAsBytes = Base64.decode(b64.getBytes(), Base64.DEFAULT);
    return BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
}