1、生成二维码
2、将二维码嵌入背景图片
1、生成二维码的方法,content是二维码内容,logoImgPath是二维码中嵌入的logo,needCompress是否需要压缩标识
private BufferedImage createImage(String content, String logoImgPath, boolean needCompress) throws WriterException, IOException {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 0);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//循环遍历每一个像素点
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
// 没有logo
if (logoImgPath == null || "".equals(logoImgPath)) {
return image;
}
// 插入图片
insertImage(image, logoImgPath, needCompress);
return image;
}
logoImagePath传值null,needCompress值为true/false都可以
2、将二维码嵌入背景图片,返回图片流
/**
* 将二维码嵌入图片
* @param zxingImage
* @param backgroundPath
* @return
*/
public InputStream changeMerchantSeatQrcodeImage(BufferedImage zxingImage, String backgroundPath,
String idMerchantStr) {
InputStream imagein = null;
ImageOutputStream imOut = null;
try {
imagein = new FileInputStream(backgroundPath);
BufferedImage image = ImageIO.read(imagein);
BufferedImage image2 = zxingImage;
Graphics g = image.getGraphics();
// 生成的二维码设置的较小,这里等比放大了二维码。也可在zxing中设置二维码生成的大小
BufferedImage squreImage = resizeImage(image2, 2);
g.drawImage(squreImage, squreImage.getWidth()/2+10, squreImage.getHeight()-100,
squreImage.getWidth(), squreImage.getHeight(), null);
Font f = new Font("宋体", Font.PLAIN, 36);
Color mycolor = Color.black;
g.setColor(mycolor);
g.setFont(f);
g.drawString(idMerchantStr, 625, 1280);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
imOut = ImageIO.createImageOutputStream(bs);
ImageIO.write(image, "jpg", imOut);
InputStream is = new ByteArrayInputStream(bs.toByteArray());
return is;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
imagein.close();
imOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
pom文件中添加依赖:
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
zxingImage是二维码图片,backgroundPath是背景图片,idMerchantStr是商户编号
商户号补齐8位:
DecimalFormat format = new DecimalFormat("00000000");
String idMerchantStr = format.format(idMerchant);
注:生产环境发现向图片写入的商户号有时会乱码(两台服务器,请求会随机分配到其中一台),通过控制台发现当请求到a服务器时会乱码,到b服务器时正常,然后发现a服务器没有此字体,所以会出现乱码。将b服务器的字体复制到a服务器,问题解决。
返回的图片流直接显示在页面img标签中