maven 依赖
<!-- http://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
service
public byte[] qr(Item item) throws Exception {
String content = commonProperties.getWxHost() + "/item/detail?id="
+ item.getId();
int width = 250; // 图像宽度
int height = 350; // 图像高度
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
int w = bitMatrix.getWidth();
int h = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
// 开始利用二维码数据创建Bitmap图片,分别设为黑白两色
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? Color.BLACK.getRGB()
: Color.WHITE.getRGB());
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String format = "png";
watermark("库存:" + item.getWarehouse_no(), image, 10);
watermark("标题:" + item.getTitle(), image, 40);
ImageIO.write(image, format, baos);
return baos.toByteArray();
}
controller
@RequestMapping(value = "/exportQR", method = RequestMethod.GET)
public void exportQR(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String id = request.getParameter("id");
Item item = itemService.get(id);//生成的内容
// create qr
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("image/png");
response.setHeader("Cache-Control", "max-age=2592000");
OutputStream outputStream = response.getOutputStream();
outputStream.write(this.barCodeService.qr(item));
outputStream.flush();
IOUtils.closeQuietly(outputStream);
}
页面引用
<pre><img style="-webkit-user-select: none" src="http://localhost:8080/mp/item/exportQR?id=13ab17372d1d11e6839e97362d2b99f1"></pre>
最终效果