二维码

1.Maven引入barcode4j依赖

<!-- 条形码生成 --><dependency><groupId>net.sf.barcode4j</groupId><artifactId>barcode4j</artifactId><version>2.1</version></dependency>
<!-- https://mvnrepository.com/artifact/org.apache.avalon.framework/avalon-framework-api --><dependency><groupId>org.apache.avalon.framework</groupId><artifactId>avalon-framework-api</artifactId><version>4.3.1</version></dependency>

2.工具类

package com.wulianwang.manage.utils.util;import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfiguration;
import org.apache.commons.io.FileUtils;
import org.krysalis.barcode4j.BarcodeException;
import org.krysalis.barcode4j.BarcodeGenerator;
import org.krysalis.barcode4j.BarcodeUtil;
import org.krysalis.barcode4j.HumanReadablePlacement;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;import java.awt.image.BufferedImage;
import java.io.*;/*** 条形码工具类*/
public class BarCodeUtils {/**************************** 条形码  ********************************/
/*** 生成code128条形码** @param message       要生成的文本* @param withQuietZone 是否两边留白* @param hideText      隐藏可读文本* @param filePath      文件生成的路径*/public static void generateBarCode128(String message, boolean withQuietZone, boolean hideText, String filePath) {Code128Bean bean = new Code128Bean();// 分辨率int dpi = 512;// 设置两侧是否留白bean.doQuietZone(withQuietZone);// 设置条形码高度和宽度(不填就是默认的)
//        bean.setBarHeight((double) ObjectUtils.defaultIfNull(height, 9.0D));
//        if (width != null) {
//            bean.setModuleWidth(width);
//        }// 设置文本位置(包括是否显示)if (hideText) {bean.setMsgPosition(HumanReadablePlacement.HRP_NONE);}// 设置图片类型String format = "image/png";
ByteArrayOutputStream ous = new ByteArrayOutputStream();BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format, dpi,BufferedImage.TYPE_BYTE_BINARY, false, 0);// 生产条形码bean.generateBarcode(canvas, message);
try {canvas.finish();//字节码byte[] bytes = ous.toByteArray();FileUtils.writeByteArrayToFile(new File(filePath), bytes);} catch (IOException e) {e.printStackTrace();}}/**************************** 二维码  ********************************//*** 生成二维码* @param message       要生成的文本* @param filePath      文件生成的路径*/public static void genQRCode(String message, String filePath){try {BarcodeUtil util = BarcodeUtil.getInstance();DefaultConfiguration cfg = new DefaultConfiguration("barcode");// Bar code typeDefaultConfiguration child = new DefaultConfiguration("datamatrix");cfg.addChild(child);// Human readable text positionDefaultConfiguration attr = new DefaultConfiguration("human-readable");
//        //设置高度(无效果)
//        attr = new DefaultConfiguration("height");
//        attr.setValue(50);
//        child.addChild(attr);//设置二维码宽度attr = new DefaultConfiguration("module-width");attr.setValue("2.0");child.addChild(attr);BarcodeGenerator gen = util.createBarcodeGenerator(cfg);//分辨率int resolution = 300;// 设置图片类型String format = "image/png";ByteArrayOutputStream ous = new ByteArrayOutputStream();BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format, resolution,BufferedImage.TYPE_BYTE_BINARY, false, 0);gen.generateBarcode(canvas, message);canvas.finish();//字节码byte[] bytes = ous.toByteArray();FileUtils.writeByteArrayToFile(new File(filePath), bytes);} catch (ConfigurationException e) {e.printStackTrace();} catch (BarcodeException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
}

3.调用工具类测试一下

  @org.junit.Testpublic void test1() throws IOException {BarCodeUtils.generateBarCode128("V000001", true, false,"./bbb.jpg");}

4.生成条形码图片

二维码

生成带logo的二维码

import java.util.Objects;import javax.imageio.ImageIO;
import org.apache.commons.lang3.StringUtils;
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;/*** 画制定logo和制定描述的二维码依赖<dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.2.1</version></dependency>
<dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>3.2.1</version></dependency>*/public class QrCodeUtil {private static final int QRCOLOR = 0xFF000000; // 默认是黑色private static final int BGWHITE = 0xFFFFFFFF; // 背景颜色private static final int WIDTH = 400; // 二维码宽private static final int HEIGHT = 400; // 二维码高// 用于设置QR二维码参数private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {private static final long serialVersionUID = 1L;{put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别(H为最高级别)具体级别信息put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式put(EncodeHintType.MARGIN, 0);}};public static void main(String[] args) throws WriterException {File logoFile = new File("D://QrCode/logo3.png");File QrCodeFile = new File("D://QrCode/05.png");String url = "http://ganyintao.top/";String note = "在下老甘";drawLogoQRCode(logoFile, QrCodeFile, url, note);}// 生成带logo的二维码图片public static void drawLogoQRCode(File logoFile, File codeFile, String qrUrl, String note) {try {MultiFormatWriter multiFormatWriter = new MultiFormatWriter();// 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);// 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF)白(0xFF000000)两色for (int x = 0; x < WIDTH; x++) {for (int y = 0; y < HEIGHT; y++) {image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);}}int width = image.getWidth();int height = image.getHeight();if (Objects.nonNull(logoFile) && logoFile.exists()) {// 构建绘图对象Graphics2D g = image.createGraphics();// 读取Logo图片BufferedImage logo = ImageIO.read(logoFile);// 开始绘制logo图片g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);g.dispose();logo.flush();}// 自定义文本描述if (StringUtils.isNotEmpty(note)) {// 新的图片,把带logo的二维码下面加上文字BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);Graphics2D outg = outImage.createGraphics();// 画二维码到新的面板outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);// 画文字到新的面板outg.setColor(Color.BLACK);outg.setFont(new Font("楷体", Font.BOLD, 30)); // 字体、字型、字号int strWidth = outg.getFontMetrics().stringWidth(note);if (strWidth > 399) {// //长度过长就截取前面部分// 长度过长就换行String note1 = note.substring(0, note.length() / 2);String note2 = note.substring(note.length() / 2, note.length());int strWidth1 = outg.getFontMetrics().stringWidth(note1);int strWidth2 = outg.getFontMetrics().stringWidth(note2);outg.drawString(note1, 200 - strWidth1 / 2, height + (outImage.getHeight() - height) / 2 + 12);BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);Graphics2D outg2 = outImage2.createGraphics();outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);outg2.setColor(Color.BLACK);outg2.setFont(new Font("宋体", Font.BOLD, 30)); // 字体、字型、字号outg2.drawString(note2, 200 - strWidth2 / 2, outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);outg2.dispose();outImage2.flush();outImage = outImage2;} else {outg.drawString(note, 200 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12); // 画文字}outg.dispose();outImage.flush();image = outImage;}image.flush();ImageIO.write(image, "png", codeFile); // TODO} catch (Exception e) {e.printStackTrace();}}}

验证码

1.工具

public class ImageVerificationCode {private int weight = 100;           //验证码图片的长和宽private int height = 40;private String text;                //用来保存验证码的文本内容private Random r = new Random();    //获取随机数对象//private String[] fontNames = {"宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312"};   //字体数组//字体数组private String[] fontNames = {"Georgia"};//验证码数组private String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";/*** 获取随机的颜色** @return*/private Color randomColor() {int r = this.r.nextInt(225);  //这里为什么是225,因为当r,g,b都为255时,即为白色,为了好辨认,需要颜色深一点。int g = this.r.nextInt(225);int b = this.r.nextInt(225);return new Color(r, g, b);            //返回一个随机颜色}/*** 获取随机字体** @return*/private Font randomFont() {int index = r.nextInt(fontNames.length);  //获取随机的字体String fontName = fontNames[index];int style = r.nextInt(4);         //随机获取字体的样式,0是无样式,1是加粗,2是斜体,3是加粗加斜体int size = r.nextInt(10) + 24;    //随机获取字体的大小return new Font(fontName, style, size);   //返回一个随机的字体}/*** 获取随机字符** @return*/private char randomChar() {int index = r.nextInt(codes.length());return codes.charAt(index);}/*** 画干扰线,验证码干扰线用来防止计算机解析图片** @param image*/private void drawLine(BufferedImage image) {int num = r.nextInt(10); //定义干扰线的数量Graphics2D g = (Graphics2D) image.getGraphics();for (int i = 0; i < num; i++) {int x1 = r.nextInt(weight);int y1 = r.nextInt(height);int x2 = r.nextInt(weight);int y2 = r.nextInt(height);g.setColor(randomColor());g.drawLine(x1, y1, x2, y2);}}/*** 创建图片的方法** @return*/private BufferedImage createImage() {//创建图片缓冲区BufferedImage image = new BufferedImage(weight, height, BufferedImage.TYPE_INT_RGB);//获取画笔Graphics2D g = (Graphics2D) image.getGraphics();//设置背景色随机g.setColor(Color.white);g.fillRect(0, 0, weight, height);//返回一个图片return image;}/*** 获取验证码图片的方法** @return*/public BufferedImage getImage() {BufferedImage image = createImage();Graphics2D g = (Graphics2D) image.getGraphics(); //获取画笔StringBuilder sb = new StringBuilder();for (int i = 0; i < 4; i++)             //画四个字符即可{String s = randomChar() + "";      //随机生成字符,因为只有画字符串的方法,没有画字符的方法,所以需要将字符变成字符串再画sb.append(s);                      //添加到StringBuilder里面float x = i * 1.0F * weight / 4;   //定义字符的x坐标g.setFont(randomFont());           //设置字体,随机g.setColor(randomColor());         //设置颜色,随机g.drawString(s, x, height - 5);}this.text = sb.toString();drawLine(image);return image;}/*** 获取验证码文本的方法** @return*/public String getText() {return text;}public static void output(BufferedImage image, OutputStream out) throws IOException                  //将验证码图片写出的方法{ImageIO.write(image, "JPEG", out);}
}

2、controller接口

    @GetMapping("/getCode")public ResResult<Map<String,String>> getCode(HttpServletRequest request) throws IOException {/*1.生成验证码2.把验证码上的文本存在session中3.把验证码图片发送给客户端*/ImageVerificationCode ivc = new ImageVerificationCode();     //用我们的验证码类,生成验证码类对象BufferedImage image = ivc.getImage();  //获取验证码request.getSession().setAttribute("text", ivc.getText());ByteArrayOutputStream stream = new ByteArrayOutputStream();ImageIO.write(image, "png", stream);String base64 = Base64.encode(stream.toByteArray());//将验证码的文本存在session中Map<String,String> map = new HashMap<>();map.put("sessionId",request.getSession().getId());map.put("text",base64);redisUtils.set(request.getSession().getId(),ivc.getText(),60);return new ResResult<>(map);//将验证码图片响应给客户端}

JAVA使用barcode4j生成条形码和二维码图片以及带logo的二维码,验证码图片相关推荐

  1. python二维码加动态图_用python自制个性二维码(设置带LOGO的二维码带动图)

    本文使用的是 python3.6 MyQR库 tkinter库 我们可以使用MyQR这个库 安装方式如下: 进入命令行输入: pip3 install MyQR 如果安装不成功多半是网络有问题,可以去 ...

  2. C#利用ZXing.Net生成条形码,二维码和带Logo的二维码

    本文是利用ZXing.Net在WinForm中生成条形码,二维码的小例子,仅供学习分享使用,如有不足之处,还请指正. 什么是ZXing.Net? ZXing是一个开放源码的,用Java实现的多种格式的 ...

  3. java使用zxing生成二维码,可带logo和底部文字

    java使用zxing生成二维码,可带logo和底部文字 springboot中整合zxing生成二维码 一.导入依赖 <properties><zxing.version>3 ...

  4. Java的方式生成条形码

    用Java的方式生成条形码可以有两种方式: 1.用servlet的方式来生成 2.纯Java的方式来生成 第一种: 代码如下: protected void doPost(HttpServletReq ...

  5. zxing生成带logo的二维码

    倒Zxing依赖 implementation 'cn.bingoogolapple:bga-qrcode-zxing:1.2.1' 代码段 import android.graphics.Bitma ...

  6. zxing 生成二维码,可设置logo、二维码颜色、白边大小

    主要是使用google的zxing 生成二维码,可设置logo.二维码前景色/后景色.白边大小.二维码大小 1.用到jar包 <dependency><groupId>com. ...

  7. Android Studio 生成二维码、生成带logo的二维码

    1.生成二维码: 2.生成logo的二维码: 一.引入依赖 首先在libs文件目录下放进jar包zxing.jar,要下载zxing.jar就点击链接:下载zxing.jar(记得点击"Cd ...

  8. 使用zxing生成带logo的二维码图片,自动调节logo图片相对二维码图片的大小

    使用zxing生成带logo的二维码图片,自动调节logo图片相对二维码图片的大小  * 可选是否带logo,可选是否保存二维码图片:结果返回base64编码的图片数据字符串  * 页面显示:< ...

  9. .NET ZXING 生成带logo的二维码和普通二维码及条型码

    工作中使用到了,就随笔记下了.希望可以帮助有需要的同学们. /// <summary>         /// 生成二维码         /// </summary>     ...

最新文章

  1. 如何用python创建一个下载网站-详解如何用python实现一个简单下载器的服务端和客户端...
  2. 从入门到实践,快速掌握 Nginx 研发
  3. Android应用开发—浅谈MVX模式
  4. Spring Boot中使用模板引擎参数化传参数
  5. ROS学习笔记一:安装配置ROS环境
  6. 如何让IOS应用从容地崩溃
  7. iOS 开发之动画篇 - 从 UIView 动画说起
  8. android无线充电技术,无线充电Qi通信协议分析,充电qi通信协议
  9. 深度学习中的常用的归一化方法汇总
  10. 小白鼠测试---VR头戴设备-暴风魔镜4
  11. Va02 修改数量和价格条件时报错
  12. 复杂性应业务抽象本质——系统化多维度思考(如何让抽象更上一层楼)
  13. 微信小程序开发视频加载:[渲染层网络层错误] Failed to load media
  14. PhpStorm 远程连接服务器
  15. BIM模型文件下载——8层综合办公楼BIM项目Revit模型(建筑、结构、暖通、电气、给排水、MEP)
  16. 计算机资源管理器出问题怎么办,W7系统资源管理器已停止工作怎么办
  17. js 数组对象sort()排序(升序降序)
  18. 色情版“微信”背后的秘密,太可怕了~
  19. [王家卫经典武侠动作][东邪西毒:终极版][BluRay-RMVB][国粤双语]
  20. C/C++ 的rationale

热门文章

  1. COF多孔复合材料3D-KSC-COFs/ZnO-CdS-Co-Fe2O4/COF-PS-GMA/MW-CNTs-TpPa-COF
  2. 回文串问题的克星——Palindrome Tree(回文树)/Palindrome Automaton(回文自动机)学习小记
  3. windows10图片打开找不到内置图片查看器
  4. 【NILM】非入侵式负荷分解模块nilmtk安装教程
  5. 简析银行核心系统24小时设计
  6. 希尔排序(实现+总结)
  7. IC工程师入门必学《Verilog超详细教程》(附下载)
  8. 在Xml中加注释的方法
  9. 惯性导航的定位原理是什么?
  10. warning C4996(转)