Java 生成二维码
2016-03-18 17:56
375 查看
【1. 简介】
使用Google 提供的Zxing 进行生成和解析二维码。只需要引入一个jar包即可。
maven 下载路径:
【2. 测试类】
BufferedImageLuminanceSource.java
QRCodeUtil.java
TestQR.java
【3. 测试结果】
【4. 生成二维码】
【5. 源码下载】
Java生成二维码.zip
使用Google 提供的Zxing 进行生成和解析二维码。只需要引入一个jar包即可。
maven 下载路径:
<dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.2.1</version> </dependency>
【2. 测试类】
BufferedImageLuminanceSource.java
package org.zgf.zxing.util; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import com.google.zxing.LuminanceSource; public class BufferedImageLuminanceSource extends LuminanceSource { private final BufferedImage image; private final int left; private final int top; public BufferedImageLuminanceSource(BufferedImage image) { this(image, 0, 0, image.getWidth(), image.getHeight()); } public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) { super(width, height); int sourceWidth = image.getWidth(); int sourceHeight = image.getHeight(); if (left + width > sourceWidth || top + height > sourceHeight) { throw new IllegalArgumentException("Crop rectangle does not fit within image data."); } for (int y = top; y < top + height; y++) { for (int x = left; x < left + width; x++) { if ((image.getRGB(x, y) & 0xFF000000) == 0) { image.setRGB(x, y, 0xFFFFFFFF); // = white } } } this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY); this.image.getGraphics().drawImage(image, 0, 0, null); this.left = left; this.top = top; } public byte[] getRow(int y, byte[] row) { if (y < 0 || y >= getHeight()) { throw new IllegalArgumentException("Requested row is outside the image: " + y); } int width = getWidth(); if (row == null || row.length < width) { row = new byte[width]; } image.getRaster().getDataElements(left, top + y, width, 1, row); return row; } public byte[] getMatrix() { int width = getWidth(); int height = getHeight(); int area = width * height; byte[] matrix = new byte[area]; image.getRaster().getDataElements(left, top, width, height, matrix); return matrix; } public boolean isCropSupported() { return true; } public LuminanceSource crop(int left, int top, int width, int height) { return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height); } public boolean isRotateSupported() { return true; } public LuminanceSource rotateCounterClockwise() { int sourceWidth = image.getWidth(); int sourceHeight = image.getHeight(); AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth); BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY); Graphics2D g = rotatedImage.createGraphics(); g.drawImage(image, transform, null); g.dispose(); int width = getWidth(); return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width); } <strong>}</strong>
QRCodeUtil.java
package org.zgf.zxing.util; import java.awt.BasicStroke; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Shape; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.util.HashMap; import javax.imageio.ImageIO; import com.google.zxing.BarcodeFormat; import com.google.zxing.BinaryBitmap; import com.google.zxing.DecodeHintType; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatReader; import com.google.zxing.MultiFormatWriter; import com.google.zxing.Result; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; /** * 二维码工具类 */ public class QRCodeUtil { /** 字符编码UTF-8 */ private static final String CHARSET_UTF8 = "utf-8"; /*** * 生成二维码图片 * @param content 二维码携带文本内容 * @return BufferedImage * @throws Exception */ private static BufferedImage createImage(String content,int qrSize) throws Exception { HashMap<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); hints.put(EncodeHintType.CHARACTER_SET, CHARSET_UTF8); hints.put(EncodeHintType.MARGIN, 1); BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, qrSize, qrSize, 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); } } return image; } /** * 图片中嵌入图片(二维码中插入logo) * @param qrBi 二维码BufferedImage * @param qcSize * @param imgPath * @param logoSize * @throws Exception */ private static void insertImage(BufferedImage qrBi, String imgPath, int logoSize) throws Exception { // 判断嵌入的文件是否存在 File file = new File(imgPath); if (!file.exists()) { throw new RuntimeException("" + imgPath + " 该文件不存在!"); } // 读取嵌入的图片 Image imgSource = ImageIO.read(new File(imgPath)); int width = imgSource.getWidth(null); int height = imgSource.getHeight(null); // 压缩LOGO if (width > logoSize) { width = logoSize; } if (height > logoSize) { height = logoSize; } Image image = imgSource.getScaledInstance(width, height, Image.SCALE_SMOOTH); BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = tag.getGraphics(); g.drawImage(image, 0, 0, null); // 绘制缩小后的图 g.dispose(); imgSource = image; // 插入LOGO Graphics2D graph = qrBi.createGraphics(); int x = (qrBi.getWidth() - width) / 2; int y = (qrBi.getHeight() - height) / 2; graph.drawImage(imgSource, x, y, width, height, null); Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6); graph.setStroke(new BasicStroke(3f)); graph.draw(shape); graph.dispose(); } /** * 生成二维码(嵌入图片) * @param content 二维码携带文本内容 * @param logoFilePath 嵌入图片路径 * @param qrPath 二维码图片生成文件 * @throws Exception */ public static void createQRCode(String content, int qcSize, String logoFilePath, int logoSize, String qrPath) throws Exception { //1. 生成二维码图片 BufferedImage image = QRCodeUtil.createImage(content,qcSize); //2. 二维码图片中嵌入logo insertImage(image, logoFilePath,logoSize); //3. 图片写入磁盘 ImageIO.write(image, "png", new File(qrPath)); } /** * 生成二维码图片(不包含图片) * @param content 二维码携带文本内容 * @param qcSize 二维码大小 * @param qrPath 生成的二维码文件全路径名 * @throws Exception */ public static void createQRCode(String content, int qcSize ,String qrPath) throws Exception{ BufferedImage image = QRCodeUtil.createImage(content,qcSize); ImageIO.write(image, "png", new File(qrPath)); } /** * 解析二维码 * * @param file 二维码图片 * @return 二维码携带内容 * @throws Exception */ public static String parseQRCode(File file) throws Exception { BufferedImage image; image = ImageIO.read(file); if (image == null) { return null; } BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Result result; HashMap<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>(); hints.put(DecodeHintType.CHARACTER_SET, CHARSET_UTF8); result = new MultiFormatReader().decode(bitmap, hints); String resultStr = result.getText(); return resultStr; } /** * 解析二维码 * * @param path 二维码所在路径 * @return 二维码携带文本内容 * @throws Exception */ public static String parseQRCode(String path) throws Exception { return QRCodeUtil.parseQRCode(new File(path)); } }
TestQR.java
package org.zgf.zxing.util; /** * 二维码工具类测试 */ public class Test_QR { //不包含图片的二维码生成路径 private static String qr1 = "d:/qrImgs/qr_001.jpg"; //包含图片的二维码生成路径 private static String qr2 = "d:/qrImgs/qr_002.jpg"; /** 二维码携带内容 */ private static String qrContent = "http://www.baidu.com"; public static void main(String[] args) throws Exception { //1. 测试生成不包含图片的二维码 createQRWithOutLogo(); //2. 测试生成包含图片的二维码 createQRIncludeLogo(); //3. 测试解析不包含图片的二维码 parseQRIncludeLogo(); //4. 测试解析包含图片的二维码 parseQRWithOutLogo(); } //测试生成不包含图片的二维码 private static void createQRWithOutLogo() throws Exception{ QRCodeUtil.createQRCode(qrContent, 200, qr1); System.out.println("不包含图片的二维码已经生成...\n**************************\n"); } //测试包含图片的二维码 private static void createQRIncludeLogo() throws Exception{ QRCodeUtil.createQRCode(qrContent, 200, "logo.png", 50, qr2); System.out.println("包含图片的二维码已经生成...\n**************************\n"); } private static void parseQRWithOutLogo() throws Exception{ String result = QRCodeUtil.parseQRCode(qr1); System.out.println("不包含图片的二维码解析结果:" + result + "\n**************************\n"); } private static void parseQRIncludeLogo() throws Exception{ String result = QRCodeUtil.parseQRCode(qr2); System.out.println("包含图片的二维码解析结果:" + result + "\n**************************\n"); } }
【3. 测试结果】
不包含图片的二维码已经生成... ************************** 包含图片的二维码已经生成... ************************** 包含图片的二维码解析结果:http://www.baidu.com ************************** 不包含图片的二维码解析结果:http://www.baidu.com **************************
【4. 生成二维码】
【5. 源码下载】
Java生成二维码.zip
相关文章推荐
- java判断字符串是否乱码
- 斐波那契堆(Fibonacci heap)原理详解(附java代码实现)
- java 请求url并解析
- Spring mvc @ResponseBody返回JSON前台JSP乱码解决
- 2. Add Two Numbers | Java最短代码实现
- java mybatis 之 mysqlmap 动态 sql 语句
- 怎样增强MyEclipse的代码自动提示功能
- SpringMVC那点事
- Java并发 线程池
- Spring MVC里面的预防 SQL 注入
- java读写excel文件
- SpringMVC定义Interceptor
- json与javaBean的序列化与反序列化(待续...)
- Struts 2 和 JSF 的区别
- Eclipse关于设置code style的问题
- spring ioc(反转控制)
- jdk 编译器 对final字段的处理
- Java第二次实验
- Java第二次实验
- struts2