首页 > 其他分享 >生成二维码

生成二维码

时间:2024-05-21 11:42:23浏览次数:13  
标签:Exception String param 生成 content 二维码 import throws

需要的依赖

        <!--生成二维码所需依赖-->
        <!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.5.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.5.3</version>
        </dependency>

生成二维码工具类

 
import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
 
/**
 * 二维码工具类
 * 
 */
public class QRCodeUtil {
 
	private static final String CHARSET = "utf-8";
	private static final String FORMAT_NAME = "JPG";
	private static final int QRCODE_SIZE = 300;// 二维码尺寸
	private static final int WIDTH = 60;// LOGO宽度
	private static final int HEIGHT = 60;// LOGO高度
 
	private static BufferedImage createImage(String content, String imgPath,
			boolean needCompress) throws Exception {
		Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
		hints.put(EncodeHintType.MARGIN, 1);
		BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
				BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
		int width = bitMatrix.getWidth();
		int height = bitMatrix.getHeight();
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
			}
		}
		if (imgPath == null || "".equals(imgPath)) {
			return image;
		}
		// 插入图片
		QRCodeUtil.insertImage(image, imgPath, needCompress);
		return image;
	}
 
	/**
	 * 插入LOGO
	 * 
	 * @param source
	 *            二维码图片
	 * @param imgPath
	 *            LOGO图片地址
	 * @param needCompress
	 *            是否压缩
	 * @throws Exception
	 */
	private static void insertImage(BufferedImage source, String imgPath,
			boolean needCompress) throws Exception {
		File file = new File(imgPath);
		if (!file.exists()) {
			System.err.println("" + imgPath + "   该文件不存在!");
			return;
		}
		Image src = ImageIO.read(new File(imgPath));
		int width = src.getWidth(null);
		int height = src.getHeight(null);
		if (needCompress) { // 压缩LOGO
			if (width > WIDTH) {
				width = WIDTH;
			}
			if (height > HEIGHT) {
				height = HEIGHT;
			}
			Image image = src.getScaledInstance(width, height,
					Image.SCALE_SMOOTH);
			BufferedImage tag = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			Graphics g = tag.getGraphics();
			g.drawImage(image, 0, 0, null); // 绘制缩小后的图
			g.dispose();
			src = image;
		}
		// 插入LOGO
		Graphics2D graph = source.createGraphics();
		int x = (QRCODE_SIZE - width) / 2;
		int y = (QRCODE_SIZE - height) / 2;
		graph.drawImage(src, x, y, width, height, null);
		Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
		graph.setStroke(new BasicStroke(3f));
		graph.draw(shape);
		graph.dispose();
	}
 
	/**
	 * 生成二维码(内嵌LOGO)
	 * 
	 * @param content
	 *            内容
	 * @param imgPath
	 *            LOGO地址
	 * @param destPath
	 *            存放目录
	 * @param needCompress
	 *            是否压缩LOGO
	 * @throws Exception
	 */
	public static void encode(String content, String imgPath, String destPath,
			boolean needCompress) throws Exception {
		BufferedImage image = QRCodeUtil.createImage(content, imgPath,
				needCompress);
		mkdirs(destPath);
//		SfPrintOrderParam param = new SfPrintOrderParam();
		String file = "QRCode"+".jpg";
		ImageIO.write(image, FORMAT_NAME, new File(destPath + "/" + file));
	}
 
	/**
	 * 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
	 * 
	 * @author lanyuan Email: [email protected]
	 * @date 2013-12-11 上午10:16:36
	 * @param destPath
	 *            存放目录
	 */
	public static void mkdirs(String destPath) {
		File file = new File(destPath);
		// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
		if (!file.exists() && !file.isDirectory()) {
			file.mkdirs();
		}
	}
 
	/**
	 * 生成二维码(内嵌LOGO)
	 * 
	 * @param content
	 *            内容
	 * @param imgPath
	 *            LOGO地址
	 * @param destPath
	 *            存储地址
	 * @throws Exception
	 */
	public static void encode(String content, String imgPath, String destPath)
			throws Exception {
		QRCodeUtil.encode(content, imgPath, destPath, false);
	}
 
	/**
	 * 生成二维码
	 * 
	 * @param content
	 *            内容
	 * @param destPath
	 *            存储地址
	 * @param needCompress
	 *            是否压缩LOGO
	 * @throws Exception
	 */
	public static void encode(String content, String destPath,
			boolean needCompress) throws Exception {
		QRCodeUtil.encode(content, null, destPath, needCompress);
	}
 
	/**
	 * 生成二维码
	 * 
	 * @param content
	 *            内容
	 * @param destPath
	 *            存储地址
	 * @throws Exception
	 */
	public static void encode(String content, String destPath) throws Exception {
		QRCodeUtil.encode(content, null, destPath, false);
	}
 
	/**
	 * 生成二维码(内嵌LOGO)
	 * 
	 * @param content
	 *            内容
	 * @param imgPath
	 *            LOGO地址
	 * @param output
	 *            输出流
	 * @param needCompress
	 *            是否压缩LOGO
	 * @throws Exception
	 */
	public static void encode(String content, String imgPath,
			OutputStream output, boolean needCompress) throws Exception {
		BufferedImage image = QRCodeUtil.createImage(content, imgPath,
				needCompress);
		ImageIO.write(image, FORMAT_NAME, output);
	}
 
	/**
	 * 生成二维码
	 * 
	 * @param content
	 *            内容
	 * @param output
	 *            输出流
	 * @throws Exception
	 */
	public static void encode(String content, OutputStream output)
			throws Exception {
		QRCodeUtil.encode(content, null, output, false);
	}
 
	/**
	 * 解析二维码
	 * 
	 * @param file
	 *            二维码图片
	 * @return
	 * @throws Exception
	 */
	public static String decode(File file) throws Exception {
		BufferedImage image;
		image = ImageIO.read(file);
		if (image == null) {
			return null;
		}
		BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(
				image);
		BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
		Result result;
		Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
		hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
		result = new MultiFormatReader().decode(bitmap, hints);
		String resultStr = result.getText();
		return resultStr;
	}
 
	/**
	 * 解析二维码
	 * 
	 * @param path
	 *            二维码图片地址
	 * @return
	 * @throws Exception
	 */
	public static String decode(String path) throws Exception {
		return QRCodeUtil.decode(new File(path));
	}
}

 测试生成二维码

package zxing;
public class TestQRcodeCreate {
    /**
 * 测试生成二维码
 * @param args
 * @throws Exception
 */
	public static void main(String[] args) {
		String text = "https://www.cnblogs.com/Dshzs17";//二维码内容
		try {
//			QRCodeUtil.encode(text, "D:\\codeImg\\QRCode\\", true);
			QRCodeUtil.encode(text, "D:\\codeImg\\QRCode\\logo.jpg", "D:\\codeImg\\QRCode\\",true);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
}

编写读取二维码内容的测试类

package zxing;

import java.io.File;

public class TestQRCodeRead {

    /**
 * 测试读取二维码内容
 * @param args
 * @throws Exception
 */
	public static void main(String[] args) throws Exception {
		String path = "D:\\codeImg\\QRCode\\" + File.separator + "kt.png";
		String decode = QRCodeUtil.decode(path);
		System.out.println(decode);//https://www.baidu.com/
	}
}

 

标签:Exception,String,param,生成,content,二维码,import,throws
From: https://www.cnblogs.com/Dshzs17/p/18203627

相关文章

  • uniApp生成的h5页面禁止浏览器上缩放页面(支持安卓,ios)
    项目场景:uniapph5内嵌原生appios样式问题:1.双击和双指滑动,内嵌的h5页面均会被放大缩小2.修改ios底部的安全距离的背景色,默认是白色问题描述1.双击和双指滑动,内嵌的h5页面均会被放大缩小2.解决ios底部的安全距离和修改背景色,默认是白色解决方案:安卓只需要在h5.template.h......
  • 生成子群阶数问题
    之前看到grass8cow博客中关于GrupaPermutacji这道题做法的简略记述后一直感觉这个题是究极神秘题。APIO听了Kubic的讲课(当时讲的是LOJ177生成子群阶数)后终于算是懂了一点了。众所周知,所有有限群同构于一个置换群的子群。当我们拿着一堆置换,然后再复合来复合去,所有可能......
  • NumPy 数组排序、过滤与随机数生成详解
    NumPy数组排序排序数组排序数组意味着将元素按特定顺序排列。顺序可以是数字大小、字母顺序、升序或降序等。NumPy的ndarray对象提供了一个名为sort()的函数,用于对数组进行排序。示例:importnumpyasnparr=np.array([3,2,0,1])print(np.sort(arr))输出:[0......
  • Liunx下通过netcore接口生成前端图片的问题。
    用netcore来生成前端微信Native支付的二维码。1、首先CentOS7.0要安装libgdiplus,命令如下:yuminstalllibgdiplus-devel,然后重启netcore服务。//这个地方要注意,网上有不少例子的下载命令是错的,有的时候安装不上。2、Vs代码使用QRCoder库,代码如下publicstaticMemoryStream......
  • axis2生成wsdl回执参数首字母大小写问题
    在跟局方对接接口的时候,局方回执我的wsdl接口,发现收不到同步回执,怀疑问题为回执参数首字母小写导致  代码中的参数对象首字母确实是大写,但生成的wsdl文件确变成了小写,目前是用axis2生成的参考:https://bbs.csdn.net/topics/390457284发现了变为小写的原因,选择使用xFire......
  • Amazon Q Developer 实战:从新代码生成到遗留代码优化(上)
    本文将探索如何在VisualStudioCode这个开发者常用的一种集成编程环境(IDE)中,使用AmazonQDeveloper列出指定区域的AmazonS3存储桶的示例代码实现。我们将从在AmazonQDeveloperAgent的协助下,从生成新代码开始,到将生成的新代码与现有的低效“遗留”旧代码进行性能对比;......
  • 【.NET项目分享】免费开源的静态博客生成工具EasyBlog,5分钟拥有自己的博客
    EasyBlog说明本博客系统通过构建工具生成纯静态的博客网站,借助GitHubPages,你可以在5分钟内免费拥有个人博客。它具有以下特点生成纯静态网站,访问速度极快使用markdown格式来编写博客内容基于git代码管理来存储你的博客使用CI工具来自动化部署你的博客站点效果展示:NilTo......
  • 人工智能帮你一键生成完美架构图
    简介架构图通过图形化的表达方式,用于呈现系统、软件的结构、组件、关系和交互方式。一个明确的架构图可以更好地辅助业务分析、技术架构分析的工作。架构图的设计是一个有难度的任务,设计者必须要对业务、相关技术栈都非常清晰才能设计出来符合需求的架构图。实践演练有明确的......
  • Uni-app 之IOS生成Universal Link(通用链接)
    一、文档https://uniapp.dcloud.net.cn/api/plugins/universal-links.html#%E8%83%8C%E6%99%AF%E4%BB%8B%E7%BB%8D二、配置1、登录苹果开发者中心找到对应的APPID,配置AssociatedDomains,如下: 2、创建apple-app-site-association文件(没有后缀){"applinks":{......
  • 开源低代码框架 ReZero API 正式版本发布 ,界面操作直接生成API
    一、ReZero简介ReZero是一款.NET中间件:全网唯一界面操作就能生成API, 可以集成到任何.NET6+API项目,无破坏性,也可让非.NET用户使用exe文件免费开源:MIT最宽松协议,一直从事开源事业十年,一直坚持开源1.1纯ReZero开发适合.NetCore零基础用户,大大简化了.NetCore开发门......