java代碼將鏈接轉換為二維碼


Talk is cheap. Show me the code.

上代碼,

 1 package cn.szy.util;
 2 
 3 import java.awt.image.BufferedImage;
 4 import java.io.File;
 5 import java.io.IOException;
 6 import java.io.OutputStream;
 7 import java.text.SimpleDateFormat;
 8 import java.util.Date;
 9 import java.util.HashMap;
10 import java.util.Map;
11 
12 import javax.imageio.ImageIO;
13 import javax.swing.filechooser.FileSystemView;
14 
15 import com.google.zxing.BarcodeFormat;
16 import com.google.zxing.EncodeHintType;
17 import com.google.zxing.MultiFormatWriter;
18 import com.google.zxing.common.BitMatrix;
19 
20 /**
21 * java代碼將鏈接轉換為二維碼
22 * @Description: TODO
23 * @author :mr.shi
24 * @date :2020年5月11日 下午2:58:05
25 */
26 public class QrCodeUtils {
27 
28 public static void main(String[] args) {
29 String url = "http://www.baidu.com/gsdrfgted344354354354353453432222/23432434666765";
30 String path = FileSystemView.getFileSystemView().getHomeDirectory() + File.separator + "testQrcode";
31 System.out.println(path);
32 String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg";
33 createQrCode(url, path, fileName);
34 }
35 
36 public static String createQrCode(String url, String path, String fileName) {
37 try {
38 Map<EncodeHintType, String> hints = new HashMap<>();
39 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
40 BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 400, 400, hints);
41 File file = new File(path, fileName);
42 if (file.exists() || ((file.getParentFile().exists() || file.getParentFile().mkdirs()) && file.createNewFile())) {
43 writeToFile(bitMatrix, "jpg", file);
44 System.out.println("測試完成:" + file);
45 }
46 
47 } catch (Exception e) {
48 e.printStackTrace();
49 }
50 return null;
51 }
52 
53 static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
54 BufferedImage image = toBufferedImage(matrix);
55 if (!ImageIO.write(image, format, file)) {
56 throw new IOException("Could not write an image of format " + format + " to " + file);
57 }
58 }
59 
60 static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException {
61 BufferedImage image = toBufferedImage(matrix);
62 if (!ImageIO.write(image, format, stream)) {
63 throw new IOException("Could not write an image of format " + format);
64 }
65 }
66 
67 private static final int BLACK = 0xFF000000;
68 private static final int WHITE = 0xFFFFFFFF;
69 
70 private static BufferedImage toBufferedImage(BitMatrix matrix) {
71 int width = matrix.getWidth();
72 int height = matrix.getHeight();
73 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
74 for (int x = 0; x < width; x++) {
75 for (int y = 0; y < height; y++) {
76 image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
77 }
78 }
79 return image;
80 }
81 
82 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM