使用Java生成二维码

来源:互联网 发布:星星知我心主题曲原唱 编辑:程序博客网 时间:2024/06/13 02:30

使用Java生成二维码

摘要:本文中代码的作用是使用Java生成二维码。

硬件环境:Windows
软件环境:jdk1.8.0.144、eclipse
所需jar包:Qrcode.jar

代码:

package com.ck.test;import java.awt.Color;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;import com.swetake.util.Qrcode;public class Test {    /**     * 生成二维码图片     * @param content 扫描二维码后显示的内容     * @param path 生成的二维码图片保存的路径,比如 C:/img/qrcode.png     * @throws IOException      */    public static void generateQRImage(String content,String path) throws IOException{        Qrcode x=new Qrcode();        x.setQrcodeErrorCorrect('M');//纠错等级        x.setQrcodeEncodeMode('B');//数据的类型        x.setQrcodeVersion(7);//设置版本        int width = 67 + 12 * (7 - 1);//公式:67 + 12 * (版本号 - 1)        int height = 67 + 12 * (7 - 1);        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//参数是宽度,高度,颜色类型        Graphics2D graphics2d = bufferedImage.createGraphics();//创建画图对象        graphics2d.setColor(Color.BLACK);//设置内容颜色        graphics2d.setBackground(Color.WHITE);//设置背景颜色        graphics2d.clearRect(0, 0, width, height);//清除出一块矩形空间,供画图用        byte[] d = content.getBytes("utf-8");        if (d.length>0 && d.length <120){            boolean[][] s = x.calQrcode(d);            for (int i=0;i<s.length;i++){                for (int j=0;j<s.length;j++){                    if (s[j][i]) {                        graphics2d.fillRect(j*3+2,i*3+2,3,3);                    }                }            }        }        graphics2d.dispose();        bufferedImage.flush();        File file = new File(path);        if (!file.exists()) {            file.mkdirs();        }        ImageIO.write(bufferedImage, "png", new File(path));    }    public static void main(String[] args) throws IOException {        generateQRImage("我是大帅哥!!!", "D:/test/qrcode.png");    }}

运行后生成的图片:

欢迎大家看我的博客,刚开始写,以后会写的越来越好的!大家有什么问题请留言,大家共同提高!
源码包可以在我贡献的资源中下载哦~