简单的 图片和Base64数据互相转换代码
图片转换为Base64格式
/**
* 将图片转换为base64字符串
*
* @param imagePath 图片路径
*/
public String converterBase64(String imagePath) throws IOException {
InputStream inputStream = new FileInputStream(imagePath);
byte[] data = new byte[inputStream.available()];
inputStream.read(data);
return DatatypeConverter.printBase64Binary(data);
}
Base64格式转图片
/**
* 保存图片
*
* @param imageData Base64图片数据
* @param targetPath 保持图片地址
*/
public void converterImage(String imageData, String targetPath) throws IOException {
byte[] imageByte = DatatypeConverter.parseBase64Binary(imageData);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
BufferedImage image = ImageIO.read(bis);
File outPutFile = new File(targetPath);
ImageIO.write(image, "jpg", outPutFile);
}