问题原因:
springboot项目需要生成带logo的二维码,且logo需要内置在jar包中。 打成jar包后图片无法访问。 报错
java.io.FileNotFoundException: class path resource [logo.jpg] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/Users/*/*/*/*/target/*-2.0.0.jar!/BOOT-INF/classes!/logo.jpg
解决方案:
使用ClassPathResource读取文件,并在指定目录重新生成临时文件 代码如下:
/**
* 插入LOGO
*
* @param source
* 二维码图片
* @param logoPath
* LOGO图片地址
* @param needCompress
* 是否压缩
* @throws Exception
*/
private static void insertImage(BufferedImage source, String logoPath, boolean needCompress) throws Exception {
//读取resources路径下的文件,获取输入流
ClassPathResource classPathResource=new ClassPathResource(logoPath);
InputStream inputStream=classPathResource.getInputStream();
//基于Guava的实现临时文件生成
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
String jarPath=System.getProperty("user.dir");
File targetFile = new File(jarPath+logoPath);
Files.write(buffer, targetFile);
//文件生成完毕后使用qrcode绘制二维码
Image src = ImageIO.read(targetFile);
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { // 压缩LOGO
if (width > LOGO_WIDTH) {
width = LOGO_WIDTH;
}
if (height > LOGO_HEIGHT) {
height = LOGO_HEIGHT;
}
Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}