您的位置:首页 > 其它

利用Qrcode.jar生成二维码

2015-10-23 20:51 453 查看
package com.java.code;

import java.awt.Color;

import java.awt.Graphics2D;

import java.awt.image.BufferedImage;

import java.io.File;

import javax.imageio.ImageIO;

import javax.servlet.jsp.PageContext;

import com.swetake.util.Qrcode;

public class QrcodeTest {

     public static void getQrcode(String content, String imgPath) {

          try {

               int width = 140;

               int height = 140;

               Qrcode qrcode = new Qrcode();

               qrcode.setQrcodeErrorCorrect('M');

               qrcode.setQrcodeEncodeMode('B');

               qrcode.setQrcodeVersion(7);

               BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);

               // 绘制二维码

               Graphics2D gs = bi.createGraphics();

               gs.setBackground(Color.white);

               gs.clearRect(0, 0, width, height);

               gs.setColor(Color.green);

               // 获取内容,通过数组

               byte[] contentType = content.getBytes("gb2312");

               int pixoff = 2;

               if (contentType.length > 0 && contentType.length < 120) {

                    boolean[][] codeOut = qrcode.calQrcode(contentType);

                    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.out.println("erro");

               }

               gs.dispose();

               bi.flush();

               File imgFile = new File(imgPath);

               ImageIO.write(bi, "png", imgFile);

               System.out.println("ok");

          } catch (Exception e) {

               e.getMessage();

          }

     }

     public static void main(String[] args) {

          String content = "http://p4.qhimg.com/dmt/235_165_/t012097845e1edd19aa.jpg";

          String imgPath = "E:\\java_code\\QrcodeDemo\\WebContent\\images\\temp.png";

          getQrcode(content, imgPath);

     }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: