Java生成二维码(附源码及相应jar包)

准备工作:导入QRCode.jar
下载链接:https://files-cdn.cnblogs.com/files/bigroc/QRCode.zip
工具类:

public class QRCodeUtil {
	//参数分别为:扫码后信息,二维码路径,二维码图片格式,二维码图片边长
	public void encoderQRCode(String content,String imgPatg,String imgType,int size) throws Exception{
		//内存中的一张二维码图片
		RenderedImage bufImg = qRcodeCommon(content,imgType,size);
		File file = new File(imgPatg);
		//生成图片,
		ImageIO.write(bufImg, imgType, file);
	}
	
	public BufferedImage qRcodeCommon(String content,String imgType,int size) throws Exception{
		BufferedImage bufImg = null;
		Qrcode qrCodeHandler = new Qrcode();
		//设置二维码的排错率:7% L<M<Q<H 30%:排错率越高,可存储信息越少,但是对二维码清晰度要求低
		qrCodeHandler.setQrcodeErrorCorrect('M');
		//二维码可存放的信息:N:只能放数字,A:数字+A-Z B:都支持
		qrCodeHandler.setQrcodeEncodeMode('B');
		//尺寸:取值范围:1-40
		qrCodeHandler.setQrcodeVersion(size);
		//字符串转Boolean数组
		byte[] contentBytes = content.getBytes("UTF-8");
		boolean[][] codeOut = qrCodeHandler.calQrcode(contentBytes);
		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;
		//画
		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);
				}
			}
		}
		//增加logo(img),加载一个img对象
		Image logo = ImageIO.read(new File("src/logo.jpg"));
		//在已生成的二维码上画logo,坐标,宽高(logo不能太大,否则有可能识别不了)
		int maxHeigth = bufImg.getHeight();
		int maxWdith = bufImg.getWidth();
		gs.drawImage(logo,imgSize/5*2, imgSize/5*2, maxWdith/5,maxHeigth/5,null);
		gs.dispose();//释放空间
		bufImg.flush();//清理
		return bufImg;
	}
}

测试:

public class qrcodeTest {
	public static void main(String[] args) throws Exception {
		//生成二维码
		String imgPath = "src/二维码.png";//生成二维码图片的路径
		String content = "http://www.baidu.com";//二维码中信息,可以是文字信息网址等
		QRCodeUtil qrUtil = new QRCodeUtil();
		qrUtil.encoderQRCode(content, imgPath, "png", 7);//7为生成二维码图片的大小
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值