如何将图像转换为 Base64 字符串?

如何将图像转换为 Base64 字符串?

问题描述:

将图像(最大 200 KB)转换为 Base64 字符串的代码是什么?

What is the code to transform an image (maximum of 200 KB) into a Base64 String?

我需要知道如何在 Android 上做到这一点,因为我必须在我的主应用程序中添加将图像上传到远程服务器的功能,将它们作为字符串放入数据库的一行中.

I need to know how to do it with Android, because I have to add the functionality to upload images to a remote server in my main app, putting them into a row of the database, as a string.

我在 Google 和 Stack Overflow 中搜索,但我找不到我负担得起的简单示例,我也找到了一些示例,但它们并不是在谈论转换为字符串.然后我需要转换成一个字符串以通过 JSON 上传到我的远程服务器.

I am searching in Google and in Stack Overflow, but I could not find easy examples that I can afford and also I find some examples, but they are not talking about to transform into a String. Then I need to transform into a string to upload by JSON to my remote server.

您可以使用 Base64 Android 类:

You can use the Base64 Android class:

String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);

不过,您必须将图像转换为字节数组.举个例子:

You'll have to convert your image into a byte array though. Here's an example:

Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); // bm is the bitmap object
byte[] b = baos.toByteArray();

* 更新 *

如果您使用的是较旧的 SDK 库(因为您希望它在具有较旧版本操作系统的手机上运行),则不会将 Base64 类打包(因为它刚刚在 API 级别 8 AKA 版本中出现)2.2).

If you're using an older SDK library (because you want it to work on phones with older versions of the OS) you won't have the Base64 class packaged in (since it just came out in API level 8 AKA version 2.2).

查看这篇文章以获得解决方法:

Check this article out for a workaround:

如何base64编码解码安卓