读取图片
public String imageToBase64(){
String image = "d:\\009.png";
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(new File(image));
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
return null;
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64编码过的字节数组字符串
return encoder.encode(data);
}
使用base64
html页面中使用 '<img src="data:image/jpg;base64,'+ base64 + '" />'
即可展示图片
根据base64写图片
public boolean base64ToImage(String base64, String path) {
if (base64 == null) { // 图像数据为空
return false;
}
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] bytes = decoder.decodeBuffer(base64);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
// 生成图片
OutputStream out = new FileOutputStream(path);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}