本文轉載:http://blog.csdn.net/huakaihualuo1223/article/details/7910232
修復了原作者里面的一些小BUG,將生成的二維碼,保存到了本地目錄。
1.首先要導入jar包(將jar包放到lib目錄下) 導入jar包的名稱為:Qrcode_swetake 下載jar包的連接http://download.csdn.net/detail/huakaihualuo1223/4527504復制下面代碼可以直接使用。
import java.awt.Color;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.io.File;import javax.imageio.ImageIO;import com.swetake.util.Qrcode;public class EncoderHandler {public static void encoderQRCoder(String content,File file) {try {Qrcode handler = new Qrcode();handler.setQrcodeErrorCorrect('M');handler.setQrcodeEncodeMode('B');handler.setQrcodeVersion(7);System.out.PRintln(content);byte[] contentBytes = content.getBytes("UTF-8");BufferedImage bufImg = new BufferedImage(140, 140, BufferedImage.TYPE_INT_RGB);Graphics2D gs = bufImg.createGraphics();gs.setBackground(Color.WHITE);gs.clearRect(0, 0, 140, 140);//設定圖像顏色:BLACKgs.setColor(Color.BLACK);//設置偏移量 不設置肯能導致解析出錯int pixoff = 2;//輸出內容:二維碼if(contentBytes.length > 0 && contentBytes.length < 124) {boolean[][] codeOut = handler.calQrcode(contentBytes);for(int i = 0; i < codeOut.length; i++) {for(int j = 0; j < codeOut.length; j++) {if(codeOut[j][i]) {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();//生成二維碼QRCode圖片ImageIO.write(bufImg, "jpg",file);} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) {String content = "姓名:maysnow 電話:123687495";File file = new File("d://TestQR//1.jpg");//二維碼保存目錄。比如現在的是在D盤根目錄創建了一個TestQR的文件夾。encoderQRCoder(content,file);}}
新聞熱點
疑難解答