我正在尋找在Android中將圖像文件轉換爲Base64字符串的最有效方式。在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;
}
您可以獲取字節數組並將其分割成幾個子數組並將它們編碼到不同的線程中,然後將結果連接在一起以獲取最終字符串。 – 2013-04-07 20:52:01