生成流程
1、创建画布
2、开启画图
3、画布上加载背景图片
4、画布上指定坐标绘制二维码(关于二维码实现的参考文后的链接)
5、将最终的图存放在本地
6、将图片url返回给前端
主要代码:
java
@PostMapping(value = "/getPoster")
public Result<?> getPoster(@RequestBody ProductDto productDto) {
Result<Map<String,Object>> result = new Result<Map<String,Object>>();
Map<String,Object> map = new HashMap<String,Object>();
Product product = productService.getById(productDto.getProductId());
if (StringUtils.isEmpty(product.getPosterImg()))
{
return Result.error("海报图片未定义");
}
try
{
BufferedImage img = new BufferedImage(750, 1334, BufferedImage.TYPE_INT_RGB);
//开启画图
Graphics g = img.getGraphics();
//背景 -- 读取互联网图片
BufferedImage back = ImageIO.read(new File(uploadpath + "/" + product.getPosterImg()));
g.drawImage(back.getScaledInstance(750, 1334, Image.SCALE_DEFAULT), 0, 0, null); // 绘制缩小后的图
String fileName = productDto.getOpenid() + "@" + productDto.getProductId() + ".jpg";
//生成二维码
QRCodeUtil.encode(productDto.getProductUrl(), "", uploadpath + "/qrcode/", fileName, true);
BufferedImage qrCode = ImageIO.read(new File(uploadpath + "/qrcode/" + fileName));
// 绘制缩小后的图
g.drawImage(qrCode.getScaledInstance(174, 174, Image.SCALE_DEFAULT), 536, 1057, null);
g.dispose();
//先将画好的海报写到本地
String picUrl = uploadpath + "/poster/" + fileName; // TODO
File file = new File(picUrl);
ImageIO.write(img, "jpg",file);
map.put("imageUrl", "/poster/" + fileName);
result.setSuccess(true);
result.setResult(map);
} catch (Exception e)
{
e.printStackTrace();
return Result.error("生成海报出现错误!");
}
return result;
}
背景图片(图片有点丑,相关字样及二维码进行了打码处理,不然可能过不了审)
生成后
相关文章
Java 使用zxing生成二维码 https://tangying.blog.csdn.net/article/details/134756196