java生成二维码测试源码


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


import javax.imageio.ImageIO;


import com.swetake.util.Qrcode;


/**
 * 二维码测试类   用到jar包QRcode.jar
 * @author colbor
 *
 */
public class QrcodeTest {
/**
* 获取内容生成二维码图片
* @param contents
* @param imgPath 生成图片存储服务器地址
* @throws Exception 
*/
public static void getQrcodeImgBycontents(String contents,String imgPath){
int width=140;
int height=140;
try{
Qrcode qrcode=new Qrcode();
//设置二维码排错率 可选项L(7%) M(15%)Q(25%)H(30%)
qrcode.setQrcodeErrorCorrect('M');
qrcode.setQrcodeEncodeMode('B');
//设置二维码的尺寸 取值范围(1-40)
qrcode.setQrcodeVersion(7);
//设置图片的尺寸
BufferedImage bufferImge=new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
//绘制二维码图片
Graphics2D gs=bufferImge.createGraphics();
//设置区域背景颜色
gs.setBackground(Color.white);
//创建一个图片矩形区域
gs.clearRect(0, 0, width, height);
//设置二维码颜色
gs.setColor(Color.BLACK);
//设置偏移量(如果不设置)可能会导致解析错误
int pixoff=2;
//获取内容,通过数组形式,设置编码
byte[] contentBytes=contents.getBytes("gb2312");
//输出二维码
if(contentBytes.length>0&&contentBytes.length<120){
boolean[][] codeOut=qrcode.calQrcode(contentBytes);
for(int i=0;i<codeOut.length;i++){
for(int j=0;j<codeOut.length;j++){
if(codeOut[j][i]){
gs.fillRect(j*3+pixoff, i*3+pixoff, 3, 3);
}
}
}
}else{
System.out.println("内容长度超出最大限制");
}
gs.dispose();
//刷新图片
bufferImge.flush();
//生成二维码的Qrcode图片
File imgFile=new File(imgPath);
ImageIO.write(bufferImge, "png", imgFile);
System.out.println("生成二维码成功");
}catch(Exception e){
e.getStackTrace();
}
}
public static void main(String[] args) {
String contents="大神王斌就是我,我就是大神王斌";
String imgPath="E:\\wsc.png";
getQrcodeImgBycontents(contents, imgPath);
System.out.println();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值