二维码的生成

今天突然翻到以前写的代码,发现自己已经有一点忘记了,于是打算写一篇博客来重新回忆一下

要用java代码生成二位码图片需要倒入QRCode.jar这个包,在http://mvnrepository.com/可以下载到。

package edu.interview.utils;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.UnsupportedEncodingException;

import javax.imageio.ImageIO;

import com.swetake.util.Qrcode;

/**
 * 生成二维码图片
 * @author Holmes
 * @version 1.0
 */
public class QRCodeUtils {
    /**
     * 生成二维码图片
     * @param path
     * @param content
     */
    public static void getQrCodeImg(String path, String content) {
    int width = 235;// 设置图片宽度
        int height = 235;// 设置图片高度
        // 创建QRCode对象
        Qrcode qrCode = new Qrcode();
        // 设置二维码排错率 可选项L(7%),M(15%),Q(25%),H(30%)
        qrCode.setQrcodeErrorCorrect('M');
        // 设置二进制
        qrCode.setQrcodeEncodeMode('B');
        // 设置版本
        qrCode.setQrcodeVersion(15);

        // 开始绘画图片,获取画板
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_BGR);
        // 获得画笔
        Graphics2D grap = image.createGraphics();
        // 设置背景色
        grap.setBackground(Color.WHITE);
        // 清空内容,创建二维码区域
        grap.clearRect(0, 0, width, height);
        // 设置画笔颜色
        grap.setColor(Color.BLACK);

        try {
            // 获取内容字节数组,设置编码集
            byte[] byteContents = content.getBytes("UTF-8");
            boolean[][] codeOut = qrCode.calQrcode(byteContents);
            // 画二维码的给个矩形
            for (int i = 0; i < codeOut.length; i++) {
                for (int j = 0; j < codeOut.length; j++) {
                    if (codeOut[j][i]) {
                        grap.fillRect(j * 3 + 10, i * 10 + 2, 3, 3);
                    }
                }
            }
            //实例化Image对象
            Image img=ImageIO.read(new File("F:\\WEB\\source\\avtar.png"));
            //画到画板
            grap.drawImage(img, 100, 100, 30, 30, null);
            
            // 释放资源
            grap.dispose();
            image.flush();

            File file = new File(path);
            ImageIO.write(image, "PNG", file);
            System.out.println("ok");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        QRCodeUtils.getQrCodeImg("F:\\CSSDMOE\\thanks.png", "谢谢你");
    }
}

 

posted @ 2015-10-20 11:09  googlemeoften  阅读(212)  评论(0编辑  收藏  举报