【发布时间】:2013-03-29 20:16:24
【问题描述】:
我正在寻找在 Android 中将图像文件转换为 Base64 字符串的最有效方法。
图像必须一次以单个 Base64 字符串发送到后端。
首先我使用 imageToByteArray 然后 imageToBase64 来获取字符串。
public static byte[] imageToByteArray(String ImageName) throws IOException {
File file = new File(sdcard, ImageName);
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
//Close input stream
is.close();
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
return bytes;
}
public String imageToBase64(String ImageName){
String encodedImage = null;
try {
encodedImage = Base64.encodeToString(imageToByteArray(ImageName), Base64.DEFAULT);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encodedImage;
}
【问题讨论】:
-
您可以获取字节数组并将其拆分为几个子数组并在单独的线程中对其进行编码,然后将结果组合在一起以获得最终字符串。
标签: android base64 type-conversion android-image