JAVA使用qrcode生成二维码(带logo/不带logo)

时间:2023-03-09 02:10:41
JAVA使用qrcode生成二维码(带logo/不带logo)
 /**
*
*/
package qrcode;
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 javax.imageio.ImageIO; import com.swetake.util.Qrcode; /**
* @author hy
* @date 2019-02-19 09:27:13
*
*/
public class QrcodeUtil {
public static void main(String[] args) {
try {
qrcodeCom();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
private static void qrcodeCom() throws IOException {
int height=200;
int width=200;
String qrContent="www.hao123.com";
Qrcode qrcode = new Qrcode();
qrcode.setQrcodeEncodeMode('B');//N代表数字,A代表a-Z,B代表其它字符
qrcode.setQrcodeErrorCorrect('Q'); // 设置二维码排错率,可选L(7%)、M(15%)、Q(25%)、H(30%),排错率越高可存储的信息越少,但对二维码清晰度的要求越小
qrcode.setQrcodeVersion(12);//版本,取值范围1-40,值越大尺寸越大,可存储的信息越大
byte[] contentBytes = qrContent.getBytes("utf-8"); //设置编码
BufferedImage bfimg =new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D grap=bfimg.createGraphics();
grap.setBackground(Color.WHITE);//设置背景色
grap.setColor(Color.BLACK);//设置二维码颜色
grap.clearRect(0, 0, width, height);//清除下画板内容
int pixoff = 2;// 设置偏移量,不设置可能导致解析出错
if (contentBytes.length>0&&contentBytes.length<800) {
boolean[][] codeout=qrcode.calQrcode(contentBytes);//让字符串生成二维码
for (int i = 0; i < codeout.length; i++) {
for (int j = 0; j < codeout.length; j++) {
if (codeout[i][j]) {
grap.fillRect(i*3+pixoff, j*3+pixoff, 3, 3);
}
}
}
}
/***带logo开始***/
Image img = ImageIO.read(new File("E://logo.png"));// 实例化一个Image对象。
grap.drawImage(img, 70, 70, 60, 60, null);// 70,70是距离grap两个边的距离,60,60是中间logo的大小
/****logo结束******/
grap.dispose();
bfimg.flush();
ImageIO.write(bfimg, "png", new File("E://qrcode.png"));
}
}

qrcode.png:JAVA使用qrcode生成二维码(带logo/不带logo)logo.png:JAVA使用qrcode生成二维码(带logo/不带logo)