图片生成工具生成

  1.支持多中形式的图片,二维码,条形码

  2.支持一张图片多个二维码

  3.支持二维码图片上加logo

  4.支持图片头部底部添加文字描述

public class ZxingEncoderUtil {private static final String CHARSET = "utf-8";private static final String FORMAT = "JPG";private static Font font = null;/*** 二维码生成,支持一张图上多个二维码,支持图片添加字体(上下位置),支持二维码中间加logo,** @param content* @param qrWidth* @param qrHeight* @param barcodeFormat* @param logoPath* @param multiImgs* @param options       key image_top_1 *** 表示图片要加的内容* @return*/public static byte[] createImage(String content, int qrWidth, int qrHeight, BarcodeFormat barcodeFormat, String logoPath, Boolean multiImgs, Map<String, String> options) {//每个图片之间的间隔int gap = 0;//每行的行距int lineHeight = 0;//字符串的高度int strHeight = 15;List<String> contents = new ArrayList<>();try {HashMap<EncodeHintType, Object> hints = new HashMap<>();if (StringUtils.isNotBlank(logoPath)) {hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //容错等级 L、M、Q、H 其中 L 为最低, H 为最高} else {hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); //容错等级 L、M、Q、H 其中 L 为最低, H 为最高
            }hints.put(EncodeHintType.CHARACTER_SET, CHARSET); // 字符编码hints.put(EncodeHintType.MARGIN, 0); // 二维码与图片边距if (multiImgs != null && multiImgs) {String[] str = content.split(",");contents = Arrays.asList(str);gap = 15;} else {contents.add(content);}//去重ArrayList<String> result = new ArrayList<>();for (String item : contents) {if (Collections.frequency(result, item) < 1) result.add(item);}Map<String, SortedMap<String, String>> addImage = addOnImage(options);SortedMap<String, String> topMap = addImage.get("top");SortedMap<String, String> bottomMap = addImage.get("bottom");//行距if (topMap != null && !topMap.isEmpty() || bottomMap != null && !bottomMap.isEmpty()) {lineHeight = 5;}//画布的宽,高int bWidth = qrWidth;int bHeight = qrHeight + gap + lineHeight * 2;//如果是条形码,需要增加源字符串在画布上if (barcodeFormat.equals(BarcodeFormat.CODE_128)) {bHeight += strHeight;}//如果要加头文字,需要加上头部的高度if (topMap != null && !topMap.isEmpty()) {bHeight += strHeight * topMap.size();}//如果要加上底部描述,需要加上底部高度if (bottomMap != null && !bottomMap.isEmpty()) {bHeight += strHeight * bottomMap.size();}//整个画布的高度bHeight = bHeight * result.size() - gap;//设置画布BufferedImage source = new BufferedImage(bWidth, bHeight, BufferedImage.TYPE_INT_RGB);Graphics2D graph = source.createGraphics();//设置背景颜色
            graph.setBackground(Color.WHITE);graph.clearRect(0, 0, bWidth, bHeight);if (font == null) {FileInputStream inputStream = new FileInputStream(new File(ZxingEncoderUtil.class.getResource("/font/msyh.ttf").getFile()));font = Font.createFont(Font.TRUETYPE_FONT, inputStream).deriveFont(Font.BOLD, 14f);inputStream.close();}graph.setFont(font);graph.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);graph.setColor(Color.BLACK);//下一次起始Y位置int nextPosY = 0;//汇总一次的高度int singleHeight;int topHeight;for (String item : result) {singleHeight = 0;topHeight = 0;BufferedImage image = printImage(item, barcodeFormat, qrWidth, qrHeight, logoPath, hints);//画图片上部分if (topMap != null && !topMap.isEmpty()) {for (SortedMap.Entry<String, String> entry : topMap.entrySet()) {int strWidth = graph.getFontMetrics().stringWidth(entry.getValue());int strX = (image.getWidth(null) - strWidth) / 2;int strY = strHeight * Integer.valueOf(entry.getKey()) + nextPosY;graph.drawString(entry.getValue(), strX, strY);}topHeight = strHeight * topMap.size();}//图片坐标int imageX = 0;int imageY = topHeight + lineHeight + nextPosY;//画图片graph.drawImage(image, imageX, imageY, image.getWidth(null), image.getHeight(null), null);singleHeight += topHeight + lineHeight + image.getHeight(null);if (barcodeFormat.equals(BarcodeFormat.CODE_128)) {int strWidth = graph.getFontMetrics().stringWidth(item);int strX = (image.getWidth(null) - strWidth) / 2;int strY = imageY + strHeight + image.getHeight(null);graph.drawString(item, strX, strY);singleHeight += strHeight;}//画图片下部分if (bottomMap != null && !bottomMap.isEmpty()) {for (SortedMap.Entry<String, String> entry : bottomMap.entrySet()) {int strWidth = graph.getFontMetrics().stringWidth(entry.getValue());int strX = (image.getWidth(null) - strWidth) / 2;int strY = strHeight * Integer.valueOf(entry.getKey()) + nextPosY + singleHeight;graph.drawString(entry.getValue(), strX, strY);}singleHeight += strHeight * bottomMap.size();}//设置下次画图的位置int i = result.indexOf(item);nextPosY = (singleHeight + gap) * (i + 1);}graph.setStroke(new BasicStroke(3f));graph.dispose();return imageIO(source);} catch (Exception e) {}return null;}/*** BufferedImage 转字节流** @param source* @return*/private static byte[] imageIO(BufferedImage source) {try {ByteArrayOutputStream os = new ByteArrayOutputStream();ImageIO.write(source, "jpg", os);return os.toByteArray();} catch (Exception ex) {return null;}}/*** 插入LOGO** @param source* @param logoPath* @throws Exception*/private static void insertImage(BufferedImage source, String logoPath) throws Exception {File file = new File(ZxingEncoderUtil.class.getResource(String.format("/image/%s", logoPath)).getFile());if (!file.exists()) {throw new Exception("logo file not found.");}Image src = ImageIO.read(file);int width = src.getWidth(null);int height = src.getHeight(null);// 插入LOGOGraphics2D graph = source.createGraphics();int x = (source.getWidth() - width) / 2;int y = (source.getHeight() - height) / 2;graph.drawImage(src, x, y, width, height, null);Shape shape = new RoundRectangle2D.Float(x, y, width, height, 6, 6);graph.setStroke(new BasicStroke(3f));graph.draw(shape);graph.dispose();}/*** zxing工具生成BufferedImage** @param content* @param barcodeFormat* @param qrWidth* @param qrHeight* @param logoPath* @param hints* @return* @throws Exception*/private static BufferedImage printImage(String content, BarcodeFormat barcodeFormat, int qrWidth, int qrHeight, String logoPath, HashMap<EncodeHintType, Object> hints) throws Exception {BitMatrix bitMatrix = new MultiFormatWriter().encode(content, barcodeFormat, qrWidth, qrHeight, 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 (StringUtils.isNotBlank(logoPath)) {insertImage(image, logoPath);}return image;}/*** 获取位置参数** @param options key image_AA_BB  value ***  AA位置(top,bottom) BB 排序* @return*/private static Map<String, SortedMap<String, String>> addOnImage(Map<String, String> options) {Map<String, SortedMap<String, String>> result = Collections.synchronizedMap(new HashMap<String, SortedMap<String, String>>());SortedMap<String, String> topMap = Collections.synchronizedSortedMap(new TreeMap<String, String>());SortedMap<String, String> bottomMap = Collections.synchronizedSortedMap(new TreeMap<String, String>());try {if (options != null && !options.isEmpty())for (Map.Entry<String, String> entry : options.entrySet()) {if (StringUtils.isNotBlank(entry.getValue())) {//topif (entry.getKey().startsWith("image_top")) {topMap.put(entry.getKey().replace("image_top_", ""), entry.getValue());}//bottomif (entry.getKey().startsWith("image_bottom")) {bottomMap.put(entry.getKey().replace("image_bottom_", ""), entry.getValue());}}}} catch (Exception e) {}result.put("top", topMap);result.put("bottom", bottomMap);return result;}
}

在开发这个工具的途中遇到问题:在本地win系统上图片drawString时,中文显示正常,但是到linux系统时,中文就显示不出来,显示的是方框,造成这种问题是由于操作系统不支持中文字体导致,最终最佳的解决方案是,下载需要的字体,放根目录,通过读取文件的方式获得字体,

java.awt.Font类方法createFont获取文件的方式获得字体,从而改变drawString画中文不异常,此解决方案不必改动linux系统字体

转载于:https://www.cnblogs.com/spring-Ganoder/p/7449361.html

zxing二维码生成工具类相关推荐

  1. 二维码 生成工具类(文件转Base64字符串,Base64字符串转文件)

    希望我的知识榨干了能帮到你解除困难,要是没有帮助你的,问度娘和知爹 一.POM.xml依赖下载 二.工具类提供 一.POM.xml依赖下载 <!-- 生成二维码依赖 --><depe ...

  2. Java:二维码生成工具类

    java 二维码生成工具类 需要引入的maven <!--Java 生成二维码 --> <dependency><groupId>com.google.zxing& ...

  3. 微信小程序二维码生成工具,后端二维码生成工具类。

    微信小程序开发二维码生成工具类 前言 业务背景 设计思路 具体实现 接下来我们进行工具的改造 前言 或许这是你搜寻的第n篇文章来解决你项目中的问题,虽然我不能去替你完全适配你的业务需求,但是我可以给你 ...

  4. 谷歌zxing 二维码生成工具

    一.加入maven依赖 <!-- 谷歌zxing 二维码 --> <dependency><groupId>com.google.zxing</groupId ...

  5. 关于二维码生成工具类简介

    二维码生成 需求:后端生成PDF同时带二维码贴上PDF界面上 废话不多说先上代码 首先:添加maven坐标 <groupId>com.google.zxing</groupId> ...

  6. zxing 二维码生成深度定制

    二维码生成服务之深度定制 之前写了一篇二维码服务定制的博文,现在则在之前的基础上,再进一步,花样的实现深度定制的需求,我们的目标是二维码上的一切都是可以由用户来随意指定 设计 1. 技术相关 zxin ...

  7. 用ZXING生成二维码的工具类(可以去掉白边,添加logo)

    ===========================用ZXING生成二维码的工具类(可以去掉白边,添加logo)========================== /**  * @auther g ...

  8. 生成二维码、识别二维码的工具类

    笔者日常: 第一次用markdown写文章,有点手生~ 声明: 此工具类由本人二次整理改造后分享给大家,原编写者未知,虽然本人重写了大部分逻辑代码,但是核心部分仍然是采用的原来的代码.若涉及侵权问题, ...

  9. 支付宝支付 第五集:二维码生成工具

    支付宝支付 第五集:二维码生成工具 一.代码 目录结构 BufferedImageLuminanceSource.java package com.dzy.alipay.qrcode;import c ...

最新文章

  1. vector,数组,动态数组效率测试
  2. 专访SIGDIAL2020最佳论文一作高信龙一:成功都是一步步走出来的
  3. 二次元少女生成器、会开车的神经网络...2019年最好的17个机器学习项目!
  4. 嵌入式linux hdmi分辨率,【Firefly3399Pro】rk3399pro在Framebuffer状态命令行模式中强制HDMI输出固定分辨率...
  5. 一个简单判等例子的深度分析
  6. asp.net2.0中session在ie9下不能保存的问题
  7. VisualSVN 补丁,你懂的,需要的速度进~ (更新至6.0.1)
  8. 如何在浏览器中增加Jupyter / ipython笔记本的单元格宽度?
  9. [C语言数据存储深度解析]-内存数据搞不懂?三千字长文带你走进数据类型及其存储
  10. 阿里云祝顺民:因云而生的云原生网络
  11. opencv车牌照识别
  12. mne plot出错_MNE-Python 环境配置 | win 10
  13. 第二章 软件项目确立
  14. 教师学计算机信息,计算机教师
  15. python匿名函数调用_(Python) 函数、匿名函数
  16. 解决报错(Navigation cancelled from “/roleList“ to “/userlist“ with a new navigation.)_@jie
  17. 创业公司,老板说等公司做大了,给5%股权,建议你不要轻易相信
  18. 1367:查找二叉树(tree_a)
  19. WIN10家庭版安装Hvper-V
  20. layui表头样式_layui表格的样式设置

热门文章

  1. C实现二叉树的先序遍历,中序遍历,后序遍历
  2. c语言结构体赋值,并输出各种类型变量的值
  3. Java就业岗位有哪些?可以从事哪些工作?
  4. MySQL基础课堂笔记
  5. 火山小视频尼尔森:2019新线消费市场人群洞察报告(附下载)
  6. 《毅力–如何培养自律的习惯》读书笔记
  7. rJava安装及Java 开发R
  8. 数据库连接数过多 too many
  9. mysql Insert on duplicate引发的死锁
  10. 理解一致性哈希算法(consistent hashing)