Java自動生成二維碼總結
阿新 • • 發佈:2018-12-02
推薦一篇部落格: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 block e.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-8 hints.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()); } } }
效果展示:
參考連結: