二维码生成工具
需导入依赖
1 <dependency> 2 <groupId>com.google.zxing</groupId> 3 <artifactId>core</artifactId> 4 <version>3.4.0</version> 5 </dependency>
createBar方法入参为二维码内容、存放路径、文件名
3 import java.awt.image.BufferedImage; 4 import java.io.File; 5 import java.io.IOException; 6 import java.io.OutputStream; 7 import java.util.Hashtable; 8 import javax.imageio.ImageIO; 9 import com.google.zxing.BarcodeFormat; 10 import com.google.zxing.EncodeHintType; 11 import com.google.zxing.MultiFormatWriter; 12 import com.google.zxing.WriterException; 13 import com.google.zxing.common.BitMatrix; 14 15 16 /** 17 * @author Yanzm 18 * @Date 2019年12月4日 19 */ 20 public class BarUtils { 21 private static final int BLACK = 0xFF000000; 22 private static final int WHITE = 0xFFFFFFFF; 23 24 public static BufferedImage toBufferedImage(BitMatrix matrix) { 25 int width = matrix.getWidth(); 26 int height = matrix.getHeight(); 27 BufferedImage image = new BufferedImage(width, height, 28 BufferedImage.TYPE_INT_RGB); 29 for (int x = 0; x < width; x++) { 30 for (int y = 0; y < height; y++) { 31 image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE); 32 } 33 } 34 return image; 35 } 36 37 public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException { 38 BufferedImage image = toBufferedImage(matrix); 39 if (!ImageIO.write(image, format, file)) { 40 throw new IOException("Could not write an image of format " + format + " to " + file); 41 } 42 } 43 44 public static void writeToStream(BitMatrix matrix, String format,OutputStream stream) throws IOException { 45 BufferedImage image = toBufferedImage(matrix); 46 if (!ImageIO.write(image, format, stream)) { 47 throw new IOException("Could not write an image of format " + format); 48 } 49 } 50 51 public static void createBar(String content,String basePath,String barName){ 52 String text = content; // 二维码内容 53 int width = 350; // 二维码图片宽度 54 int height = 350; // 二维码图片高度 55 String format = "gif"; // 二维码的图片格式 56 Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); 57 hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码 58 BitMatrix bitMatrix = null; 59 try { 60 bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints); 61 } catch (WriterException e) { 62 e.printStackTrace(); 63 } 64 // 生成二维码 65 String pname = basePath + File.separator +barName + "." +format; 66 File outputFile = new File(pname); 67 if (!outputFile.exists()) { 68 outputFile.mkdirs(); 69 } 70 try { 71 BarUtils.writeToFile(bitMatrix, format, outputFile); 72 } catch (IOException e) { 73 e.printStackTrace(); 74 } 75 } 76 77 public static void main(String[] args) throws Exception { 78 createBar("https://www.baidu.com","D://desktop","123"); 79 } 80 }