首先需哟引入一个工具类,有需要的同学可以自行的保存

package com.example.demo.util;import java.awt.BasicStroke;
import java.awt.Color;
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.FileInputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;import javax.imageio.ImageIO;import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;/***
* @ClassName: QRcodeUtil
* @Description: 二维码生成工具类   基于QRcode和ZXing类
* @author hehh
* @date 2018年1月9日 下午1:20:03
**/
public class QRcodeUtil {  // 默认宽为300  private Integer width = 300;  // 默认高为300  private Integer height = 300;  // 默认二维码图片格式  private String imageFormat = "png";  // 默认二维码字符编码  private String charType = "utf-8";  // 默认二维码的容错级别  private ErrorCorrectionLevel corretionLevel = ErrorCorrectionLevel.H;  // 二维码与图片的边缘  private Integer margin = 1;  // 二维码参数  private Map<EncodeHintType, Object> encodeHits = new HashMap<>();  private  Integer LOG_HEIGHT;private  Integer LOG_WIDTH;/*** * @Title:  * @Description: 创建 QRcodeUtil的带参构造方法* @param @param width :宽度* @param @param height :高度* @param @param imageFormat :图片格式:如:png* @param @param charType :编码类型如:UTF-8* @param @param corretionLevel :修正比 水平??* @param @param margin  :边缘* @throws*/public QRcodeUtil(Integer width, Integer height, String imageFormat, String charType,  ErrorCorrectionLevel corretionLevel, Integer margin,Integer LOG_HEIGHT,Integer LOG_WIDTH) {  if (width != null) {  this.width = width;  }  if (height != null) {  this.height = height;  }  if (imageFormat != null) {  this.imageFormat = imageFormat;  }  if (charType != null) {  this.charType = charType;  }  if (corretionLevel != null) {  this.corretionLevel = corretionLevel;  }  if (margin != null) {  this.margin = margin;  } if(LOG_HEIGHT != null){this.LOG_HEIGHT = LOG_HEIGHT;}if(LOG_WIDTH != null){this.LOG_WIDTH = LOG_WIDTH;}}  //    @SuppressWarnings("unchecked")
//  public  BufferedImage craderLogQR(String contents,String format) throws Exception{
//      @SuppressWarnings("rawtypes")
//      HashMap hashMap = new HashMap();
//      hashMap.put(EncodeHintType.CHARACTER_SET, "utf-8");
//      hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
//      hashMap.put(EncodeHintType.MARGIN, 2);
//      BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height,hashMap);
//
//      Path file = new File("D:/1.png").toPath(); //已存在的一张二维码图片
//      MatrixToImageWriter.writeToPath(bitMatrix, format, file); //读取二维码图片
//      BufferedImage twodimensioncode = ImageIO.read(new File(file.toString())); //获取画笔
//      Graphics2D g = twodimensioncode.createGraphics(); //读取logo图片
//      BufferedImage logo = ImageIO.read(new File("D:/12.jpg")); //加入的log图片
//      //设置二维码大小,太大,会覆盖二维码,此处20%
//      int logoWidth = logo.getWidth() > twodimensioncode.getWidth()*2 /10 ? (twodimensioncode.getWidth()*2 /10) : logo.getWidth(); int logoHeight = logo.getHeight() > twodimensioncode.getHeight()*2 /10 ? (twodimensioncode.getHeight()*2 /10) : logo.getHeight();
//      //设置logo图片放置位置
//      //中心
//      int x = (twodimensioncode.getWidth() - logoWidth) / 2; int y = (twodimensioncode.getHeight() - logoHeight) / 2; //开始合并绘制图片
//      g.drawImage(logo, x, y, logoWidth, logoHeight, null); g.drawRoundRect(x, y, logoWidth, logoHeight, 15 ,15); //logo边框大小
//      g.setStroke(new BasicStroke(2)); //logo边框颜色
//      g.setColor(Color.WHITE); g.drawRect(x, y, logoWidth, logoHeight);
//      g.dispose(); logo.flush();
//      twodimensioncode.flush();
//      ImageIO.write(twodimensioncode, format, new File("D:/img2.png"));
//      return logo;
//
//    }public QRcodeUtil(Integer width, Integer height, String imageFormat, String charType,  ErrorCorrectionLevel corretionLevel) {  this(width, height, imageFormat, charType, corretionLevel, null,null, null);  }  public QRcodeUtil(Integer width, Integer height, String imageFormat, String charType, Integer margin) {  this(width, height, imageFormat, charType, null, margin,null, null);  }  public QRcodeUtil(Integer width, Integer height, String imageFormat, String charType) {  this(width, height, imageFormat, charType, null, null,null, null);  }  public QRcodeUtil(Integer width, Integer height, String imageFormat) {  this(width, height, imageFormat, null, null, null,null, null);  }  public QRcodeUtil(Integer width, Integer height) {  this(width, height, null, null, null, null,null, null);  }  public QRcodeUtil() {  }  // 初始化二维码的参数  private void initialParamers() {  // 字符编码  encodeHits.put(EncodeHintType.CHARACTER_SET, this.charType);  // 容错等级 L、M、Q、H 其中 L 为最低, H 为最高  encodeHits.put(EncodeHintType.ERROR_CORRECTION, this.corretionLevel);  // 二维码与图片边距  encodeHits.put(EncodeHintType.MARGIN, margin);  }  /***  * @Title: getBufferedImage * @Description: 创建图片二维码,并 返回图片流对象 * @param @param content :二维码的内容* @param @return    设定文件 * @return BufferedImage    返回类型 :图片缓冲流* @throws*/public BufferedImage getBufferedImage(String content) {  initialParamers();  BufferedImage bufferedImage = null;  try {  BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, this.width,  this.height, this.encodeHits);  bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);  } catch (WriterException e) {  e.printStackTrace();  return null;  }  return bufferedImage;  }  // 将二维码保存到输出流中  public void writeToStream(String content, OutputStream os) {  initialParamers();  try {  BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, this.width, this.height,  this.encodeHits);  MatrixToImageWriter.writeToStream(matrix, this.imageFormat, os);  } catch (Exception e) {  e.printStackTrace();  }  }  /***  * @Title: createQrImage * @Description: 创建一个二维码 发送到指定路径* @param @param content :二维码内容* @param @param path :路径* @return void    返回类型 * @throws*/public void createQrImage(String content, String path) {  initialParamers();  try {  BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, this.width, this.height,this.encodeHits);  MatrixToImageWriter.writeToPath(matrix, this.imageFormat, new File(path).toPath());  } catch (Exception e) {  e.printStackTrace();  }  }  /***   * @Title: decodeQrImage * @Description: 解析二维码的内容* @param @param file :二维码图片* @return String    返回类型 * @throws*/public String decodeQrImage(File file){  String content=null;  try {  BufferedImage bufferedImage=ImageIO.read(new FileInputStream(file));  LuminanceSource source=new BufferedImageLuminanceSource(bufferedImage);  Binarizer binarizer=new HybridBinarizer(source);  BinaryBitmap image=new BinaryBitmap(binarizer);  Map<DecodeHintType,Object> decodeHits=new HashMap<>();  decodeHits.put(DecodeHintType.CHARACTER_SET, this.charType);  Result result=new MultiFormatReader().decode(image, decodeHits);  content=result.getText();  }catch (Exception e) {  e.printStackTrace();  }  return content;  }  /** * 生成二维码 * @param content   源内容 * @param imgPath   生成二维码保存的路径 * @param needCompress  是否要压缩 * @return      返回二维码图片 * @throws Exception */  @SuppressWarnings("unchecked")private  BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {  @SuppressWarnings("rawtypes")Hashtable hints = new Hashtable();  hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);  hints.put(EncodeHintType.CHARACTER_SET, charType);  hints.put(EncodeHintType.MARGIN, 1);  BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, height, 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);  }  }  if (imgPath == null || "".equals(imgPath)) {  return image;  }  // 插入图片  this.insertImage(image, imgPath, needCompress);  return image;  }  /** * 在生成的二维码中插入图片 * @param source :二维码 图片流* @param imgPath :log图片的地址* @param needCompress * @throws Exception */  private void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {  File file = new File(imgPath);  if (!file.exists()) {  System.err.println("" + imgPath + "   该文件不存在!");  return;  }  // 读取log图片Image src = ImageIO.read(new File(imgPath));  int width = src.getWidth(null);  int height = src.getHeight(null); // 设置高度if (needCompress) { // 压缩LOGO  if (width > LOG_WIDTH) {  width = LOG_WIDTH;  }  if (height > LOG_HEIGHT) {  height = LOG_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();  // 创建 log坐标int x = (this.height - width) / 2;  int y = (this.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();  }  /** * 生成带logo二维码,并保存到磁盘 * @param content :二维码内容* @param imgPath   logo图片 地址* @param destPath  :要保存的位置* @param needCompress :是否需要压缩* @throws Exception */  public  BufferedImage encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {  BufferedImage image = this.createImage(content, imgPath, needCompress);  mkdirs(destPath);  //String file = new Random().nextInt(99999999) + ".png";//生成随机文件名  //ImageIO.write(image, imageFormat, new File(destPath + "/" + file));return image;}  public static void mkdirs(String destPath) {  File file = new File(destPath);  // 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir。(mkdir如果父目录不存在则会抛出异常)  if (!file.exists() && !file.isDirectory()) {  file.mkdirs();  }  }  public Integer getWidth() {  return width;  }  public void setWidth(Integer width) {  this.width = width;  }  public Integer getHeight() {  return height;  }  public void setHeight(Integer height) {  this.height = height;  }  public String getImageFormat() {  return imageFormat;  }  public void setImageFormat(String imageFormat) {  this.imageFormat = imageFormat;  }  public String getCharType() {  return charType;  }  public void setCharType(String charType) {  this.charType = charType;  }  public ErrorCorrectionLevel getCorretionLevel() {  return corretionLevel;  }  public void setCorretionLevel(ErrorCorrectionLevel corretionLevel) {  this.corretionLevel = corretionLevel;  }  public Integer getMargin() {  return margin;  }  public void setMargin(Integer margin) {  this.margin = margin;  }  public Map<EncodeHintType, Object> getHits() {  return encodeHits;  }  public void setHits(Map<EncodeHintType, Object> hits) {  this.encodeHits = hits;  }  } 

编写一个controller层

@RestController
public class QRcodeController {@RequestMapping("/api/qrcode")public void QrCode(HttpServletResponse response){QRcodeUtil qrCode = new QRcodeUtil(300, 400, "JPG");//设置二维码的边缘为1  qrCode.setMargin(1);BufferedImage qrCodeImage = qrCode.getBufferedImage("http://www.baidu.com");//这里进行写死response.setContentType("image/PNG");//response.setHeader("Content-Disposition", "attachment; filename=1.png");// 通过ImageIO 响应数据try {// 这里通过imageIo进行相应浏览器ImageIO.write(qrCodeImage,"PNG",response.getOutputStream());} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}

}

如何生成一个二维码?相关推荐

  1. 一张照片,如何生成一个二维码?

    冬天落在恭王府的第一场大雪.春天聚在河边觅食的麻雀.盛夏午后从冰箱里拿出来的大西瓜.深秋爬满南墙的红叶--每一份惊喜和快乐,都值得分享给更多的朋友. 今天我们要介绍的是,如何将一张照片,做成一个二维码 ...

  2. 如何将一个PPT生成一个二维码?扫码就能查看文件内容

    制作文件二维码很简单! PDF文件.PPT文件.图片文件.音频文件.视频文件.Excel文件.Word等,都可以一键上传,然后生成一个可自定义设计.并支持追踪扫描数据的动态二维码. 什么是动态二维码呢 ...

  3. 怎么将图文、视频生成一个二维码?多内容在线生成二维码的方法

    现在很多幼儿园在招生.宣传时经常会使用二维码的方式来让家长快速了解幼儿园的信息,那么大多采用的方式也是通过文字.图片.视频等类型的内容来做宣传推广,那么如何将这些类型的内容同时放到一个二维码中呢?怎么 ...

  4. python学习之生成一个二维码(一)

    首先,简单介绍一下二维码:二维码又称二维条码,常见的二维码为QR Code,QR全称Quick Response,是一个近几年来移动设备上超流行的一种编码方式,它比传统的Bar Code条形码能存更多 ...

  5. Python 生成一个二维码

    python是所有编程语言中模块最丰富的 生活中常见的二维码功能在使用python第三方库来生成十分容易 一.只需要安装引用qrcode包即可 当然,我们需要先安装几个依赖包: sudo pip in ...

  6. HTML生成一个二维码,微信扫一扫,可以对网页分享

    在网上找了大量的例子,及微信接口文档,分享功能均是Android 和IOS的,分享功能都是提供的一套自己的分享,那么网页版我看了很多,没有找到适用的,但是皇天不负有心人,终于找到了一个可以完成这样的功 ...

  7. 二维码原理解析,生成一个二维码需要这些知识

    /   今日科技快讯   / 近日,在英伟达取消以400亿美元收购英国芯片设计公司ARM的计划后,ARM宣布将在全球范围内裁员,大约涉及1000名员工.ARM在声明中表示:"与其他公司一样, ...

  8. python生成动态二维码实例_python生成动态个性二维码(示例代码)

    1 安装工具 2 生成普通二维码 3 带图片的二维码 4 动态 GIF 二维码 5 在Python程序中使用 一.安装 首先在python环境下运行, 打开cmd进入python27 进入script ...

  9. vue生成app二维码,并扫码下载app

    文章目录 项目需求 开发 web官网下载页的开发 web官网地址生成下载二维码 项目需求 公司要做一个web官网的下载页面,功能是微信扫码可以直接下载Ios手机端app.Android手机端app.及 ...

最新文章

  1. 3des java 库_java 3DES 加密
  2. android git提交整个项目_使用git管理嵌入式软件版本
  3. LEACH分簇算法实现和能量控制算法实现
  4. pandas 如何删掉第一行_Python:Pandas – 按组删除第一行
  5. 优雅的使用 PhpStorm 来开发 Laravel 项目
  6. centos5.4 64位下安装mysql5.5.14
  7. 【C语言简单说】十七:数组
  8. Visual Studio的Web Performance Test提取规则详解(1)
  9. 八、计数排序及其应用分析
  10. 当我们群嘲假博士时,不要忘了真博士们的艰辛
  11. cisc 和 risc_RISC和CISC | 电脑组织
  12. 四元数插值方法Slerp/Squad/Spicv/Sping知识总结思维导图
  13. 离开张小龙后,她要做一款与微信互补的社交产品
  14. 如何使用Super Vectorizer在 Mac 上将 PDF 转换为 SVG 矢量?
  15. LINUX下载并编译javasqlite
  16. php oracle 存储过程,用PHP调用Oracle存储过程
  17. 移动iptv安装三方软件
  18. 单元测试 测试用例 用例测试文件golang的单元测试
  19. mysql 8 my.ini skip_mysql8.0版本skip-grant-tables出现的新问题
  20. 解决 XCUITest iproxy exited with code 208

热门文章

  1. 使用ChannelSftp的put方法被挂起,卡住的问题
  2. jQuery 从零开始学习 (二) 选择器
  3. C# 关键字 使用where来限定泛型约束
  4. 什 么 是 可 重 入 性 , 为 什 么 说 Synchronized 是 可 重 入 锁 ?
  5. Ubuntu 16.04 下 旋转显示器屏幕 竖屏显示
  6. 集束搜索(Beam Search)
  7. 白话微服务60秒:从快餐店点餐看事件驱动架构
  8. C语言基础-判断质数(素数)
  9. c++ 0x8000ffff灾难性故障_硬盘出了故障就换?教你一招,不花一分钱就能修复!...
  10. 非功能性需求之性能需求分析