Java自动生成二维码总结
生活随笔
收集整理的這篇文章主要介紹了
Java自动生成二维码总结
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
推薦一篇博客:Java自動生成帶log的二維碼?https://mp.csdn.net/postedit/84454677
第一種簡單的方法:?
import java.io.File; import java.nio.file.Path; import java.util.HashMap; import java.util.UUID;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; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;public class weweima2 {public static void createQrCode(int width, int height, String content) {// 1、設置二維碼的一些參數HashMap hints = new HashMap();// 1.1設置字符集hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 1.2設置容錯等級;因為有了容錯,在一定范圍內可以把二維碼p成你喜歡的樣式hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);// 1.3設置外邊距;(即白色區域)hints.put(EncodeHintType.MARGIN, 1);// 2、生成二維碼try {// 2.1定義BitMatrix對象BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);// 2.2、設置二維碼存放路徑,以及二維碼的名字Path codePath = new File("E:/erweima/2" + UUID.randomUUID().toString().substring(0,4) + ".png").toPath();// 2.3、執行生成二維碼MatrixToImageWriter.writeToPath(bitMatrix, "png", codePath);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static void main(String []args) {createQrCode(200, 200, "https://www.baidu.com");} }第二種
import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.util.Scanner;import javax.imageio.ImageIO;import com.swetake.util.Qrcode;/*實現輸入字符串(文本,網址)生成對應的二維碼* 二維碼實質是01代碼,具有4個等級的容錯能力* 二維碼具有容錯功能,當二維碼圖片被遮擋一部分后,仍可以掃描出來。*容錯的原理是二維碼在編碼過程中進行了冗余,就像是123被編碼成123123,這樣只要掃描到一部分二維碼圖片,*二維碼內容還是可以被全部讀到。*二維碼容錯率即是指二維碼圖標被遮擋多少后,仍可以被掃描出來的能力。容錯率越高,則二維碼圖片能被遮擋的部分越多。*二維碼容錯率用字母表示,容錯能力等級分為:L、M、Q、H四級* */ public class CreateQrcode {public static void main(String[] args) throws Exception {// 創建生成二維碼的對象Qrcode x = new Qrcode();// 設置二維碼的容錯能力等級x.setQrcodeErrorCorrect('M');// N代表的是數字,A代表的是a-z,B代表的是其他字符x.setQrcodeEncodeMode('B');// 版本x.setQrcodeVersion(7);// 設置驗證碼內容 可以輸入多次Scanner scanner = new Scanner(System.in);// String str = scanner.nextLine(); //只能輸入一次while (scanner.hasNext()) {String str = scanner.nextLine();// 設置驗證碼的大小int width = 67 + 12 * (7 - 1);int height = 67 + 12 * (7 - 1);// 定義緩沖區圖片BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// 設置畫圖工具Graphics2D gs = bufferedImage.createGraphics();// 設置二維碼背景顏色gs.setBackground(Color.white);//lightGray// 設置顏色gs.setColor(Color.black);//cyan,green,red,black,pink// 清除畫板內容gs.clearRect(0, 0, width, height);// 定義偏移量int pixoff = 2;// 填充的內容轉化為字節數byte[] d = str.getBytes("utf-8"); // 設置編碼方式if (d.length > 0 && d.length < 120) {boolean[][] s = x.calQrcode(d);for (int i = 0; i < s.length; i++) {for (int j = 0; j < s.length; j++) {if (s[j][i]) {// 驗證碼圖片填充內容gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);}}}}// 結束寫入gs.dispose();// 結束內存圖片bufferedImage.flush();/** 保存生成的二維碼圖片 第一先生成4位隨機字母字符串,用于給生成的二維碼命名 第二保存生成的二維碼* (char)(int)(Math.random()*26+65) 隨機生成一個大寫字母* (char)(int)(Math.random()*26+97) 隨機生成一個小寫字母*/System.out.println("生成的4位隨機字符串為:");for (int i = 0; i < 4; i++) {char c = (char) (int) (Math.random() * 26 + 65);System.out.print(c);}ImageIO.write(bufferedImage, "png", new File("E:/erweima/1" + (char) (int) (Math.random() * 26 + 65)+ (char) (int) (Math.random() * 26 + 97) + ".png"));System.out.println("\n二維碼圖片生成成功!");}} }第三種
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Hashtable; import java.util.Map;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.LuminanceSource; import com.google.zxing.MultiFormatReader; import com.google.zxing.MultiFormatWriter; import com.google.zxing.ReaderException; import com.google.zxing.Result; import com.google.zxing.Writer; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.oned.CodaBarWriter; import com.google.zxing.oned.Code128Writer; import com.google.zxing.oned.Code39Writer; import com.google.zxing.oned.EAN13Writer; import com.google.zxing.oned.EAN8Writer; import com.google.zxing.oned.ITFWriter; import com.google.zxing.oned.UPCAWriter; import com.google.zxing.pdf417.encoder.PDF417Writer; import com.google.zxing.qrcode.QRCodeWriter;/*** 利用zxing開源工具生成二維碼QRCode* * @date 2012-10-26* @author xhw* */ public class QRCode {private static final int BLACK = 0xff000000;private static final int WHITE = 0xFFFFFFFF;/*** @param args*/public static void main(String[] args) {QRCode test = new QRCode();File file = new File("E://erweima/test.png");test.encode("http://www.cnblogs.com/hongten", file, BarcodeFormat.QR_CODE, 200, 200, null);test.decode(file);}/*** 生成QRCode二維碼<br> * 在編碼時需要將com.google.zxing.qrcode.encoder.Encoder.java中的<br>* static final String DEFAULT_BYTE_MODE_ENCODING = "ISO8859-1";<br>* 修改為UTF-8,否則中文編譯后解析不了<br>*/public void encode(String contents, File file, BarcodeFormat format, int width, int height, Map<EncodeHintType, ?> hints) {try {//消除亂碼contents = new String(contents.getBytes("UTF-8"), "ISO-8859-1"); BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, format, width, height);writeToFile(bitMatrix, "png", file);} catch (Exception e) {e.printStackTrace();}}/*** 生成二維碼圖片<br>* * @param matrix* @param format圖片格式* @param file 生成二維碼圖片位置* @throws IOException*/public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {BufferedImage image = toBufferedImage(matrix);ImageIO.write(image, format, file);}/*** 生成二維碼內容<br> * @param matrix* @return*/public static BufferedImage toBufferedImage(BitMatrix matrix) {int width = matrix.getWidth();int height = matrix.getHeight();BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);for (int x = 0; x < width; x++) {for (int y = 0; y < height; y++) {image.setRGB(x, y, matrix.get(x, y) == true ? BLACK : WHITE);}}return image;}/*** 解析QRCode二維碼*/@SuppressWarnings("unchecked")public void decode(File file) {try {BufferedImage image;try {image = ImageIO.read(file);if (image == null) {System.out.println("Could not decode image");}LuminanceSource source = new BufferedImageLuminanceSource(image);BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));Result result;@SuppressWarnings("rawtypes")Hashtable hints = new Hashtable();//解碼設置編碼方式為:utf-8hints.put(DecodeHintType.CHARACTER_SET, "utf-8");result = new MultiFormatReader().decode(bitmap, hints);String resultStr = result.getText();System.out.println("解析后內容:" + 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());}} }效果展示:
參考鏈接:
總結
以上是生活随笔為你收集整理的Java自动生成二维码总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DC/DC升压转换器AAT1118 贴片
- 下一篇: iOS 多线程之同步和异步