首先将需要的jar加到工程中
QRCode.jar、zxingcore-2.2.jar、javase-2.2.jar(也可不加,增加一个MatrixToImageWriter类也可以)
package com.demo; 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; /** * * @ClassName: MatrixToImageWriter * @Description: 如果不想增加javase-2.2.jar,新增此类即可 * @date 2015年4月30日 上午10:05:51 * @since AR1.0 */ 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); } } }
测试类
package com.demo; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.common.BitMatrix; import com.swetake.util.Qrcode; public class QRCodeDemo { public static void main(String[] args) { QRCodeDemo.encoderQRCode("这是用Qrcode生成的二维码", "C:/Users/liyy/Desktop/TestQRCode.png"); QRCodeDemo.zXingTest("这是用zXing生成的二维码", "C:/Users/liyy/Desktop/TestZXing.png"); } /** * * @Title: encoderQRCode * @Description: 使用Qrcode生成二维码 * @param @param content * @param @param imgPath * @return void 返回类型 * @throws */ public static void encoderQRCode(String content, String imgPath) { try { Qrcode qrcodeHandler = new Qrcode(); qrcodeHandler.setQrcodeErrorCorrect('M');// 纠错 qrcodeHandler.setQrcodeEncodeMode('B'); qrcodeHandler.setQrcodeVersion(7); byte[] contentBytes = content.getBytes("gb2312"); BufferedImage bufImg = new BufferedImage(140, 140, BufferedImage.TYPE_INT_RGB); Graphics2D gs = bufImg.createGraphics(); gs.setBackground(Color.WHITE); gs.clearRect(0, 0, 140, 140); // 设定图像颜色> BLACK gs.setColor(Color.BLACK); // 设置偏移量 int pixoff = 2; // 输出内容> 二维码 if ((contentBytes.length > 0) && (contentBytes.length < 120)) { boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes); for (int i = 0; i < codeOut.length; i++) { for (int j = 0; j < codeOut.length; j++) { if (codeOut[j][i]) { gs.fillRect((j * 3) + pixoff, (i * 3) + pixoff, 3, 3); } } } } else { System.err.println("QRCode content bytes length = " + contentBytes.length + " not in [ 0,120 ]. "); } gs.dispose(); bufImg.flush(); File imgFile = new File(imgPath); // 生成二维码QRCode图片 ImageIO.write(bufImg, "png", imgFile); System.out.println("Qrcode已输出二维码!"); } catch (Exception e) { e.printStackTrace(); } } /** * * @Title: zXingTest * @Description: 使用google的zXing生成二维码 * @param * @return void 返回类型 * @throws */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static void zXingTest(String content, String imgPath) { try { MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); Map hints = new HashMap(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400, hints); File file1 = new File(imgPath); MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file1); System.out.println("zXing已输出二维码!"); } catch (Exception e) { e.printStackTrace(); } } }
解析二维码
使用QRCode解析
/** * * @Title: decoderQRCode * @Description: 使用Qrcode解析二维码 * @param @param inputStream * @param @throws IOException * @return void 返回类型 * @throws */ public static void decoderQRCode(String imgPath) { try { BufferedImage image = ImageIO.read(new File(imgPath)); LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); // decode the barcode QRCodeReader reader = new QRCodeReader(); Result result = null; result = reader.decode(bitmap); System.out.println("使用QRCode解析后内容:" + result.getText()); } catch (Exception e) { // the data is improperly formatted e.printStackTrace(); } }
使用zXing解析时需要使用BufferedImageLuminanceSource类
package com.demo; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import com.google.zxing.LuminanceSource; public final 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; } @Override public byte[] getRow(int y, byte[] row) { if ((y < 0) || (y >= this.getHeight())) { throw new IllegalArgumentException("Requested row is outside the image: " + y); } int width = this.getWidth(); if ((row == null) || (row.length < width)) { row = new byte[width]; } this.image.getRaster().getDataElements(this.left, this.top + y, width, 1, row); return row; } @Override public byte[] getMatrix() { int width = this.getWidth(); int height = this.getHeight(); int area = width * height; byte[] matrix = new byte[area]; this.image.getRaster().getDataElements(this.left, this.top, width, height, matrix); return matrix; } @Override public boolean isCropSupported() { return true; } @Override public LuminanceSource crop(int left, int top, int width, int height) { return new BufferedImageLuminanceSource(this.image, this.left + left, this.top + top, width, height); } @Override public boolean isRotateSupported() { return true; } @Override public LuminanceSource rotateCounterClockwise() { int sourceWidth = this.image.getWidth(); int sourceHeight = this.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(this.image, transform, null); g.dispose(); int width = this.getWidth(); return new BufferedImageLuminanceSource(rotatedImage, this.top, sourceWidth - (this.left + width), this.getHeight(), width); } }
/** * * @Title: zXingDecode * @Description: 使用google的zXing解析二维码 * @param * @return void 返回类型 * @throws */ @SuppressWarnings("unchecked") public static void zXingDecode(String imgPath) { try { BufferedImage image; try { image = ImageIO.read(new File(imgPath)); if (image == null) { System.out.println("没找到图片"); } LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Result result; @SuppressWarnings("rawtypes") Hashtable hints = new Hashtable(); // 解码设置编码方式为:utf-8 hints.put(DecodeHintType.CHARACTER_SET, "utf-8"); result = new MultiFormatReader().decode(bitmap, hints); String resultStr = result.getText(); System.out.println("使用zXing解析后内容:" + resultStr); } catch (IOException ioe) { System.out.println(ioe.toString()); } catch (ReaderException re) { System.out.println(re.toString()); } } catch (Exception ex) { System.out.println(ex.toString()); } }