之前写了一篇生成微信公众号带参数二维码的文章,今天闲来无事,就通过代码实现了生成的过程,因为请求微信接口返回的参数如下:
{"ticket":"gQH47joAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL2taZ2Z3TVRtNzJXV1Brb3ZhYmJJAAIEZ23sUwMEmm3sUw==","url":"http://weixin..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..com/q/02fdnPNpL3e9j10000w07a',
});
</script>
</body>
</html>
示例:


版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/82038.html