如何将一张图片(最大200KB)转换成 Base64 字符串?
我需要知道在 Android 中如何实现这个功能,因为我需要在我的主要应用程序中添加上传图片到远程服务器的功能,并将它们作为字符串放入数据库的一行中。
我已经在 Google 和 Stack Overflow 上搜索了很久,但是没有找到易于理解的示例代码。虽然我找到了一些示例代码,但它们并没有讲述如何将图片转换成字符串。所以我需要将它们转换成字符串后通过 JSON 上传到远程服务器。
您可以使用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(也称为2.2版本)中才发布)。
请参考这篇文章以获取解决方法:
除了使用 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);
以下是 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)
}
// 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;
}
这段代码在我的项目中运行完美:
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;
}
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) {
}
}
在 Kotlin 中,还有一种更简单的写法:
fun imageBase64(filepath: String): String {
FileInputStream(filepath).use {
val bytes = it.readBytes()
return Base64.encodeToString(bytes, Base64.DEFAULT)
}
}
Kotlin版本:
fun File.toBase64(): String? {
val result: String?
inputStream().use { inputStream ->
val sourceBytes = inputStream.readBytes()
result = Base64.encodeToString(sourceBytes, Base64.DEFAULT)
}
return result
}
在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);
http://androidcodemonkey.blogspot.com/2010/03/how-to-base64-encode-decode-android.html
。我也在答案中更新了它。 - xil3