最近做项目遇到了一种常见得需求,起初是生成一个二维码图片,用base64展现在页面上,而后发现这种方式显得页面很乱,于是将其转化为图片文件存储在项目目录当中,返回图片名称供前端引用图片,话不多说,直接上代码:
@RequestMapping("/QrCode")
public R getScanCode(@PathVariable("deviceNo") String deviceNo) {
//获取要存储文件 得路径
String url = this.getClass().getClassLoader().getResource("").getPath();
//对路劲进行拼接添加
String destPath = url + "statics/img/";
//定义最终文件得名字
String fileName = "scanCode.png";
//将参数传入调用方法
String name = QRCodeUtil.getImage2(codeUrl, url, destPath, fileName);
//最后返回文件得名字
return R.ok().put("ScanCodeUrl", name);
}
public static String getImage2(String codeUrl, String url, String destPath, String fileName) {
BufferedImage image = null;
String png_base64 = null;
String file = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_app" + ".jpg";
try {
//生成带有logo的二维码图片 其实这儿就可以存储
//本文演示全过程
image = QRCodeUtil.encode(codeUrl, url + "statics/img/aaa.png", url + "statics/img/aaa.png", true, file);
//转化
ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
ImageIO.write(image, "png", baos);//写入流中
byte[] bytes = baos.toByteArray();//转换成字节
BASE64Encoder encoder = new BASE64Encoder();
//转换成base64串
String png_base = encoder.encodeBuffer(bytes).trim();
//删除 \r\n
png_base64 = png_base.replaceAll("\n", "").replaceAll("\r", "");
} catch (Exception e) {
e.printStackTrace();
}
//将base64转文件 目标文件得位置 64得码 定义得文件名
base64ToFile(destPath, png_base64, fileName);
return fileName;
}
//转化并存储文件
public static void base64ToFile(String destPath, String base64, String fileName) {
File file = null;
//创建文件目录
String filePath = destPath;
//创建文件目录
File dir = new File(filePath);
//如果不存在则创建目录
if (!dir.exists() && !dir.isDirectory()) {
dir.mkdirs();
}
BufferedOutputStream bos = null;
java.io.FileOutputStream fos = null;
try {
//创建的64得解码 注 用什么编码 就用什么解码 这里之前用的是BASE64Encoder 编码就用相应的Decoder
BASE64Decoder decode = new BASE64Decoder();
byte[] bytes = decode.decodeBuffer(base64);
file = new File(filePath + "/" + fileName);
//开始写入文件
fos = new java.io.FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//编码生成图片
public static BufferedImage encode(String content, String imgPath, String destPath, boolean needCompress, String imgName) throws Exception {
System.out.println(imgPath);
BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
return image;
}
最后文件存放的位置是:
target-----classes----statics-----img-----scanCode.jpg
至此生成转化完毕。。。。