1. 程式人生 > >圖片轉換成Base64格式的字串

圖片轉換成Base64格式的字串

在開發中會遇到上傳圖片到服務端的需求,需要把圖片轉換Base64 格式的字串。

        /**

* 圖片裝換成Base64字串
* @param path 路徑
* @return Base64字串
*/
public static  synchronized String imgToBase64String(String path)
{
File file = new File(path);
ByteArrayOutputStream imgData = new ByteArrayOutputStream();
if (!"null".equals(path) && file.exists()) {
try {
InputStream in = new FileInputStream(file);
byte[] buffer = new byte[1024];
int count = 0;
while (( count = in.read(buffer)) > 0) {
imgData.write(buffer, 0, count);
}
in.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

try {
imgData.close();
} catch (IOException e) {
e.printStackTrace();
}


String imgStr = new String(Base64.encode(imgData.toByteArray(), Base64.DEFAULT));
return imgStr;
}