您的位置:首页 > 编程语言 > Java开发

Java 制作二维码代码

2016-08-25 16:21 405 查看
用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;
}

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