pom支持:
<!-- 二维码支持包 start-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.2.0</version>
</dependency> <dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.2.0</version>
</dependency>
<!-- 二维码支持包 end--> 工具类支持:
package com.example.demo.dao.qrcode; 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.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable; /**
* @author jin.tang
* @Title: springbootdemo
* @Package com.example.demo.dao.qrcode
* @Description: java web二维码生成器
* @date 2017/12/25
*/
@Slf4j
public class QRCodeUtil { /**
* 方式一:流的方式直接生成web版本二维码
* 默认的二维码外观(可设置高宽)
* @param url 要生成二维码的路径
* @param response response对象
* @param width 二维码宽度
* @param height 二维码高度
* @throws IOException
*/
public static void getTwoDimension(String url, HttpServletResponse response, int width, int height) throws IOException {
if (url != null && !"".equals(url)) {
ServletOutputStream stream = null;
try {
stream = response.getOutputStream();
QRCodeWriter writer = new QRCodeWriter();
BitMatrix m = writer.encode(url, BarcodeFormat.QR_CODE, height, width);
MatrixToImageWriter.writeToStream(m, "png", stream);
} catch (WriterException e) {
e.printStackTrace();
log.error("生成二维码失败!");
} finally {
if (stream != null) {
stream.flush();
stream.close();
}
}
}
} /**
* 方式二:返回ResponseEntity的方式显示二维码
* 可设置二维码外观颜色,logo图片
* @param url 二维码对于URL
* @param width 二维码宽
* @param height 二维码高
* @param format 二维码格式
* @param logPath logo图片路径
* @param needLogo 二维码是否需要生成logo
* @return
* @throws WriterException
* @throws IOException
*/
// 直接在页面显示
public static ResponseEntity<byte[]> getResponseEntity(String url, String logPath, boolean needLogo,String format,int width,int height)throws Exception {
BufferedImage image = QRCodeUtil.createImage(url, logPath,needLogo,width,height); ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(image, format, out);//将BufferedImage转成out输出流
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(out.toByteArray(),
headers, HttpStatus.CREATED);
} /**
* 方式三:以流的形式直接显示二维码
* 可设置二维码外观颜色,logo图片
*/
public static void showQrcode(String url, String logPath,HttpServletResponse response, boolean needLog,String format,int width,int height)throws Exception {
BufferedImage image = QRCodeUtil.createImage(url, logPath,needLog,width,height);
boolean bl = ImageIO.write(image, format, response.getOutputStream());
System.out.println(" boolean is " + bl);
} /** 方式四:生成二维码文件存储
* 可设置二维码外观颜色,logo图片
* @param logPath
* @param destPath 存储路径
* @param fileName 存储文件名称(不需要后缀)
* @param needLog
* @param format
* @param width
* @param height
* @return
* @throws Exception
*/
public static boolean SaveQrCode(String url, String logPath,
boolean needLog,String format,int width,int height,String destPath, String fileName) throws Exception { boolean flag = false;
BufferedImage image;
try {
image = QRCodeUtil.createImage(url, logPath,needLog,width,height);
File file = new File(destPath);
// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
String fileUrl = fileName + "."+format;
ImageIO.write(image, format, new File(destPath + "/" + fileUrl));
flag = true;
} catch (Exception e) {
e.printStackTrace();
} return flag;
} /**
* 生成二维码图片私有方法
*/
private static BufferedImage createImage (String url, String imgPath,boolean needCompress,
int width, int height) throws Exception {
Hashtable hints = new Hashtable(); // 二维码纠错级别:由高到低 H、Q、M、L
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 二维码边界空白大小由大到小 4、3、2、1(默认为4)
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(url,
BarcodeFormat.QR_CODE, width, height, hints); int H = bitMatrix.getHeight();
int W = bitMatrix.getWidth();
int L = getFinderPatternWidth(bitMatrix) + 3;
int[] pixels = new int[W * H];
// 二维码角颜色,依次为左上、左下、右上
Color redColor = new Color(182, 0, 5);
int redColorInt = redColor.getRGB();
Color greenColor = new Color(0, 124, 54);
int greenColorInt = greenColor.getRGB();
Color blueColor = new Color(0, 64, 152);
int blueColorInt = blueColor.getRGB();
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
// 颜色渐变程度,RGB(158,255,158)
int num1 = (int) (158 - (158.0 - 30.0) / bitMatrix.getHeight()
* (y + 1));
int num2 = (int) (255 - (255.0 - 80.0) / bitMatrix.getHeight()
* (y + 1));
int num3 = (int) (158 - (158.0 - 130.0) / bitMatrix.getHeight()
* (y + 1));
Color color = new Color(num1, num2, num3);
int colorInt = color.getRGB();
// 此处可以修改二维码的颜色,可以分别制定二维码和背景的颜色;
pixels[y * W + x] = bitMatrix.get(x, y) ? colorInt : 0xffffff;
}
} BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB); image.getRaster().setDataElements(0, 0, W, H, pixels);
if (imgPath == null || "".equals(imgPath)) {
return image;
}
// 插入图片
QRCodeUtil.insertImage(image, imgPath, needCompress,width,height);
return image; } private static int getFinderPatternWidth(BitMatrix matrix) {
int W = matrix.getWidth();
int H = matrix.getHeight();
int length = 0;
boolean flag = false;
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
if (matrix.get(x, y) == true) {
flag = true;
length++;
} else {
if (flag != false) {
return x;
}
}
}
}
return length;
}
/**
* 在二维码中插入图片
*/
private static void insertImage(BufferedImage source, String imgPath,
boolean needCompress,int wid,int hei) 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 > wid) {
width = wid;
}
if (height > hei) {
height = hei;
}
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 = (wid - width) / 2;
int y = (hei - height) / 2;
/*
* int x = QRCODE_SIZE - width - 20; int y = QRCODE_SIZE - height - 20;
*/ graph.drawImage(src, x, y, width, height, null); // logo边框
/*
* Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
* graph.setStroke(new BasicStroke(3f)); graph.draw(shape);
*/ graph.dispose();
} controller中调用: package com.example.demo.controller; import com.example.demo.dao.qrcode.QRCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; /**
* @author jin.tang
* @Title: springbootdemo
* @Package com.example.demo.controller
* @Description: ${todo}
* @date 2017/12/25
*/
@Slf4j
@Controller
public class QRCodeController {
/**
* 获得二维码
* @param request
* @param response
*/
@RequestMapping(value = "phoneversion/getTwoDimension",method={RequestMethod.POST,RequestMethod.GET})
public void getTwoDimensionForIOSs(HttpServletRequest request, HttpServletResponse response){
try {
QRCodeUtil.getTwoDimension("https://bbs.hupu.com/bxj", response, 300, 300);
} catch (IOException e) {
e.printStackTrace();
} } @RequestMapping("/downloadIOSAPPQRCode")
public ResponseEntity<byte[]> downloadIOSAPPController(/*@RequestParam(required = true)String type*/)
throws Exception{
// InputStream is = this.getClass().getClassLoader().getResourceAsStream("app.properties");
// Properties props = new Properties();
// props.load(is);
// String appId = (String)props.get(type);
// String url = "" + appId;
return QRCodeUtil.getResponseEntity("https://www.zhibo8.cc", "F:\\logo.png",true,"png", 300, 300);
} @RequestMapping("/showQrcode")
public void showQrcode(HttpServletRequest request, HttpServletResponse response)
throws Exception{
QRCodeUtil.showQrcode("https://www.zhibo8.cc", "",response,false,"png", 300, 300);
} @RequestMapping("/SaveQrCode")
public void SaveQrCode(HttpServletRequest request, HttpServletResponse response)
throws Exception{
boolean flag=QRCodeUtil.SaveQrCode("https://www.zhibo8.cc", "",false,"png", 300, 300,"D:\\","qrcode");
log.info("flag=="+flag);
}
}
前端显示: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>首页</title>
</head>
<body>
<p>二维码图片1:</p>
<div><img src="/phoneversion/getTwoDimension" alt="" /></div> <p>二维码图片2:</p>
<img src="/downloadIOSAPPQRCode"/><a href="/downloadIOSAPPQRCode">下载</a> <p>二维码图片3:</p>
<img src="/showQrcode"/><a href="/showQrcode">下载</a>
</body>
</html>}

java web 二维码生成的更多相关文章

  1. java实现二维码生成的几个方法

    1: 使用SwetakeQRCode在Java项目中生成二维码 http://swetake.com/qr/ 下载地址 或着http://sourceforge.jp/projects/qrcode/ ...

  2. Java实现二维码生成的方法

    1.支持QRcode.ZXing 二维码生成.解析: package com.thinkgem.jeesite.test; import com.google.zxing.BarcodeFormat; ...

  3. JAVA实现二维码生成加背景图

    pom.xml依赖 <!-- 二维码生成 -->         <!-- https://mvnrepository.com/artifact/com.google.zxing/c ...

  4. Java条形码/二维码生成和解析

    注意-本类依赖jar包文件:core.jar和zxing-javase.jar 下载jar文件,到本博客文件栏目下载. import com.google.zxing.BarcodeFormat; i ...

  5. Java 条形码 二维码 的生成与解析

    Barcode简介 Barcode是由一组按一定编码规则排列的条,空符号,用以表示一定的字符,数字及符号组成的,一种机器可读的数据表示方式. Barcode的形式多种多样,按照它们的外观分类: Lin ...

  6. 聊聊 Web 项目二维码生成的最佳姿势

    在设计和实现的过程之后,你永远不知道部署上去的程序会已什么样的姿势运行. 本篇借一次生成二维码逻辑的不同实现,阐述 Web 项目中二维码生成的正确姿势. 文中如有批量,欢迎各位看客老爷拍砖.试运行前5 ...

  7. simple go web application & 二维码生成 & 打包部署

    go语言简易web应用 & 二维码生成及解码 & 打包部署 转载请注明出处: https://www.cnblogs.com/funnyzpc/p/10801476.html 前言(闲 ...

  8. java 二维码生成(可带图片)springboot版

    本文(2019年6月29日 飞快的蜗牛博客) 有时候,男人和女人是两个完全不同的世界,男人的玩笑和女人的玩笑也完全是两码事,爱的人完全不了解你,你也不要指望一个女人了解你,所以男的不是要求别人怎么样, ...

  9. atitit.二维码生成总结java zxing

    atitit.二维码生成总结java zxing #-----zxing类库.. but zxing3.0  的类库core-3.0.jar 需要jdk7 只好zing2.2.jar ..jdk6走o ...

随机推荐

  1. js 获取地址栏信息,可以传递多个参数

    //获取多个地址栏信息,name为地址栏参数名,可以传递多个参数 // 形式为 .html?id=12&a=2 function getQueryString(name){ var reg = ...

  2. Taro 遇到的坑

    1.createSelectorQuery无法获取节点宽高 业务场景: 列表需要在最后一页底部显示 ‘我是有底线的~’ 提示,但是如果数据只有一页且不占满屏幕的话,就不显示.需要判断 ‘我是有底线的~ ...

  3. 【知识库】-数据库_MySQL常用SQL语句语法大全示例

    简书作者:seay 文章出处: 关系数据库常用SQL语句语法大全 Learn [已经过测试校验] 一.创建数据库 二.创建表 三.删除表 四.清空表 五.修改表 六.SQL查询语句 七.SQL插入语句 ...

  4. C++入门经典-例7.5-对象的指针,函数指针调用类成员

    1:指向相应对象的指针就是对象的指针,它的生明方法与其他类型一样,如下: 类名 *p; 类的指针可以调用它所指向对象的成员.形式如下: p->类成员; 2:代码如下: (1)cat.h #inc ...

  5. 在.slurm文件中激活Anaconda环境

    超算中心使用slurm作为集群调度.原始slurm脚本如下: source activate tensorflow-gpu python neural_style.py --content conte ...

  6. VLC-Qt 入门指南

      关于 VLC-Qt VLC-Qt:一个结合了 Qt 应用程序和 libVLC 的免费开源库.它包含了用于媒体播放的核心类,以及用于更快速地进行媒体播放器开发的一些 GUI 类. 官网地址:http ...

  7. yarn application命令介绍

    yarn application 1.-list     列出所有 application 信息    示例:yarn  application -list 2.-appStates <Stat ...

  8. LC 609. Find Duplicate File in System

    Given a list of directory info including directory path, and all the files with contents in this dir ...

  9. 跨平台python异步回调机制实现和使用方法

    跨平台python异步回调机制实现和使用方法 这篇文章主要介绍了python异步回调机制的实现方法,提供了使用方法代码 1 将下面代码拷贝到一个文件,命名为asyncore.py 代码如下: impo ...

  10. 使用Keepalived实现Nginx高可用

    Keepalived是一个路由软件,可以提供linux系统和linux系统上的组件的负载均衡和高可用,高可用基于VRRP(Virtual Router Redundancy Protocol,虚ip) ...