如何将Base64字符串转换为Bitmap图像以在ImageView中显示?

问题描述 投票:0回答:10

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

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

如何做?

这是我用来将图像转换为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);
android base64 imageview
10个回答
431
投票

您基本上可以使用其他一些内置方法来恢复代码。

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

83
投票

对于仍然对这个问题感兴趣的人: 如果: 1-decodeByteArray 返回 null 2-Base64.decode 抛出 bad-base64 异常

解决办法如下: -您应该考虑从 API 发送给您的值是 Base64 编码的,并且应该首先解码,以便将其转换为 Bitmap 对象! -看看你的 Base64 编码字符串,如果它以

开头

数据:图像/jpg;base64

Base64.decode 将无法解码它,因此必须将其从编码字符串中删除:

final String encodedString = "data:image/jpg;base64, ....";                        
final String pureBase64Encoded = encodedString.substring(encodedString.indexOf(",")  + 1);

现在 pureBase64Encoded 对象已准备好进行解码:

final byte[] decodedBytes = Base64.decode(pureBase64Encoded, Base64.DEFAULT);

现在只需使用下面的行将其转换为Bitmap对象即可! :

Bitmap decodedBitmap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);

或者如果您正在使用很棒的库Glide

Glide.with(CaptchaFragment.this).load(decodedBytes).crossFade().fitCenter().into(mCatpchaImageView);

这应该可以完成工作!浪费了一天时间才想到这个解决方案!

注意: 如果您仍然遇到 bad-base64 错误,请考虑其他 Base64.decode 标志,例如 Base64.URL_SAFE 等


18
投票

这是一个非常古老的线程,但我想分享这个答案,因为我花了很多开发时间来管理

NULL
返回
BitmapFactory.decodeByteArray()
,就像@Anirudh所面临的那样。

如果

encodedImage
字符串是
JSON
响应,只需使用
Base64.URL_SAFE
而不是
Base64.DEAULT

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

15
投票

要在线检查,您可以使用

http://codebeautify.org/base64-to-image-converter

您可以像这样将字符串转换为图像

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView image =(ImageView)findViewById(R.id.image);

        //encode image to base64 string
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);

        //decode base64 string to image
        imageBytes = Base64.decode(imageString, Base64.DEFAULT);
        Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
        image.setImageBitmap(decodedImage);
    }
}

http://www.thecrazyprogrammer.com/2016/10/android-convert-image-base64-string-base64-string-image.html


8
投票

这是一个很好的示例:

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

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


5
投票

我找到了这个简单的解决方案

要将位图转换为 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);
}

2
投票

在 Kotlin 中,您可以使用扩展函数,如下所示:

fun String.base64ToByteCode() = Base64.decode(this.substring(this.indexOf(",")  + 1), Base64.DEFAULT)

并称其如下:

yourBase64String.base64ToByteCode()

1
投票

这个解决方案对我来说效果很好。如果您收到 null,请告诉我。

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);
    
            
        }

0
投票

我已经尝试了所有解决方案,这个解决方案对我有用

let temp = base64String.components(separatedBy: ",")
let dataDecoded : Data = Data(base64Encoded: temp[1], options: 
 .ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)

yourImage.image = decodedimage

0
投票

在 Kotlin 中,您可以在 ImageView 上创建扩展函数,如下所示:

fun ImageView.loadFromBase64(encodedImageString: String) {
    try {
         val base64Image = encodedImageString.split(",")[1]
         val decodedString = Base64.decode(base64Image, Base64.DEFAULT)
         val bitmap = 
         BitmapFactory.decodeByteArray(decodedString,0,decodedString.size)
         setImageBitmap(bitmap)
    } catch (e: Exception) {
         Timber.d("Error loading image from base64: ${e.message}")
    }
}

使用时,您可以轻松做到:

imageView.loadFromBase64(encodedImageString)
© www.soinside.com 2019 - 2024. All rights reserved.