maven引入 com.google.zxing

package com.util.qrCode;import com.alibaba.druid.util.Base64;
import com.github.liaochong.myexcel.utils.StringUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;/*** @Description: (二维码) * @author:luoguohui * @date:2015-10-29 下午05:27:13*/
public class GenerateCode {private static final int QRCOLOR = 0xFF000000;   //默认是黑色private static final int BGWHITE = 0xFFFFFFFF;   //背景颜色/*** @Description 生成带logo,名称,可跳转微信二维码  指定长宽* @Author lic* @Date 2021-06-04*/public static String getLogoQRCode(String qrUrl, String productName, String logoUrl,int width, int height) {try {GenerateCode zp = new GenerateCode();BufferedImage bim = zp.getQR_CODEBufferedImage(qrUrl, BarcodeFormat.QR_CODE, width, height, zp.getDecodeHintType());return zp.addLogo_QRCode(bim,logoUrl, new LogoConfig(), productName,width, height);} catch (Exception e) {e.printStackTrace();}return null;}/*** 给二维码图片添加Logo * * @param qrPic * @param logoPic*/public String addLogo_QRCode(BufferedImage bim, String logoUrl, LogoConfig logoConfig, String productName,int width, int height) {try {/** * 读取二维码图片,并构建绘图对象 */BufferedImage image = bim;if(StringUtil.isNotBlank(logoUrl)){Graphics2D g = image.createGraphics();/** * 读取Logo图片 */BufferedImage logo = getRemoteBufferedImage(logoUrl);/** * 设置logo的大小,本人设置为二维码图片的20%,因为过大会盖掉二维码 */int widthLogo = logo.getWidth(null) > image.getWidth() * 3 / 10 ? (image.getWidth() * 3 / 10) : logo.getWidth(null),heightLogo = logo.getHeight(null) > image.getHeight() * 3 / 10 ? (image.getHeight() * 3 / 10) : logo.getWidth(null);/** * logo放在中心 */int x = (image.getWidth() - widthLogo) / 2;int y = (image.getHeight() - heightLogo) / 2;/** * logo放在右下角 * int x = (image.getWidth() - widthLogo); * int y = (image.getHeight() - heightLogo); *///开始绘制图片g.drawImage(logo, x, y, widthLogo, heightLogo, null);// g.drawRoundRect(x, y, widthLogo, heightLogo, 15, 15);// g.setStroke(new BasicStroke(logoConfig.getBorder()));// g.setColor(logoConfig.getBorderColor());// g.drawRect(x, y, widthLogo, heightLogo);g.dispose();logo.flush();}//把商品名称添加上去,商品名称不要太长哦,这里最多支持两行。太长就会自动截取啦if (productName != null && !productName.equals("")) {//新的图片,把带logo的二维码下面加上文字,预留文字高度BufferedImage outImage = new BufferedImage(width, height+50, BufferedImage.TYPE_4BYTE_ABGR);//                ClassLoader classLoader = ImageUtil.class.getClassLoader();
//                InputStream fontIs = classLoader.getResourceAsStream("font/simsun.ttc");Resource resource = new ClassPathResource("font/simsun.ttc");Font font = Font.createFont(Font.TRUETYPE_FONT, Objects.requireNonNull(resource.getInputStream()));GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();localGraphicsEnvironment.registerFont(font);Graphics2D outg = localGraphicsEnvironment.createGraphics(outImage);//画二维码到新的面板outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);//画文字到新的面板outg.setColor(Color.BLACK);outg.setFont(font.deriveFont(35F));//设置字体大小int strWidth = outg.getFontMetrics().stringWidth(productName);if (strWidth > width) {// //长度过长就截取前面部分// outg.drawString(productName, 0, image.getHeight() + (outImage.getHeight() - image.getHeight())/2 + 5 ); //画文字//长度过长就换行String productName1 = productName.substring(0, productName.length() / 2);String productName2 = productName.substring(productName.length() / 2, productName.length());int strWidth1 = outg.getFontMetrics().stringWidth(productName1);int strWidth2 = outg.getFontMetrics().stringWidth(productName2);outg.drawString(productName1,  (width-strWidth1)/2, image.getHeight()+20 );BufferedImage outImage2 = new BufferedImage(width, height+50, BufferedImage.TYPE_4BYTE_ABGR);Graphics2D outg2 = localGraphicsEnvironment.createGraphics(outImage2);outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);outg2.setColor(Color.BLACK);outg2.setFont(font.deriveFont(35F));outg2.drawString(productName2, (width-strWidth2)/2, image.getHeight()+50 );outg2.dispose();outImage2.flush();outImage = outImage2;} else {outg.drawString(productName,(width-strWidth)/2, image.getHeight() + (outImage.getHeight() - image.getHeight()) / 2 ); //画文字}outg.dispose();outImage.flush();image = outImage;}image.flush();ByteArrayOutputStream baos = new ByteArrayOutputStream();baos.flush();ImageIO.write(image, "png", baos);//二维码生成的路径,但是实际项目中,我们是把这生成的二维码显示到界面上的,因此下面的折行代码可以注释掉//可以看到这个方法最终返回的是这个二维码的imageBase64字符串//前端用 <img src="https://img-blog.csdnimg.cn/2022010613475123229.png"/> 其中${imageBase64QRCode}对应二维码的imageBase64字符串String imageBase64QRCode = Base64.byteArrayToBase64(baos.toByteArray());baos.close();return imageBase64QRCode;} catch (Exception e) {e.printStackTrace();}return null;}/*** 构建初始化二维码 * * @param bm * @return*/public BufferedImage fileToBufferedImage(BitMatrix bm) {BufferedImage image = null;try {int w = bm.getWidth(), h = bm.getHeight();image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);for (int x = 0; x < w; x++) {for (int y = 0; y < h; y++) {image.setRGB(x, y, bm.get(x, y) ? 0xFF000000 : 0xFFCCDDEE);}}} catch (Exception e) {e.printStackTrace();}return image;}/*** 生成二维码bufferedImage图片 * * @param content * 编码内容 * @param barcodeFormat * 编码类型 * @param width * 图片宽度 * @param height * 图片高度 * @param hints * 设置参数 * @return*/public BufferedImage getQR_CODEBufferedImage(String content, BarcodeFormat barcodeFormat, int width, int height, Map<EncodeHintType, ?> hints) {MultiFormatWriter multiFormatWriter = null;BitMatrix bm = null;BufferedImage image = null;try {multiFormatWriter = new MultiFormatWriter();// 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数bm = multiFormatWriter.encode(content, barcodeFormat, width, height, hints);int w = bm.getWidth();int h = bm.getHeight();image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);// 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF)白(0xFF000000)两色for (int x = 0; x < w; x++) {for (int y = 0; y < h; y++) {image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);}}} catch (WriterException e) {e.printStackTrace();}return image;}/*** 设置二维码的格式参数 * * @return*/public Map<EncodeHintType, Object> getDecodeHintType() {// 用于设置QR二维码参数Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();// 设置QR二维码的纠错级别(H为最高级别)具体级别信息hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置编码方式hints.put(EncodeHintType.CHARACTER_SET, "utf-8");hints.put(EncodeHintType.MARGIN, 0);hints.put(EncodeHintType.MAX_SIZE, 350);hints.put(EncodeHintType.MIN_SIZE, 100);return hints;}/***@Description 获取网络图片BufferedImage*@Author lic*@Date 2021-06-04*/public static BufferedImage getRemoteBufferedImage(String imageURL) {URL url = null;InputStream is = null;BufferedImage bufferedImage = null;try {url = new URL(imageURL);is = url.openStream();bufferedImage = ImageIO.read(is);} catch (MalformedURLException e) {e.printStackTrace();System.out.println("imageURL: " + imageURL + ",无效!");return null;} catch (IOException e) {e.printStackTrace();System.out.println("imageURL: " + imageURL + ",读取失败!");return null;} finally {try {if (is!=null) {is.close();}} catch (IOException e) {e.printStackTrace();System.out.println("imageURL: " + imageURL + ",流关闭异常!");return null;}}return bufferedImage;}}class LogoConfig {// logo默认边框颜色public static final Color DEFAULT_BORDERCOLOR = Color.WHITE;// logo默认边框宽度public static final int DEFAULT_BORDER = 2;// logo大小默认为照片的1/5public static final int DEFAULT_LOGOPART = 5;private final int border = DEFAULT_BORDER;private final Color borderColor;private final int logoPart;/*** Creates a default config with on color {@link #BLACK} and off color * {@link #WHITE}, generating normal black-on-white barcodes.*/public LogoConfig() {this(DEFAULT_BORDERCOLOR, DEFAULT_LOGOPART);}public LogoConfig(Color borderColor, int logoPart) {this.borderColor = borderColor;this.logoPart = logoPart;}public Color getBorderColor() {return borderColor;}public int getBorder() {return border;}public int getLogoPart() {return logoPart;}
}

JAVA生成带图片带名称的二维码相关推荐

  1. 小程序之 保存canvas生成商品图片附加小程序二维码 分享到朋友圈

    小程序之 保存canvas生成商品图片附加小程序二维码 分享到朋友圈 一.概述 需要用到的生成二维码组件(可自行下载添加到小程序根目录utils里):https://github.com/demi52 ...

  2. java生成自定义标志、大小的二维码

    为什么80%的码农都做不了架构师?>>>    前段时间没事突然看到有些宣传海报上面打印了带log的二维码,于是在网上查找了生成二维码的方法,自己进行了写修改,下面直接贴出代码供参考 ...

  3. java生成酷炫霸气叼二维码

    java生成二维码 文章目录 java生成二维码 pom依赖 第一种类型 第二种类型 完整pom文件 pom依赖 <!--生成二维码依赖--><!-- https://mvnrepo ...

  4. C#生成带背景和文字的二维码图片

    /// <summary>         /// 生成带背景和文字的二维码图片         /// </summary>         /// <param na ...

  5. PHP使用phpqrcode生成带LOGO或文字的二维码

    一.加入文字的代码示例: //如果没有文件夹 则自动创建$nowDay = date('Y-m-d');if(!is_dir($_SERVER['DOCUMENT_ROOT'].$path.$nowD ...

  6. Python学习之生成带logo背景图的二维码(静态和动态图)

    前言 二维码简称 QR Code(Quick Response Code),学名为快速响应矩阵码,是二维条码的一种,由日本的 Denso Wave 公司于 1994 年发明.现随着智能手机的普及,已广 ...

  7. Java实现生成可跳转指定页面的二维码

    Java实现生成可跳转指定页面的二维码 package test; import java.awt.BasicStroke; import java.awt.Graphics; import java ...

  8. Java实现一行代码生成二维码,可传输到前端展示,可自定义二维码样式,可设置图片格式,可对二维码添加图片,可对二维码添加文字,可以设置二维码大小、字体大小、字体颜色、边框颜色、边框大小等等

    Java实现一行代码生成二维码,可传输到前端展示,可自定义二维码样式,可设置图片格式,可对二维码添加图片,可对二维码添加文字,可以设置二维码大小.字体大小.字体颜色.边框颜色.边框大小等等. 0.准备 ...

  9. 基于ZXing Android实现生成二维码图片和相机扫描二维码图片即时解码的功能

    NextQRCode ZXing开源库的精简版 **基于ZXing Android实现生成二维码图片和相机扫描二维码图片即时解码的功能 原文博客 附源码下载地址** 与原ZXingMini项目对比 N ...

  10. 【Python实例分析】批量生成海报--自动添加姓名和二维码

    最近参加了老男孩的一个python训练营,里面某项任务是要求在某个海报模板上批量添加姓名和二维码,生成类似下图的海报. 图中我用红色方框标记的是需要修改的地方,先来聊下自己的思路: 1.要进行图片操作 ...

最新文章

  1. 怎么交换两个字符串_leetcode1202_go_交换字符串中的元素
  2. 检查数据库的CPU和PSU补丁信息
  3. python软件下载手机版-Learn Python中文版app
  4. 【互联网今日大事儿记】小米要做汽车了嘛!
  5. kafka同一个group 消费两个topic吗_MQ: 一张图读懂kafka工作原理
  6. python PyQt5 Signal类 (Signal类提供了一种以pythonic方式声明和连接Qt信号的方法)(connect()、disconnect()、emit())
  7. npm install 安装软件,出现 operation not permitted, mkdir 'C:\Program Files\nodejs\node_cache'...
  8. php斯芬克斯,斯芬克斯之迷——ie私有属性haslayout的困扰
  9. CF1223F. Stack Exterminable Arrays
  10. 《程序员代码面试指南》第三章 二叉树问题 二叉树节点间的最大距离问题
  11. bootstrap中如何使input中的小图标获得点击事件
  12. c mysql用户登录_SQL语句及5.7.2 mysql 用户管理 c_G
  13. 把一个人的特点写具体作文_把一个人的特点写具体作文450字
  14. DPDK DPVS 笔记 -> 基本框架整理
  15. Access——SQL语言查询
  16. 汉王考勤机管理系统服务器,汉王考勤管理系统7
  17. 方正计算机如何用u盘安装系统,方正电脑用u盘装系统操作方法
  18. 3D点云目标检测综述
  19. c# u盘使用记录_用 C# 编写 USB 存储设备使用痕迹检测和删除工具
  20. 关于word中如何生成自动目录以及页码编排

热门文章

  1. c语言赛车游戏代码大全,初学者天地游戏制作--赛车游戏的完整图
  2. 配置海思开发板的网络(永久修改)
  3. MacOS苹果系统下Chrome谷歌浏览器缓存目录
  4. 程序员真实从零开始实操 赚钱渠道之一CPS
  5. python抠出图片人像_Python抠图
  6. Ubuntu命令行下运行matlab
  7. 正交设计 python算法_人人都可以掌握的正交试验设计测试用例方法
  8. winrar远程代码执行漏洞(cve-2018-20250)
  9. excel组合汇总_Excel汇总20150202
  10. 如何解决 Chrome提示“adobe flash player 因过期而遭阻止?