一旦我不得不将图像转换为base 64并将该图像作为流发送(这里的编码和解码内容是代码)
要将文件转换为 base64 :
String filePath = "E:\\water-drop-after-convert.jpg";
File bMap = new File(filePath);
byte[] bFile = new byte[(int) bMap.length()];
FileInputStream fileInputStream = null;
String imageFileBase64 = null;
try {
fileInputStream = new FileInputStream(bMap);
fileInputStream.read(bFile);
fileInputStream.close();
imageFileBase64 = Base64.encode(bFile);
}catch(Exception e){
e.printStackTrace();
}
然后在服务端我做了类似的事情将base 64 String中的图像转换回文件,以便我可以显示。我在服务器端使用过这个库import sun.misc.BASE64Decoder;
//filePath is where you wana save image
String filePath = "E:\\water-drop-after-convert.jpg";
File imageFile = new File(filePath);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(imageFile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = null;
try {
decodedBytes = decoder.decodeBuffer(imageFileBase64);//taking input string i.e the image contents in base 64
} catch (IOException e1) {
e1.printStackTrace();
}
try {
fos.write(decodedBytes);
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}