1 /** 2 * 3 */ 4 package qrcode; 5 import java.awt.Color; 6 import java.awt.Graphics2D; 7 import java.awt.Image; 8 import java.awt.image.BufferedImage; 9 import java.io.File; 10 import java.io.IOException; 11 12 import javax.imageio.ImageIO; 13 14 import com.swetake.util.Qrcode; 15 16 /** 17 * @author hy 18 * @date 2019-02-19 09:27:13 19 * 20 */ 21 public class QrcodeUtil { 22 public static void main(String[] args) { 23 try { 24 qrcodeCom(); 25 } catch (IOException e) { 26 // TODO 自動生成的 catch 塊 27 e.printStackTrace(); 28 } 29 } 30 private static void qrcodeCom() throws IOException { 31 int height=200; 32 int width=200; 33 String qrContent="www.hao123.com"; 34 Qrcode qrcode = new Qrcode(); 35 qrcode.setQrcodeEncodeMode('B');//N代表數字,A代表a-Z,B代表其它字符 36 qrcode.setQrcodeErrorCorrect('Q'); // 設置二維碼排錯率,可選L(7%)、M(15%)、Q(25%)、H(30%),排錯率越高可存儲的信息越少,但對二維碼清晰度的要求越小 37 qrcode.setQrcodeVersion(12);//版本,取值范圍1-40,值越大尺寸越大,可存儲的信息越大 38 byte[] contentBytes = qrContent.getBytes("utf-8"); //設置編碼 39 BufferedImage bfimg =new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 40 Graphics2D grap=bfimg.createGraphics(); 41 grap.setBackground(Color.WHITE);//設置背景色 42 grap.setColor(Color.BLACK);//設置二維碼顏色 43 grap.clearRect(0, 0, width, height);//清除下畫板內容 44 int pixoff = 2;// 設置偏移量,不設置可能導致解析出錯 45 if (contentBytes.length>0&&contentBytes.length<800) { 46 boolean[][] codeout=qrcode.calQrcode(contentBytes);//讓字符串生成二維碼 47 for (int i = 0; i < codeout.length; i++) { 48 for (int j = 0; j < codeout.length; j++) { 49 if (codeout[i][j]) { 50 grap.fillRect(i*3+pixoff, j*3+pixoff, 3, 3); 51 } 52 } 53 } 54 } 55 /***帶logo開始***/ 56 Image img = ImageIO.read(new File("E://logo.png"));// 實例化一個Image對象。 57 grap.drawImage(img, 70, 70, 60, 60, null);// 70,70是距離grap兩個邊的距離,60,60是中間logo的大小 58 /****logo結束******/ 59 grap.dispose(); 60 bfimg.flush(); 61 ImageIO.write(bfimg, "png", new File("E://qrcode.png")); 62 } 63 }
qrcode.png:logo.png: