使用Java生成二维码

使用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");
    }
}

运行后生成的图片:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值