QRcode生成二维码

现在还存在的问题就是不知道如何往二维码中间加logo,还需要继续努力,fighting奋斗

public class TwoDimensionCode {
/**

* @param content 二维码内容
* @param imgType 二维码图片类型
* @param size    二维码图片大小
* @param imagePath  二维码图片路径
* @param response
* @return BufferedImage 返回图像
* @author miss wang
*/
public BufferedImage encodeQRCode(String content,String imgType,int size,String imagePath,HttpServletResponse response){
BufferedImage bufimg=null;
try{
Qrcode qrHandler=new Qrcode();
// 设置二维码的拍错率,可选L(7%),M(15%),Q(25%),H(30%)拍错率越高,可存储的信息越小,但是对
// 二维码清晰度的要求就越小
qrHandler.setQrcodeErrorCorrect('M');
qrHandler.setQrcodeEncodeMode('B');
// 设置二维码的尺寸,范围是1-40,取值范围越大,可存储的信息越多
qrHandler.setQrcodeVersion(size);
//获得内容的字节数组,试着编码格式
byte[] contentBytes=content.getBytes("utf-8");
//图片尺寸
int imgsize=67+12*(size-1);
bufimg=new BufferedImage(imgsize,imgsize,BufferedImage.TYPE_INT_RGB);
Graphics2D gs=bufimg.createGraphics();
// 设置背景颜色
gs.setBackground(Color.white);
gs.clearRect(0, 0, imgsize,imgsize);
// 设定图像颜色
gs.setColor(Color.black);
// 设置偏移量,不设置可能会出错
int pixoff=2;
// 输出内容 二维码
if(contentBytes.length>0 && contentBytes.length<800){
boolean [][]codeout=qrHandler.calQrcode(contentBytes);
for(int i=0;i<codeout.length;i++){
for(int j=0;j<codeout.length;j++){
if(codeout[i][j]){
gs.fillRect(i*3+pixoff,j*3+pixoff,3,3);
}
}
}
}else{
throw new Exception("QRCode content bytes length="+contentBytes.length+"not in [0,800]");
}
gs.dispose();
bufimg.flush();
}catch(Exception e ){
e.printStackTrace();
}
// 生成二维码QRcode图片
try{
// File imgfile=new File(imagePath);
ImageIO.write(bufimg, imgType,response.getOutputStream());
}catch(IOException e){
e.printStackTrace();
}
return bufimg;
}
public String decodeQRCode(String imgPath){
File imgfile=new File(imgPath);
BufferedImage bufimg=null;
String content =null;
try{
bufimg=ImageIO.read(imgfile);
QRCodeDecoder decoder=new QRCodeDecoder();
content=new String(decoder.decode(new TwoDeminsionCodeImage(bufimg)),"utf-8");
}catch(IOException e){
e.printStackTrace();
}catch(DecodingFailedException dfe){
System.out.println("Error"+dfe.getMessage());
dfe.printStackTrace();
}
return content;
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setHeader("content-type","text/html;charset=utf-8");*///PrintWriter out.write()会存在乱码现象
String value = request.getParameter("qrcodeValue");
System.out.println(value);

String imgPath ="F:/test.png";
 TwoDimensionCode handler = new TwoDimensionCode();
BufferedImage bufimg= handler.encodeQRCode(value, "png", 20, imgPath,response); // 内容 图片
 // 图片格式 大小
 System.out.println(imgPath);

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值