Java生成二维码

需要用到Qrcode这个文件jar放在web-inf下面的lib文件夹下面,同时,需要创建的是web项目


package com;
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;


/**
 * Java开发微信二维码扫一扫生成器
 * @version 1.0
 * @author Administrator
 *
 */
public class QrcodeTest {



/**
* 根据内容生成二维码图片
* @param contents 内容
* @param imgPath 生成图片存储的服务器地址
*/

public static void getQrcodeImgBycontents(
String contents,String imgPath){

int width=140;
int height=140;

try{
//实例化Qrcode new
Qrcode qrCode=new Qrcode();
//设置二维码的排错率 可选项L(7%),M(15%),Q(25%),H(30%)
qrCode.setQrcodeErrorCorrect('M');
qrCode.setQrcodeEncodeMode('B');

//设置二维码的尺寸 取值范围[1-40]
qrCode.setQrcodeVersion(7);
//设置图片的尺寸
BufferedImage bufImg=new BufferedImage(
width,height,BufferedImage.TYPE_INT_BGR);

//绘制二维码图片
Graphics2D gs=bufImg.createGraphics();
//设置二维码矩形区域的背景颜色,设置为白色
gs.setBackground(Color.WHITE);
//创建一个图片的矩形区域
gs.clearRect(0, 0, width, height);
//设置二维码的颜色
gs.setColor(Color.BLACK);


//获取内容,通过一个数组的形式 设置编码
byte[] contentBytes=contents.getBytes("gb2312");

//设置一个偏移量(如果不设置可能会导致解析错误)
int pixoff=2;

//输出二维码
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++){//被中间那个j害惨了,把它写成了i
if(codeOut[j][i]==true){
gs.fillRect(j*3+pixoff, i*3+pixoff, 3, 3);
}
}
}
}else{
System.out.println("出错了,可能是您的内容长度超出了最大限制!");
}

gs.dispose();
bufImg.flush();
//生成二维码的Qrcode图片
File imgFile=new File(imgPath);
if(!imgFile.exists()) imgFile.createNewFile(); 
ImageIO.write(bufImg, "png", imgFile);
System.out.println("生成二维码成功!");

}catch(Exception e){
e.getStackTrace();
e.printStackTrace();
}

}


//Java程序的入口函数
public static void main(String[] args){

System.out.println("Hello World!");

String contents="hello,my name is Xiaowen!";
String imgPath="D:\\Java_Tanzhou\\Xiaowen_Qrcode\\images\\xiaowen04.png";

getQrcodeImgBycontents(contents,imgPath);
System.out.println("Hello World!");
}


}







































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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值