1:首先感謝這篇文章真正的博客:https://w.cnblogs.com/Reborn-yuan/p/10409693.htmlhtml
以下代碼都是根據這篇文章改進了一些地方java
2:首先仍是導入jar包spring
<!--普通二維碼生成jar包-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
3:配置寫入器以及測試主方法(默認生成地址不在C盤,這裏的緣由是個人電腦,系統是家庭版C盤否則輕易訪問因此改爲了E)api
package com.ff.demo; 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 org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.util.StringUtils; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class GenerateQRcode { /** *生成二維碼主方法入口 * @param qrdata 二維碼的內容 * @param generatePath 生成的路徑 * @param photoName 生成後名稱 * @param imageType 圖片的類型 */ public static void getQRcode(String qrdata,String generatePath,String photoName,String imageType) { try { if(StringUtils.isEmpty(generatePath)){ generatePath = "E:\\";// 二維碼默認 } if(StringUtils.isEmpty(photoName)){ photoName = UUID.randomUUID().toString();// 二維碼的圖片名 } if(StringUtils.isEmpty(imageType)){ imageType = "jpg";// 圖片類型 } MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); Map<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = multiFormatWriter.encode(qrdata, BarcodeFormat.QR_CODE, 400, 400, hints); File file1 = new File(generatePath, photoName + "." + imageType); if (!file1.exists() && !file1.isDirectory()) { file1.mkdirs(); } MatrixToImageWriter.writeToFile(bitMatrix, imageType, file1); } catch (WriterException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /**
* 簡要構造器 * @param qrdata 二維碼內容 * @param photoName 二維碼名稱(能夠不填,寫null 生成後名稱就是uuid) */ public static void getQRcode(String qrdata,String photoName) { getQRcode(qrdata,null,photoName,null); } } class MatrixToImageWriter { private static final int BLACK = 0xFF000000; private static final int WHITE = 0xFFFFFFFF; public static BufferedImage toBufferedImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.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, matrix.get(x, y) ? BLACK : WHITE); } } return image; } public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException { BufferedImage image = toBufferedImage(matrix); if (!ImageIO.write(image, format, file)) { throw new IOException("Could not write an image of format " + format + " to " + file); } } }
3:新建枚舉類,用來放一些經常使用的圖片類型 也能夠不用這一步,直接在測試的時候,圖片類型直接寫成String類型的,如:「JPG」dom
public enum ImageTypeEnum {
JPG("jpg"),
PNG("png"),
BMP("bmp"),
TIF("tif"),
GIF("gif"),
PCX("pcx"),
TGA("tga"),
FPX("fpx"),
SVG("scg"),
PSD("psd"),
CDR("cdr"),
EXIF("exif");
private String type; public String getType() { return type; } ImageTypeEnum(String type) { this.type = type; } }
4:測試生成二維碼測試
@SpringBootTest class DemoApplicationTests {
@Test
void contextLoads() throws Exception {
GenerateQRcode.getQRcode("https://www.cnblogs.com/aiqingbi-aifeifei/",null,"測試",ImageTypeEnum.GIF.getType());
GenerateQRcode.getQRcode("https://www.cnblogs.com/aiqingbi-aifeifei/","E:\\","測試名稱","png");
}
}
結果:ui
二:二維碼中間套圖片等this
1:首先仍是導入jar包,與上面的包是一致的google
2:配置寫入器spa
package com.ff.demo;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.util.StringUtils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;
import java.util.UUID;
public class GenerateUtils {
private static final String CHARSET = "utf-8";
private static final String FORMAT_NAME = "jpg";
// 二維碼尺寸
private static final int QRCODE_SIZE = 300;
// LOGO寬度
private static final int WIDTH = 100;
// LOGO高度
private static final int HEIGHT = 100;
private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
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;
}
// 插入圖片
GenerateUtils.insertImage(image, imgPath, needCompress);
return image;
}
/**
* 插入LOGO
*
* @param source 二維碼圖片
* @param imgPath LOGO圖片地址
* @param needCompress 是否壓縮
* @throws Exception
*/
private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) 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 > WIDTH) {
width = WIDTH;
}
if (height > HEIGHT) {
height = 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();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - 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 是否壓縮LOGO
* @throws Exception
*/
public static String getLogoQRcode(String content, String imgPath, String destPath, boolean needCompress,String photoName,String imageType)
throws Exception {
BufferedImage image = GenerateUtils.createImage(content, imgPath, needCompress);
// 隨機生成二維碼圖片文件名
if(StringUtils.isEmpty(destPath)){
destPath = "E:\\";// 二維碼默認
}
if(StringUtils.isEmpty(photoName)){
photoName = UUID.randomUUID().toString();// 二維碼的圖片名
}
if(StringUtils.isEmpty(imageType)){
imageType = "jpg";// 圖片類型
}
mkdirs(destPath);
String file = photoName+"."+imageType;
ImageIO.write(image, FORMAT_NAME, new File(destPath,file ));
return destPath + file;
}
/**
* 當文件夾不存在時,mkdirs會自動建立多層目錄,區別於mkdir.(mkdir若是父目錄不存在則會拋出異常)
*
* @author lanyuan Email: mmm333zzz520@163.com
* @date 2013-12-11 上午10:16:36
* @param destPath 存放目錄
*/
public static void mkdirs(String destPath) {
File file = new File(destPath);
// 當文件夾不存在時,mkdirs會自動建立多層目錄,區別於mkdir.(mkdir若是父目錄不存在則會拋出異常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
public static String getLogoQRcode(String content, String imgPath, boolean needCompress)
throws Exception {
String re = getLogoQRcode(content,imgPath,null,needCompress,null,null);
return re;
}
}
3:到這一步就能夠測試了
@SpringBootTest class DemoApplicationTests { @Test void contextLoads() throws Exception { GenerateQRcode.getQRcode("https://www.cnblogs.com/aiqingbi-aifeifei/",null,"測試",ImageTypeEnum.GIF.getType()); GenerateQRcode.getQRcode("https://www.cnblogs.com/aiqingbi-aifeifei/",null,"測試名稱","png"); }
//測試logo方法 @Test void getQR() throws Exception{
//第一個路徑是logo圖片,第二個是生成的路徑 生成的路徑在簡要方法中能夠不寫,默認在我電腦是E盤 GenerateUtils.getLogoQRcode("https://www.cnblogs.com/aiqingbi-aifeifei/","E:\\MyPhotos\\mongchong.jpg","E:\\",true,"測試套圖",ImageTypeEnum.JPG.getType());
GenerateUtils.getLogoQRcode("https://www.cnblogs.com/aiqingbi-aifeifei/","E:\\MyPhotos\\mongchong.jpg",true); } }
結果以下:
至此,生成測試已經完畢,你們能夠參考一下,代碼複製後,改個包名,就能夠直接生成了,可是代碼中的E盤,能夠參考本機的盤,寫個C D應該都沒問題