java 二维码图片生成工具类

版权声明:本文为博主原创文章,随便转载。 https://blog.csdn.net/qq_37902949/article/details/81228320

简单二维码生成。

使用的是Qrcode获取boolean[][],再通过Graphics绘制生成图片。

1、lib添加jar包:QRCode.jar

2、代码:

package com.gx.code;

import java.awt.Color;
import java.awt.Graphics;
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;

/**
 * 
* @ClassName: CodeUtil 
* @Description: TODO(二维码工具类) 
* @author zhoujie 
* @date 2018年7月26日 下午9:02:39 
* @version V1.0
* <div style="width:200px;height:200px;background:red;"></div>
 */
public class CodeUtil {
	
	public static void main(String[] args) {
		String content = "hello world!";
		String newfile = "C:\\Users\\zj\\Desktop\\code.jpg";
		createCode(content, newfile, 175, 2); //生成二维码图片
	}
	
	/**
	* @Title: createCode 
	* @Description: 创建二维码图片
	* @param @param content 生成内容
	* @param @param fileDir 生成图片位置
	* @param @param lon 二维码图片大小
	* @param @param pixoff    偏移量
	* @return void    返回类型 
	* @throws
	 */
	public static void createCode(String content, String fileDir, Integer lon, Integer pixoff){
		//创建图片
		BufferedImage bufferedImage = new BufferedImage(lon, lon, 1);
		Graphics g = bufferedImage.getGraphics();
		g.setColor(Color.white);
		g.fillRect(0, 0, lon, lon);
		g.setColor(Color.black);
		//创建一个boolean类型二维数组
		boolean[][] bs = getBooleans(content);
		int len = bs.length;
		int weight = 3; //矩形点宽度
		for (int i = 0; i < len; i++) {
			for (int j = 0; j < len; j++) {
				if(bs[i][j]){
					g.fillRect(j * weight+pixoff, i * weight+pixoff, weight, weight); //绘制矩形点
				}
			}
		}
		g.dispose();
		try {
			ImageIO.write(bufferedImage, "jpg", new File(fileDir));
			System.out.println("生成二维码");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
     * 纠错等级分为
     * level L : 最大 7% 的错误能够被纠正;
     * level M : 最大 15% 的错误能够被纠正;
     * level Q : 最大 25% 的错误能够被纠正;
     * level H : 最大 30% 的错误能够被纠正;
     */
	public static boolean[][] getBooleans(String content){
		boolean[][] bs = null;
		Qrcode qrcode = new Qrcode();
		qrcode.setQrcodeErrorCorrect('M'); //纠错等级
		qrcode.setQrcodeEncodeMode('B'); //注意版本信息 N代表数字 、A代表 a-z,A-Z、B代表 其他)
		qrcode.setQrcodeVersion(10); //版本号  1-40
		try {
			bs = qrcode.calQrcode(content.getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return bs;
	}
	
}

ok,简单方便快捷。。

代码下载

猜你喜欢

转载自blog.csdn.net/qq_37902949/article/details/81228320