使用Html5绘制图表,前端返回的是Base64字符串,如果想在后台将Base64字符串转换为图片,保存在本地,在Java中经常需要做如下处理,下文介绍了Base64字符串与图片的相互转换过程。
具体Java代码如下:
示例代码1
/**
*
* @site 四个空格-https://www.4spaces.org/
* @author michael
*
*/
public class Base64StringToImage {
public static void main(String[] args) {
String imgStr = "/9j/4AAQSkZ...";
generateImage(imgStr, "D:\\wangyc.jpg"); //
System.out.println(getImageStr("d:\\wangyc.jpg"));
}
/**
* 将图片转换为Base64类型字符串
*
* @param imgFilePath
* @return
*/
public static String getImageStr(String imgFilePath) {
byte[] data = null;
try {
InputStream in = new FileInputStream(imgFilePath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
/**
* 将Base64类型字符串转换为图片
*
* @param imgStr
* @param imgFilePath
* @return
*/
public static boolean generateImage(String imgStr, String imgFilePath) {
if (imgStr == null)
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] bytes = decoder.decodeBuffer(imgStr);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {
bytes[i] += 256;
}
}
OutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
示例代码2
String imgStr = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA...";
String imgFilePath = "D:\root\xf-service\upload-path\37\a.jpg";
generateImage(imgStr, imgFilePath);
/**
* 将Base64类型字符串转换为图片
*
* @param imgStr
* @param imgFilePath
* @return
*/
private boolean generateImage(String imgStr, String imgFilePath) {
if (imgStr == null) {
return false;
}
String base64Image = imgStr.split(",")[1];
byte[] imageBytes = javax.xml.bind.DatatypeConverter.DatatypeConverter.parseBase64Binary(base64Image);
java.awt.image.BufferedImage.BufferedImage image = null;
try {
image = javax.imageio.ImageIO.ImageIO.read(new ByteArrayInputStream(imageBytes));
// write the image to a file
File outputfile = new File(imgFilePath);
ImageIO.write(image, "png", outputfile);
} catch (IOException e) {
e.printStackTrace();
}
return true;
}