之前写了一篇生成微信公众号带参数二维码的文章,今天闲来无事,就通过代码实现了生成的过程,因为请求微信接口返回的参数如下:
{"ticket":"gQH47joAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL2taZ2Z3TVRtNzJXV1Brb3ZhYmJJAAIEZ23sUwMEmm3sUw==","url":"http://weixin.qq.com/q/kZgfwMTm72WWPkovabbI"}
我希望拿到URL转换为二维码图片,上网查找资料后有两种实现方式。
第一种是通过后端引入zxing的jar包,在pom中添加依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>zxingorg</artifactId>
<version>3.3.2</version>
</dependency>
工具类:
import com.google.zxing.common.BitMatrix;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.OutputStream;
import java.io.IOException;
import java.awt.image.BufferedImage;
public final class MatrixToImageWriter {
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
private MatrixToImageWriter() {}
public static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.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, matrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
}
public static void writeToFile(BitMatrix matrix, String format, File file)
throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
}
public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)
throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, stream)) {
throw new IOException("Could not write an image of format " + format);
}
}
}
代码如下:
String path = "C:/Users/Administrator/Desktop/qrCodeImg";
try {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = multiFormatWriter.encode((String) bookShelf.get("qr_code"), BarcodeFormat.QR_CODE, 400, 400, hints);
File file1 = new File(path, bookShelf.get("code") + ".jpg");
MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file1);
} catch (Exception e) {
e.printStackTrace();
}
保存到本地的二维码图片示例如下:
第二种就是在页面引入query.qrcode.js。(还需要jQuery的js)text内容就是我们微信请求获取到的URL
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>查看二维码</title>
<script src="jquery-3.3.1.min.js"></script>
<script src="jquery.qrcode.min.js"></script>
</head>
<body>
<div id="qrCode"></div>
<script>
$('#qrCode').qrcode({
render: 'canvas', //table或者canvas
width: 200,
height: 200,
text: 'http://weixin.qq.com/q/02fdnPNpL3e9j10000w07a',
});
</script>
</body>
</html>
示例: