java鬼混笔记:java zxing生成二维码和带图的二维码

来源:互联网 发布:并购发展前景 知乎 编辑:程序博客网 时间:2024/05/16 06:52
一、生成普通的二维码:import java.nio.file.Path;import java.nio.file.Paths;import java.util.Hashtable;import com.google.zxing.BarcodeFormat;import com.google.zxing.EncodeHintType;import com.google.zxing.MultiFormatWriter;import com.google.zxing.client.j2se.MatrixToImageWriter;import com.google.zxing.common.BitMatrix;//创建纯二维码public class CreateQRCode {public static void main(String[] args){  try {int width = 150; // 二维码图片150像素宽int height = 150; // 二维码图片150像素高String format = "png";// 二维码的图片格式String content = "流口水的外星人";//找描二维码后的内容//String content = "http://www.baidu.com";//如果是链接就直接跳到到相关网页Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码hints.put(EncodeHintType.MARGIN, "1");//外边距 可以不用设置 但是二维码不是铺满的 0才是铺满,我这里设置1好看点BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);// 生成二维码String imgPath = "D://";//二维码图片路径String imgName = "fk.png";//二维码图片路径Path path = Paths.get(imgPath, imgName);MatrixToImageWriter.writeToPath(bitMatrix, format, path);System.out.println("OK");} catch (Exception e) {System.out.println("BAD" + e.getMessage());}}  }
二、解析二维码:import java.awt.image.BufferedImage;import java.io.File;import java.io.FileInputStream;import java.util.HashMap;import javax.imageio.ImageIO;import com.google.zxing.Binarizer;import com.google.zxing.BinaryBitmap;import com.google.zxing.DecodeHintType;import com.google.zxing.LuminanceSource;import com.google.zxing.MultiFormatReader;import com.google.zxing.Result;import com.google.zxing.client.j2se.BufferedImageLuminanceSource;import com.google.zxing.common.HybridBinarizer;//读二维码内容 不区分普通二维码和带Logo的二维码public class ReadQRCode {public static void main(String[] args) {try {String retStr = "";//读取后的内容String path = "D:"+File.separator+"fk.png";//在D盘里有个叫fk.png图片的路径BufferedImage bufferedImage = ImageIO.read(new FileInputStream(path));LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);Binarizer binarizer = new HybridBinarizer(source);BinaryBitmap bitmap = new BinaryBitmap(binarizer);HashMap<DecodeHintType, Object> hintTypeObjectHashMap = new HashMap<>();hintTypeObjectHashMap.put(DecodeHintType.CHARACTER_SET, "UTF-8");Result result = new MultiFormatReader().decode(bitmap, hintTypeObjectHashMap);retStr = result.getText();System.out.println("内容是:"+retStr);System.out.println("OK");} catch (Exception e) {System.out.println("BAD" + e.getMessage());}}}


三、带有logo的二维码生成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.io.OutputStream;import java.util.Hashtable;import java.util.Random;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.client.j2se.BufferedImageLuminanceSource;import com.google.zxing.common.BitMatrix;import com.google.zxing.common.HybridBinarizer;import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;//创建带Logo二维码 比如平时微信二维码public class CreateQRCodeWithLogo {private static final String CHARSET = "utf-8";private static final String FORMAT_NAME = "PNG";// 二维码尺寸private static final int QRCODE_SIZE = 300;// LOGO宽度private static final int WIDTH = 60;// LOGO高度private static final int HEIGHT = 60;private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {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, 1);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);}}if (imgPath == null || "".equals(imgPath)) {return image;}// 插入图片CreateQRCodeWithLogo.insertImage(image, imgPath, needCompress);return image;}/*** 插入LOGO* * @param source*            二维码图片* @param imgPath*            LOGO图片地址* @param needCompress*            是否压缩* @throws Exception*/private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {File file = new File(imgPath);if (!file.exists()) {System.err.println("" + imgPath + "   该文件不存在!");return;}Image src = ImageIO.read(new File(imgPath));int width = src.getWidth(null);int height = src.getHeight(null);if (needCompress) { // 压缩LOGOif (width > WIDTH) {width = WIDTH;}if (height > HEIGHT) {height = HEIGHT;}Image image = src.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();src = image;}// 插入LOGOGraphics2D graph = source.createGraphics();int x = (QRCODE_SIZE - width) / 2;int y = (QRCODE_SIZE - height) / 2;graph.drawImage(src, 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();}/*** 生成二维码(内嵌LOGO)* * @param content*            内容* @param imgPath*            LOGO地址* @param destPath*            存放目录* @param needCompress*            是否压缩LOGO* @throws Exception*/public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {BufferedImage image = CreateQRCodeWithLogo.createImage(content, imgPath, needCompress);String file = "d.png";ImageIO.write(image, FORMAT_NAME, new File(destPath + "/" + file));}public static void main(String[] args) throws Exception {           String content = "流口水的外星人";String logo = "D:/abc.png";String path = "D:/";CreateQRCodeWithLogo.encode(content, logo, path, true);}}


原创粉丝点击