我正在寻找在 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;
}