生成后的图片:
所须jre包:Qrcode_swetake.jar 网上均可下载
源代码如下:
package com.yfly.test;
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 yfly
*
*/
public class QrcodeImg {
/**
* 生成二维码的方法
* @param content 二维码内容
* @param imgPath 图片路径
*/
public static void getQrcodeImg(String content, String imgPath) {
int width = 235;
int height = 235;
//实例化一个Qrcode对象
Qrcode myQrcode = new Qrcode();
//设置排错率
myQrcode.setQrcodeErrorCorrect('M');
//设置编码方式
myQrcode.setQrcodeEncodeMode('B');
//设置二维码版本
myQrcode.setQrcodeVersion(15);
//绘制二维码-->创建画板
BufferedImage bfImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//绘制工具
Graphics2D gd =bfImg.createGraphics();
//设置背景色
gd.setBackground(Color.black);
//设置前景色
gd.setColor(Color.white);
//创建二维码区域
gd.setClip(0, 0, width, height);
try {
//处理二维码
byte[] codeOut = content.getBytes("utf-8");
boolean[][] code = myQrcode.calQrcode(codeOut);
for (int i = 0; i < code.length; i++) {
for (int j = 0; j < code.length; j++) {
if(!code[j][i]) {
//遍历数组,true 绘图 false 不绘制
gd.fillRect(j*3+2, i*3+2, 3, 3);
}
}
}
//加载logo图片
File file = new File("F:/blog1.jpg");//这里替换成自己本地图片
Image srcImage = ImageIO.read(file);
int imgWidth = srcImage.getWidth(null);
int imgHeight = srcImage.getHeight(null);
gd.drawImage(srcImage, (width-imgHeight)/2, (height-imgHeight)/2, imgWidth, imgHeight,null, null );
//释放资源
gd.dispose();
bfImg.flush();
//写入到指定路径
ImageIO.write(bfImg, "png", new File(imgPath));
System.out.println("二维码生产成功");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
getQrcodeImg("这里编辑想要生成的二维码内容", "f:/img.png(这里设置保存图片的位置)");
}
}