QRGen+thumbnailator生成包含logo 的 二维码
原理很简单:QRGen 生成二维码,同时结合thumbnailator的 水印模式将图片放中心,这样一个支持logo 的二维码就可以了
参考代码
- pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dalong</groupId>
<artifactId>imageapp</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.github.kenglxn.qrgen</groupId>
<artifactId>javase</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
</dependencies>
</project>
- 核心代码
package com.dalong;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import net.glxn.qrgen.core.image.ImageType;
import net.glxn.qrgen.javase.QRCode;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
public class Application {
public static void main(String[] args) throws IOException {
File file = QRCode.from("https://www.cnblogs.com/rongfengliang/p/13822698.html").withColor(0x171616, 0xFFFFFFAA).to(ImageType.PNG).withSize(350, 350).file();
Thumbnails.of(file)
.size(350, 350)
.watermark(Positions.CENTER, ImageIO.read(new File("src/main/resources/yyy_meitu_2.png")), 0.7f)
.toFile(new File("appdemo.jpg"));
}
}
- 效果
- web 集成说明
很简单,主要是转为base64编码,方便传输
package com.dalong;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import net.glxn.qrgen.core.image.ImageType;
import net.glxn.qrgen.javase.QRCode;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.io.*;
public class Application {
public static void main(String[] args) throws IOException {
ByteOutputStream outputStream = new ByteOutputStream();
File file = QRCode.from("https://www.cnblogs.com/rongfengliang/p/13822698.html").withColor(0x171616, 0xFFFFFFAA).to(ImageType.PNG).withSize(350, 350).file();
Thumbnails.of(file)
.size(350, 350)
.watermark(Positions.CENTER, ImageIO.read(new File("src/main/resources/yyy_meitu_2.png")), 1f)
.toOutputStream(outputStream);
String qrCodeBase64 = new BASE64Encoder().encode(outputStream.getBytes());
System.out.println(qrCodeBase64);
}
}
说明
以上生成的二维码还是偏简单的,实际需要自己调整下 ,同时注意实际我们需要进行下颜色搭配,包含了logo的颜色以及二维码的背景以及前景
颜色
参考资料
https://github.com/kenglxn/QRGen
https://github.com/coobird/thumbnailator