Java 制作二维码代码

用MyEclipse 编写代码前,先在项目中导入二维码包 QRCode.jar

下载地址:http://download.csdn.net/detail/qqssliuxiu/9612857


public class QRcode {

public static void main(String[] args){
String content = "我的二维码"; //内容
String imgType = "png"; //图片格式
Integer version = 5; //版本
int pixel = 5; //模块像素值
String imgPath = "E:code.png"; //生成路径

//实现二维码
QRcode qrcode = new QRcode();
qrcode.createQrcode(content, imgType, version, pixel, imgPath);
System.out.println("二维码生成完毕,请查看!");
}

/**
* 生成二维码图片

* @param content 内容
* @param imgType 图片类型
* @param version 版本
* @param pixel 模块像素值
* @param imgPath 图片地址
*/
public void createQrcode(String content,String imgType,
int version, int pixel, String imgPath){
//确定图片大小
int imageSize = (17+4*version)*pixel+10;

//图片流进行基本设置
BufferedImage bufferImage = new BufferedImage(imageSize, imageSize, BufferedImage.TYPE_INT_BGR);
Graphics2D graphics = bufferImage.createGraphics();
graphics.setBackground(Color.WHITE);
graphics.clearRect(0, 0, imageSize, imageSize);
graphics.setColor(Color.BLACK);

//信息转换成二维数组
boolean[][] codeOut = changeContent(content,version);

//根据二维数据对图片进行填充
fillImage(graphics,pixel,codeOut);

//图片输出
try {
ImageIO.write(bufferImage, imgType, new File(imgPath));
} catch (Exception e) {
e.printStackTrace();
}
}


/**
* 对图片内容进行填充

* @param graphics 画板
* @param pixel 每个模块的像素值
* @param codeOut 加密后的内容
*/
private void fillImage(Graphics2D graphics, int pixel, boolean[][] codeOut) {
//输出内容 > 二维码
for(int i = 0; i < codeOut.length; i++){
for(int j = 0; j < codeOut.length; j++){
if(codeOut[i][j]){
//填充
graphics.fillRect(i*pixel+5, j*pixel+5, pixel, pixel);
}
}
}
}


/**
* 利用jar包把内容转换为QrCode的二维数组

* @param content 内容
* @param version 版本
* @return
*/
private boolean[][] changeContent(String content, int version) {
boolean[][] codeOut = null;
Qrcode qrcode = new Qrcode();
//设置二维码的排错率,可选为L(7%)、M(15%)、Q(25%)、H(30%),排错率越高存储的信息越少
qrcode.setQrcodeErrorCorrect('M');
//编码模版"B"
qrcode.setQrcodeEncodeMode('B');
//设置二维码的尺寸,取值范围1-40,值越大尺寸越大,可存储的信息越大
qrcode.setQrcodeVersion(version);
//开始加密内容
try {
codeOut = qrcode.calQrcode(content.getBytes("utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return codeOut;
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值