java生成二维码(最初版)

时间:2023-12-23 08:10:38

研究了2个小时,发现自己竟然智障,用原先的图片覆盖另一个图片

package com.tz.util;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.imageio.ImageIO;

import com.swetake.util.Qrcode;//引进的包,我自己

/**
* 生成二维码
* @author yanlong
* content 二维码的内容
* imgPath二维码的路径
* return void 返回的类型
*
*/
public class QrcodeImg {
//生成一个二维码的方法
public static void getQrcodeImg(String content,String imgPath){
//实例化Qrcode 对象
Qrcode qcQrcode=new Qrcode();
//编码
qcQrcode.setQrcodeEncodeMode('B');
//排错率15%的大小
qcQrcode.setQrcodeErrorCorrect('M');
//版本
qcQrcode.setQrcodeVersion(15);

int width=235;
int height=235;
//花板
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
//绘制工具
Graphics2D gs=image.createGraphics();
//开始绘制
//背景色
gs.setBackground(Color.white);
//绘制矩形
gs.clearRect(0, 0, width, height);
//设置内容的颜色
gs.setColor(Color.black);
//开始处理我们的信息
byte[] codeOut;
try {
codeOut =content.getBytes("utf-8");
//通过byte返回布尔类型的数组。
boolean[][] code=qcQrcode.calQrcode(codeOut);
for(int i=0;i<code.length;i++){
for(int j=0;j<code.length;j++){
if(code[j][i]){
//如果为真则涂成黑色
gs.fillRect(j*3+2, i*3+2, 3, 3);
}
}
}
/*
//加载图片
File file=new File("C:/Users/yanlong/Desktop/3.png");
Image srcImage=ImageIO.read(file);
int _width=srcImage.getWidth(null);
int _heigth=srcImage.getHeight(null);
gs.drawImage(srcImage,(width-_width)/2,(height-_heigth)/2,_width,_heigth,null);
*/
//释放资源
gs.dispose();
image.flush();
//保存------,写入指定路径

ImageIO.write(image, "png", new File(imgPath));
System.out.println("二维码生成成功");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
//主方法
public static void main(String[] args){

getQrcodeImg(" ","C:/Users/yanlong/Desktop/3.png");

}

}