Java代码生成二维码(ZXing工具类实操完整代码)
这里写目录标题
一、二维码原理
二维码又称QR Code,QR全称Quick Response,是一个近几年来移动设备上超流行的一种编码方式,它比传统的Bar Code条形码能存更多的信息,也能表示更多的数据类型:比如:字符,数字,日文,中文等等。
想深入了解请参考:(转载):http://t.csdn.cn/Pvvse
二、ZXing
2.1工具类
zxing项目是谷歌推出的用来识别多种格式条形码的开源项目,项目地址为https://github.com/zxing/zxing,zxing有多个人在维护,覆盖主流编程语言,也是目前还在维护的较受欢迎的二维码扫描开源项目之一。
zxing的项目很庞大,主要的核心代码在
core
文件夹里面,也可以单独下载由这个文件夹打包而成的jar
包,具体地址在http://mvnrepository.com/artifact/com.google.zxing/core,直接下载jar包也省去了通过maven
编译的麻烦。
2.2工具类实现的需求
最近项目中有生成带而二维码海报的需求,先研究一下二维码的生成,这个工具类可以生成带logo的二维码图片,如果有阿里云oss存储的可以直接上传到云服务器上,也可以输出到指定文件夹
三、ZXing生成二维码工具类(完整代码附后)
3.1 引入依赖
配置pom.xml文件,引入相关依赖
<!--生成二维码--> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.3.0</version> </dependency>
3.2工具类
/** * @author: Mr.zhao * @Description: ZXing生成二维码工具类 带logo * @date:2023年2月23日 下午3:53:55 */ public class ZXingCodeUtils { /** *配置常量信息 */ private static final int QRCOLOR = 0xFF000000; // 默认是黑色 private static final int BGWHITE = 0xFFFFFFFF; // 背景颜色 private static final int WIDTH = 170; // 二维码宽 private static final int HEIGHT = 170; // 二维码高 // 用于设置QR二维码参数 private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() { { put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别(H为最高级别)具体级别信息 put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式 put(EncodeHintType.MARGIN, 0); } }; /** * 根据输入的内容生成二维码+上传阿里云oss,返回url地址 * @param text:内容 * @param width:宽度 * @param height:高度 * */ public static String generateQRCodeImage(String text, int width, int height) { try { QRCodeWriter qrCodeWriter = new QRCodeWriter(); //创建二维码字节转换对象 BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height,hints); ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream(); MatrixToImageWriter.writeToStream(bitMatrix, "JPG", pngOutputStream); //阿里云oss存储容器bucket访问地址 String url = ""; //阿里云oss用户的Bucket所在数据中心的访问域名 String endpoint = ""; //阿里云oss访问密钥对 String accessKeyId = ""; String accessKeySecret = ""; // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret); //利用uuid工具类生成随机切全局唯一的命名 String newName = "code/"+UUIDUtil.getUUID() + ".jpg"; // 上传Byte数组。 byte[] content = pngOutputStream.toByteArray(); //阿里云存储容器的名字bucket ossClient.putObject("bucket", newName, new ByteArrayInputStream(content)); // 关闭OSSClient。 ossClient.shutdown(); return url+"/"+newName; } catch (WriterException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; } /** * 生成二维码 * @param content 扫码内容 * @param QRcodeWidth 二维码宽度 * @param QRcodeHeigh 二维码高度 * @param logoWidth logo宽度 * @param logoHeigh logo高度 * @param logoPath logo相对路径(null时不加logo) * @param QRcodeColor 二维码颜色 * @return * @throws Exception */ public static String generateQRcode(String content, int QRcodeWidth,int QRcodeHeigh,int logoWidth, int logoHeigh, String logoPath, int QRcodeColor) throws Exception{ /** 定义Map集合封装二维码配置信息 */ Map<EncodeHintType, Object> hints = new HashMap<>(); /** 设置二维码图片的内容编码 */ hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); /** 设置二维码图片的上、下、左、右间隙 */ hints.put(EncodeHintType.MARGIN, 1); /** 设置二维码的纠错级别 */ hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); /** * 创建二维码字节转换对象 * 第一个参数:二维码图片中的内容 * 第二个参数:二维码格式器 * 第三个参数:生成二维码图片的宽度 * 第四个参数:生成二维码图片的高度 * 第五个参数:生成二维码需要配置信息 * */ BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRcodeWidth, QRcodeHeigh, hints); /** 获取二维码图片真正的宽度 */ int matrix_width = matrix.getWidth(); /** 获取二维码图片真正的高度 */ int matrix_height = matrix.getHeight(); /** 定义一张空白的缓冲流图片 */ BufferedImage image = new BufferedImage(matrix_width, matrix_height, BufferedImage.TYPE_INT_RGB); /** 把二维码字节转换对象 转化 到缓冲流图片上 */ for (int x = 0; x < matrix_width; x++){ for (int y = 0; y < matrix_height; y++){ /** 通过x、y坐标获取一点的颜色 true: 黑色 false: 白色 */ int rgb = matrix.get(x, y) ? QRcodeColor : 0xFFFFFF; image.setRGB(x, y, rgb); } } if(!logoPath.equals("null")) { /** 获取logo图片 */ /** * static 内不能用this获取绝对路径 * 通过getCanonicalPath获取当前程序的绝对路径 */ File directory = new File("");//参数为空 String courseFile = directory.getCanonicalPath(); // String path = courseFile + "/C:/hwx/" +logoPath; // System.out.println(path); BufferedImage logo = ImageIO.read(new File(logoPath)); /** 获取缓冲流图片的画笔 */ Graphics2D g = (Graphics2D) image.getGraphics(); /** 在二维码图片中间绘制logo */ g.drawImage(logo, (matrix_width - logoWidth) / 2, (matrix_height - logoHeigh) / 2, logoWidth, logoHeigh, null); /** 设置画笔的颜色 */ g.setColor(Color.WHITE); /** 设置画笔的粗细 */ g.setStroke(new BasicStroke(5.0f)); /** 设置消除锯齿 */ g.setRenderingHint(RenderingHints .KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); /** 绘制圆角矩形 */ g.drawRoundRect((matrix_width - logoWidth) / 2, (matrix_height - logoHeigh) / 2, logoWidth, logoHeigh, 10, 10); } /** 生成二维码 */ //使用时间戳命名来保证唯一 String qrcodeName = System.currentTimeMillis()+".png"; //指定图片文件生成的路径 绝对路径path,需要提前创建 ImageIO.write(image, "png", new File("path" + qrcodeName));//输出带logo图片 return qrcodeName; } // public static void main(String[] args) throws Exception{ // generateQRcode("https://blog.csdn.net/ZXYD_10",300,300,90,120, // "default/67.jpg",0x6495ED); // }
3.3效果图
四、总结
使用zxing进行二维码的编解码是非常方便的,zxing的API覆盖了多种主流编程语言,具有良好的扩展性和可定制性。