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

将图像(最大200KB)转换为 Base64String 的代码是什么?

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

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

276447 次浏览

你可以使用 Base64 Android 类:

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

但是你必须把你的图像转换成一个字节数组,这里有一个例子:

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中发布)。

看看这篇文章,你会发现一个解决办法:

如何基64编码解码 Android

如果您需要 Base64 over JSON,请查看 杰克逊: 它在低级(JsonParser,JsonGenerator)和数据绑定级别都明确支持二进制数据作为 Base64读/写。因此,您可以只使用带有 byte []属性的 POJO,并自动处理编码/解码。

而且效率很高,如果这很重要的话。

与使用 Bitmap不同,您还可以通过一个简单的 InputStream来完成这项工作。我不确定,但我觉得有点效率。

InputStream inputStream = new FileInputStream(fileName); // You can get an inputStream using any I/O API
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();


try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
catch (IOException e) {
e.printStackTrace();
}


bytes = output.toByteArray();
String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);

这段代码在我的项目中运行得很完美:

profile_image.buildDrawingCache();
Bitmap bmap = profile_image.getDrawingCache();
String encodedImageData = getEncoded64ImageStringFromBitmap(bmap);




public String getEncoded64ImageStringFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
byte[] byteFormat = stream.toByteArray();


// Get the Base64 string
String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);


return imgString;
}
byte[] decodedString = Base64.decode(result.getBytes(), Base64.DEFAULT);
// Put the image file path into this method
public static String getFileToByte(String filePath){
Bitmap bmp = null;
ByteArrayOutputStream bos = null;
byte[] bt = null;
String encodeString = null;
try{
bmp = BitmapFactory.decodeFile(filePath);
bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bt = bos.toByteArray();
encodeString = Base64.encodeToString(bt, Base64.DEFAULT);
}
catch (Exception e){
e.printStackTrace();
}
return encodeString;
}

如果你在 仿生人上做这个,这里有一个从 本机代码库复制的助手:

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;


import android.util.Base64;
import android.util.Base64OutputStream;
import android.util.Log;


// You probably don't want to do this with large files
// (will allocate a large string and can cause an OOM crash).
private String readFileAsBase64String(String path) {
try {
InputStream is = new FileInputStream(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Base64OutputStream b64os = new Base64OutputStream(baos, Base64.DEFAULT);
byte[] buffer = new byte[8192];
int bytesRead;
try {
while ((bytesRead = is.read(buffer)) > -1) {
b64os.write(buffer, 0, bytesRead);
}
return baos.toString();
} catch (IOException e) {
Log.e(TAG, "Cannot read file " + path, e);
// Or throw if you prefer
return "";
} finally {
closeQuietly(is);
closeQuietly(b64os); // This also closes baos
}
} catch (FileNotFoundException e) {
Log.e(TAG, "File not found " + path, e);
// Or throw if you prefer
return "";
}
}


private static void closeQuietly(Closeable closeable) {
try {
closeable.close();
} catch (IOException e) {
}
}

使用以下代码:

byte[] decodedString = Base64.decode(Base64String.getBytes(), Base64.DEFAULT);


Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

下面是可能对您有帮助的伪代码:

public  String getBase64FromFile(String path)
{
Bitmap bmp = null;
ByteArrayOutputStream baos = null;
byte[] baat = null;
String encodeString = null;
try
{
bmp = BitmapFactory.decodeFile(path);
baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
baat = baos.toByteArray();
encodeString = Base64.encodeToString(baat, Base64.DEFAULT);
}
catch (Exception e)
{
e.printStackTrace();
}


return encodeString;
}

以下是 Kotlin 的编码和解码代码:

 fun encode(imageUri: Uri): String {
val input = activity.getContentResolver().openInputStream(imageUri)
val image = BitmapFactory.decodeStream(input , null, null)


// Encode image to base64 string
val baos = ByteArrayOutputStream()
image.compress(Bitmap.CompressFormat.JPEG, 100, baos)
var imageBytes = baos.toByteArray()
val imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT)
return imageString
}


fun decode(imageString: String) {


// Decode base64 string to image
val imageBytes = Base64.decode(imageString, Base64.DEFAULT)
val decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)


imageview.setImageBitmap(decodedImage)
}

在 Android 中将图像转换为 Base64字符串:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.yourimage);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);

对于那些正在寻找一种有效的方法来将图像文件转换为 Base64字符串而无需压缩或首先将文件转换为位图的人来说,您可以改为 将文件编码为 base64

val base64EncodedImage = FileInputStream(imageItem.localSrc).use {inputStream - >
ByteArrayOutputStream().use {outputStream - >
Base64OutputStream(outputStream, Base64.DEFAULT).use {
base64FilterStream - >
inputStream.copyTo(base64FilterStream)
base64FilterStream.flush()
outputStream.toString()
}
}
}

希望这个能帮上忙!

下面是图像编码和解码的代码。

在 XML 文件中

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yyuyuyuuyuyuyu"
android:id="@+id/tv5"
/>

在 Java 文件中:

TextView textView5;
Bitmap bitmap;


textView5 = (TextView) findViewById(R.id.tv5);


bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);


new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... voids) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] byteFormat = stream.toByteArray();


// Get the Base64 string
String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);


return imgString;
}


@Override
protected void onPostExecute(String s) {
textView5.setText(s);
}
}.execute();

我做了一个静态函数,我觉得效率更高。

public static String file2Base64(String filePath) {
FileInputStream fis = null;
String base64String = "";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
fis = new FileInputStream(filePath);
byte[] buffer = new byte[1024 * 100];
int count = 0;
while ((count = fis.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
base64String = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);
return base64String;


}

简单又容易!

科特林版本:

fun File.toBase64(): String? {
val result: String?
inputStream().use { inputStream ->
val sourceBytes = inputStream.readBytes()
result = Base64.encodeToString(sourceBytes, Base64.DEFAULT)
}


return result
}

在 Kotlin,你可以使用 byteArray 的 decode 函数... ..。

  private fun stringToBitmap(encodedString: String): Bitmap {
val imageBytes = decode(encodedString, DEFAULT)
return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
}

进行编码

 private String encodeImage(Bitmap bitmap){
int previewWidth=150;
int previewHeight=bitmap.getHeight()*previewWidth/ bitmap.getWidth();
Bitmap previewBitmap = Bitmap.createScaledBitmap(bitmap,previewWidth,previewHeight,false);
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
previewBitmap.compress(Bitmap.CompressFormat.JPEG,50,byteArrayOutputStream);
byte[] bytes=byteArrayOutputStream.toByteArray();
return Base64.encodeToString(bytes,Base64.DEFAULT);
}




private final ActivityResultLauncher<Intent> pickImage=registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode()==RESULT_OK){
if (result.getData()!=null){
Uri imageuri=result.getData().getData();
try{
InputStream inputStream= getContentResolver().openInputStream(imageuri);
Bitmap bitmap= BitmapFactory.decodeStream(inputStream);
binding.imageProfile.setImageBitmap(bitmap);
encodedImage= encodeImage(bitmap);
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
}
);

在 Kotlin,另一种写作方式更简单:

fun imageBase64(filepath: String): String {
FileInputStream(filepath).use {
val bytes = it.readBytes()
return Base64.encodeToString(bytes, Base64.DEFAULT)
}
}