二维码生成
1 package com.wsc.core.pig; 2 3 import com.google.zxing.BarcodeFormat; 4 import com.google.zxing.EncodeHintType; 5 import com.google.zxing.MultiFormatWriter; 6 import com.google.zxing.common.BitMatrix; 7 8 import javax.imageio.ImageIO; 9 import java.awt.image.BufferedImage; 10 import java.io.File; 11 import java.io.IOException; 12 import java.io.OutputStream; 13 import java.util.Hashtable; 14 15 /** 16 * @version 1.0 17 * @ClassName MatrixToImageWriter 18 * @Description TODO 19 * @Author WSC 20 * @Date 2019/9/7 16:05 21 **/ 22 public class MatrixToImageWriter { 23 private static final int BLACK = 0xFF000000; 24 private static final int WHITE = 0xFFFFFFFF; 25 26 private MatrixToImageWriter() { 27 } 28 29 public static BufferedImage toBufferedImage(BitMatrix matrix) { 30 int width = matrix.getWidth(); 31 int height = matrix.getHeight(); 32 BufferedImage image = new BufferedImage(width, height, 33 BufferedImage.TYPE_INT_RGB); 34 for (int x = 0; x < width; x++) { 35 for (int y = 0; y < height; y++) { 36 image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE); 37 } 38 } 39 return image; 40 } 41 42 public static void writeToFile(BitMatrix matrix, String format, File file) 43 throws IOException { 44 BufferedImage image = toBufferedImage(matrix); 45 if (!ImageIO.write(image, format, file)) { 46 throw new IOException("Could not write an image of format " 47 + format + " to " + file); 48 } 49 } 50 51 public static void writeToStream(BitMatrix matrix, String format, 52 OutputStream stream) throws IOException { 53 BufferedImage image = toBufferedImage(matrix); 54 if (!ImageIO.write(image, format, stream)) { 55 throw new IOException("Could not write an image of format " + format); 56 } 57 } 58 59 public static void main(String[] args) throws Exception { 60 String text = "http://www.baidu.com"; // 二维码内容 61 int width = 300; // 二维码图片宽度 62 int height = 300; // 二维码图片高度 63 String format = "jpg";// 二维码的图片格式 64 65 Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); 66 hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码 67 68 BitMatrix bitMatrix = new MultiFormatWriter().encode(text, 69 BarcodeFormat.QR_CODE, width, height, hints); 70 // 生成二维码 71 File outputFile = new File("d:" + File.separator + "new.jpg"); 72 MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile); 73 } 74 75 }
pom.xml:
1 <dependency> 2 <groupId>com.google.zxing</groupId> 3 <artifactId>core</artifactId> 4 <version>3.2.0</version> 5 <scope>test</scope> 6 </dependency>
学习不分先后,知识不分多少;事无巨细,当以虚心求教;三人行,必有我师焉!!!wished for you successed !!!