需要下載QRCode.jar包,下載地址:http://download.csdn.net/detail/sinat_22750705/9748085package BasicsTest;import com.swetake.util.Qrcode;import javax.imageio.ImageIO;import java.awt.*;import java.awt.image.BufferedImage;import java.io.File;/** * 二維碼生成 * Created by xs on 2017/2/6. */public class QRCode { /** * @param args the command line arguments */ public static void main(String[] args) {//圖片地址和名稱 String imgPath = "./qrCodeTest.png"; //二維碼的內容 String content = "/t珊丫頭" + "/nCSDN :sinat_22750705"; QRCode handler = new QRCode(); handler.encodeQRCode(content, imgPath); System.out.PRintln("encoder QRcode success"); } /** * 生成二維碼(QRCode)圖片 * @param content * @param imgPath */ public void encodeQRCode(String content,String imgPath){ try{ //二維碼實體 Qrcode qrcodeHandler=new Qrcode(); //二維碼糾錯 qrcodeHandler.setQrcodeErrorCorrect('M'); //二維碼編碼模式 qrcodeHandler.setQrcodeEncodeMode('B'); //二維碼版本 qrcodeHandler.setQrcodeVersion(7); System.out.println(content); byte[] contentBytes = content.getBytes("utf-8"); //BufferedImage 提供創建和修改圖像的各種類。140 長 140 寬 BufferedImage bufImg = new BufferedImage(140, 140, BufferedImage.TYPE_INT_RGB); //返回一個呈現指定 BufferedImage 的 Graphics2D 對象。 Graphics2D gs = bufImg.createGraphics(); //背景顏色 gs.setBackground(Color.white); // public abstract void clearRect(int x, int y, int width, int height);寬 高 //clearRect() 清除一個矩形區域 gs.clearRect(0, 0, 140, 140); // 設定圖像顏色 > BLACK gs.setColor(Color.BLACK); // 設置偏移量 不設置可能導致解析出錯 int pixoff = 2; // 輸出內容 > 二維碼 if (contentBytes.length > 0 && contentBytes.length < 120) { boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes); for (int i = 0; i < codeOut.length; i++) { for (int j = 0; j < codeOut.length; j++) { if (codeOut[j][i]) { //fillRect() 填充一個矩形區域 gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3); } } } } else { System.err.println("QRCode content bytes length = " + contentBytes.length + " not in [ 0,120 ]. "); } //關閉窗體,并釋放資源 gs.dispose(); bufImg.flush(); //創建文件 File imgFile = new File(imgPath); // 生成二維碼QRCode圖片 ImageIO.write(bufImg, "png", imgFile); }catch (Exception e){ e.printStackTrace(); } }}
新聞熱點
疑難解答