java如何生成二维码

编写生成二维码的Java代码:

public class CreateCode {
	public static void main(String[] args) {

		String data = "一个程序员的微信公众账号";

		// 生成二维码,注意testCode文件夹要存在.
		CreateCode.encode(data, "D:/testCode/二维码.JPG");

		}

		//2.对应的生成二维码的方法encode(),代码如下:

		public static boolean encode(String srcValue, String qrcodePicfilePath){

		int MAX_DATA_LENGTH = 200;

		     byte[] d = srcValue.getBytes();

		     int dataLength = d.length;

		     int imageWidth = 113; 

		     int imageHeight = imageWidth;

		     BufferedImage bi = new BufferedImage(imageWidth, imageHeight,BufferedImage.TYPE_INT_RGB);

		     Graphics2D g = bi.createGraphics();

		     g.setBackground(Color.WHITE);

		     g.clearRect(0, 0, imageWidth, imageHeight);

		     g.setColor(Color.BLACK);

		     if (dataLength > 0 && dataLength <= MAX_DATA_LENGTH) {

		        Qrcode qrcode = new Qrcode();

		        qrcode.setQrcodeErrorCorrect('M'); 

		        qrcode.setQrcodeEncodeMode('B'); 

		        qrcode.setQrcodeVersion(5);

		        boolean[][] b = qrcode.calQrcode(d);

		        int qrcodeDataLen = b.length;

		        for (int i = 0; i < qrcodeDataLen; i++) {

		           for (int j = 0; j < qrcodeDataLen; j++) {

		              if (b[j][i]) {

		                 g.fillRect(j * 3 + 2, i * 3 + 2, 3, 3); 

		              }

		           }

		        }

		        System.out.println("二维码成功生成!!");

		     } else {

		        System.out.println( dataLength +"大于"+ MAX_DATA_LENGTH);

		        return false;

		     }

		     g.dispose();

		     bi.flush();

		     File f = new File(qrcodePicfilePath);

		     String suffix = f.getName().substring(f.getName().indexOf(".")+1, f.getName().length());

		     System.out.println("二维码输出成功!!");

		     try {

		        ImageIO.write(bi, suffix, f);

		     } catch (IOException ioe) {

		        System.out.println("二维码生成失败" + ioe.getMessage());

		        return false;

		     }

		return true;

		}
}

生成二维码:
在这里插入图片描述
类中需要的jar包地址为:https://download.csdn.net/download/zhuhuihui123/11225933

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值