java生成二维码 微信、支付宝、钉钉等等通用_java生成支付二维码-程序员宅基地

技术标签: java  钉钉二维码  微信二维码  支付宝二维码  二维码  

需要2个jar包  com.google.zxing  下的core.jar 和 javase.jar

<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.1</version>
</dependency>

<dependency>

<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.1</version>

</dependency>


java 代码

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;


import com.google.common.collect.Maps;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;


public class QRCodeUtil {


private static final int width = 300;// 默认二维码宽度
private static final int height = 300;// 默认二维码高度
private static final String format = "png";// 默认二维码文件格式
private static final Map<EncodeHintType, Object> hints = Maps.newHashMap();// 二维码参数


static {
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 字符编码
// 容错等级 L、M、Q、H 其中 L 为最低, H 为最高
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.MARGIN, 2);// 二维码与图片边距
}


/**
* 返回一个 BufferedImage 对象

* @param content
*            二维码内容
*/
public static BufferedImage toBufferedImage(String content)
throws WriterException, IOException {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}


/**
* 将二维码图片输出到一个流中

* @param content
*            二维码内容
* @param stream
*            输出流
*/
public static void writeToStream(String content, OutputStream stream)
throws WriterException, IOException {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter.writeToStream(bitMatrix, format, stream);
}


/**
* 生成二维码图片文件

* @param content
*            二维码内容
* @param path
*            文件保存路径
*/
public static void createQRCode(String content, String path)
throws WriterException, IOException {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
// toPath() 方法由 jdk1.7 及以上提供
MatrixToImageWriter.writeToPath(bitMatrix, format, new File(path).toPath());
}

public static void main(String[] args) {
try {
createQRCode("https://www.baidu.com", "D://1111.png");


} catch (Exception e) {
e.printStackTrace();
}
}

}


@RequestMapping("getQRCode.do")
public void getQRCodeImg(HttpServletRequest request, HttpServletResponse response) {
// 响应头
response.setDateHeader("expires", 0);
response.setHeader("Cache-control", "no-store,no-cache,must-revalidate");
response.addHeader("Cache-Control", "post-check=0,pre-check=0");
response.setHeader("pragma", "no-cache");
response.setContentType("image/jpeg");

String content= "www.baidu.com";
try {
// 响应流中绘制二维码
QRCodeUtil.writeToStream(content, response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();

}



jsp

<body>

            <img class="mt20 mb30" alt="二维码" src="/getQRCode.do"/>

</body>


-------------------------------------------------------这是分割线----------------------------------------------------------------

在二维码中插入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 = createImage(content, imgPath, needCompress);
ImageIO.write(image, FORMAT_NAME, output);
}

/**
* 创建二维码
*/

private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {

Hashtable hints = new Hashtable();
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_WIDTH,
QRCODE_HEIGHT, 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);
}
}
                //如果logo图片路径为空,则生成的二维码无logo
if (imgPath == null || "".equals(imgPath)) {
return image;
}


QRCodeCreator.insertImage(image, imgPath, needCompress);
return image;

}


/**
* 二维码中插入LOGO图片
*/
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_WIDTH - width) / 2;
int y = (QRCODE_HEIGHT - 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();

}


-------------------------------------------------------又是分割线^_^------------------------------------------

public void createWxQRCode() {

                int width = 280;
int height = 280;
// 二维码的图片格式
Hashtable hints = new Hashtable();
// 内容所使用编码
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
BufferedImage image = null;
ServletOutputStream out = null;
try {
// 二维码信息
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);
bitMatrix = deleteWhite(bitMatrix);
// 创建二维码
image = toBufferedImage(matrix);
try {
out = response.getOutputStream();
ImageIO.write(image, "gif", out);
image.flush();
out.flush();
} finally {
if (out != null) {
try {
out.close();
} catch (Exception e) {

}
}
}
} catch (Exception e) {

}

}

         /**
 *   去掉白边
 */
public static BitMatrix deleteWhite(BitMatrix matrix) {
int[] rec = matrix.getEnclosingRectangle();
int resWidth = rec[2] + 1;
int resHeight = rec[3] + 1;
BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
resMatrix.clear();
for (int i = 0; i < resWidth; i++) {
for (int j = 0; j < resHeight; j++) {
if (matrix.get(i + rec[0], j + rec[1]))
resMatrix.set(i, j);
}
}
return resMatrix;
}

public static BufferedImage toBufferedImage(BitMatrix matrix) {

int width = matrix.getWidth();
int height = matrix.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, matrix.get(x, y) ? BLACK : WHITE);
}
}
return image;

}




以上是本人亲测成功的,如有疑问请提出,共同进步,谢谢,逐渐完善。。。


版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/lsygood/article/details/80018996

智能推荐

联想高志国:超融合已进入2.0时代_高志国 2018-程序员宅基地

文章浏览阅读872次。超融合2.0时代真的来了吗?超融合迈进2.0时代早在,2017年9月,联想在发布新一代超融合产品——H1000高级版、H3000企业版和H3000标准版的同时提出,超融合正在步入以“应用智能感知”为核心的2.0时代。联想是从用户应用需求的变化,以及超融合技术和架构自身演进的角度提出的超融合2.0的概念,其核心思想是以自主可控、弹性、可定制化的应用感知模式取代传统的技术架构,_高志国 2018

SVN遇到None of the targets are working copies的正确处理方式-程序员宅基地

文章浏览阅读2.5w次。有可能有人会问我为什么还在使用svn而不是git,从现状来讲git毫无疑问是当下的翘楚,但是并不是每个公司都会顺应时代潮流,svn就是是我们公司成为了首选的版本控制工具,既来之则安之! 回到主题吧,就在我开发的过程中,一次偶然的操作导致了提交与更新都无法成功。每次得到的结果都是None of the targets are working copies!立马我想到的就是谷歌,但..._none of the targets are working copies

WPS插件开发流程(1)-程序员宅基地

文章浏览阅读3.4w次,点赞22次,收藏106次。OneKey_Lite是一款由 @只为设计 独立开发的WPS演示免费插件。在开发过程中,感恩于网上那些无私分享代码的陌生人,给我这个开发小白提供了重要的借鉴参考。于是我决定把用C#和Visual Studio开发WPS插件的每一个具体步骤分享出来,让免费分享精神继续传递下去,希望对需要的朋友提供一些帮助。(一)开发前准备1. 操作系统在Win10系统中引用WPS的dll文件可能会受到系统权限限制的..._wps插件开发

Real-Time-Voice-Cloning(github声音克隆项目演示)-程序员宅基地

文章浏览阅读3.2k次,点赞2次,收藏13次。github项目地址①检查pytorch的安装②ffmpeg是做什么的,在哪里下载?怎么使用?原文地址ffmpeg是一个处理多媒体信息的框架,有视频采集、视频格式转换、视频抓图、给视频加水印等功能requirements.txtpython项目中必须包含一个 requirements.txt 文件,用于记录所有依赖包及其精确的版本号,以便新环境部署切换到项目目录,生成requirement.txt文件并查看③Download Pretrained Mode..

教学语音提取文本系统_教学视频语音提取文本系统tefs-程序员宅基地

文章浏览阅读258次。资料:实践!实现纯前端下的音频剪辑处理我的蓝猫被削了JS纯前端实现audio音频剪裁剪切复制播放与上传audio-sculptorffmpeg.js用 Web 实现一个简易的音频编辑器100AUDIO 免费在线音频编辑器重要:audiomassAudioMass虽然是python和go运行,但是绝大部分代码是js..._教学视频语音提取文本系统tefs

克隆你的声音,可能只需要5秒钟:MockingBird实现AI拟声 (详解)_提取音色模仿声音的软件-程序员宅基地

文章浏览阅读5.2w次,点赞70次,收藏544次。语音克隆仅需5秒之:MockingBird实现AI拟MockingBird1. 背景2. 环境搭建2.1 安装pytorch2.2 安装ffmpeg2.3 下载MockingBird源码2.4 安装requirements2.5. 下载预训练模型3. 运行MockingBrid1. 背景继“AI换脸”刷屏之后,这个AI换声技术也开始受到关注AI换声也叫AI拟声,2. 环境搭建建议使用Anaconda,可参加之前博文2.1 安装pytorch这里我直接pip安装的CPU版本pip3 in_提取音色模仿声音的软件

随便推点

深度学习系列资料总结_cellpose 2.0-程序员宅基地

文章浏览阅读2.2w次,点赞126次,收藏467次。说明本系列深度学习资料集合包含机器学习、深度学习等各系列教程,主要以计算机视觉资料为主,包括图像识别、分类、检测、分割等,内容参考Github及网络资源,仅供个人学习。深度学习定义一般是指通过训练多层网络结构对未知数据进行分类或回归深度学习分类有监督学习方法——深度前馈网络、卷积神经网络、循环神经网络等;无监督学习方法——深度信念网、深度玻尔兹曼机,深度自编码器等。手写机器学习笔记github机器学习算法公式推导以及numpy实现github人工智能相关术语link。.................._cellpose 2.0

GitHub好玩有趣的开源项目_有没有开源的网页fps游戏-程序员宅基地

文章浏览阅读2.6k次。有些地址已经失效:访问目录地址https://github.com/Wechat-ggGitHub/Awesome-GitHub-Repohttps://github.com/Wechat-ggGitHub/Awesome-GitHub-Repo 好玩项目 摸鱼神器 宝藏项目 开源游戏 实战项目 前后端分离项目 毕业设计实战项目 高仿 App 项目 Vue 实战项目 小程序实战项目 Spring Boot 实战项目 管理系统 ._有没有开源的网页fps游戏

Junit 入门使用教程_junitgenerator怎么用-程序员宅基地

文章浏览阅读1.8k次,点赞5次,收藏25次。&#13; 1、Junit 是什么?&#13;  JUnit是一个Java语言的单元测试框架。它由Kent Beck和Erich Gamma建立,逐渐成为源于Kent Beck的sUnit的xUnit家族中最为成功的一个JUnit有它自己的JUnit扩展生态圈。多数Java的开发环境都已经集成了JUnit作为单元测试的工具。&#13;  注意:Junit 测试也是程序员测..._junitgenerator怎么用

基于arduino和openmv的智能小车设计制作流程_arduino和openmv跟随小车-程序员宅基地

文章浏览阅读4k次,点赞9次,收藏43次。arduino与openmv的智能物流小车一、购买模块组件准备阶段1、ArduinoMAGE2560+扩展板使用这个当做主控板,加上扩展板已经满足了所有需求,主要是也很便宜,唯一不足的是就是扩展板装上的时候,扩展板的电源接口的引脚有时候会与MAGE2560 的数据接口碰上,导致板子短路,当初因为这个换了好几块板子。2、openmvopenmv主要是用来扫码和识别物料颜色,我用的型号是openmv4 H7,识别很灵敏,但是换不同场景识别物料的时候一定要记得调节物料颜色阈值,不然有时候会识别不到。3_arduino和openmv跟随小车

.net用BouncyCastle进行签名&加解密_.net bouncycastle-程序员宅基地

文章浏览阅读1.4w次。.net用BouncyCastle进行签名&加解密_.net bouncycastle

sklearn.metrics.f1_score 使用方法-程序员宅基地

文章浏览阅读2.8w次,点赞14次,收藏74次。原网站:sklearn官网使用sklearn计算 F1 scoresklearn.metrics.f1_score(y_true, y_pred, labels=None, pos_label=1, average='binary', sample_weight=None, zero_division='warn')计算F1分数,也称为平衡F分数或F测度F1分数可..._metrics.f1_score