使用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;
}
最新评论
网飞没问题, 迪士尼+有解决方案么?
pp助手是安卓手机用的,根本下载用不来苹果
已解决
这样的话数据库里的结构为{"attachment":{"content":"xxx"}}, 要怎么才能变成{"content":"xxx"},从而使结构保持一致?
赞! make test不过的坑都写到的,谢谢楼主~
谢谢你
用了root用户还是一直502是怎么回事呢
student id 是空的