package com.scamel.mom.common.util;
import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.nacos.common.utils.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;
import sun.font.FontDesignMetrics;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.AffineTransform;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* 二维码、条码生成工具
*/
public class CodeUtils {
/**
* 中心图片宽度的
*/
private static final int IMAGE_WIDTH = 80;
private static final int IMAGE_HEIGHT = 80;
private static final int IMAGE_HALF_WIDTH = IMAGE_WIDTH / 2;
private static final int FRAME_WIDTH = 2;
/**
* 宋体
*/
private static Font fontSun;
/*
静态加载字体(linux没中文字体,会显示口口口)
*/
static {
try {
ClassPathResource fontResource = new ClassPathResource("font/simsun.ttc");
Font font = Font.createFont(Font.TRUETYPE_FONT, fontResource.getStream());
fontSun = font.deriveFont(Font.BOLD, 15);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 生成二维码
*
* @param content 二维码内容
* @return 图片
* @throws WriterException 异常
*/
public static BufferedImage createQRImage(String content) throws WriterException {
// 二维码参数设置
Map<EncodeHintType, Object> hints = new HashMap<>();
// 安全等级,最高h
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 编码设置
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 设置margin=0-10
hints.put(EncodeHintType.MARGIN, 1);
// 创建矩阵容器
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 300, 300,
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);
}
}
return image;
}
/**
* 生成中心插入图片底部带文字的二维码
*
* @param content 二维码内容
* @param description 底部描述文字
* @return 要插入的图片
* @throws WriterException 异常
*/
public static BufferedImage createQRImageWithPic(String content, String description, String srcImagePath) throws WriterException, IOException {
BufferedImage bufferedImage = genBarcode(content, description, 300, 300, srcImagePath);
// 判断是否添加底部文字
if (StringUtils.hasText(description)) {
addText(bufferedImage, description, 300);
}
return bufferedImage;
}
/**
* 二维码底部添加文字
*
* @param source 源二维码图片
* @param description 底部描述文字
*/
private static void addText(BufferedImage source, String description, int qrWidth) {
//生成image
int defineHeight = 20;
BufferedImage textImage = new BufferedImage(qrWidth, defineHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) textImage.getGraphics();
//开启文字抗锯齿
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setBackground(Color.WHITE);
g2.clearRect(0, 0, qrWidth, defineHeight);
g2.setPaint(Color.BLACK);
FontRenderContext context = g2.getFontRenderContext();
g2.setFont(fontSun);
LineMetrics lineMetrics = fontSun.getLineMetrics(description, context);
FontMetrics fontMetrics = FontDesignMetrics.getMetrics(fontSun);
float offset = (qrWidth - fontMetrics.stringWidth(description)) / 2;
float y = (defineHeight + lineMetrics.getAscent() - lineMetrics.getDescent() - lineMetrics.getLeading()) / 2;
g2.drawString(description, (int) offset, (int) y);
Graphics2D graph = source.createGraphics();
//开启文字抗锯齿
graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//添加image
int width = textImage.getWidth(null);
int height = textImage.getHeight(null);
graph.drawImage(textImage, 0, qrWidth - 8, width, height, Color.WHITE, null);
graph.dispose();
}
/**
* 生成二维码并在中心插入图片
*
* @param content 二维码内容
* @param description 底部描述文本
* @param width 二维码宽度
* @param height 二维码高度
* @param srcImagePath 原图片
* @return
* @throws WriterException
* @throws IOException
*/
private static BufferedImage genBarcode(String content, String description, int width, int height, String srcImagePath) throws WriterException, IOException {
// 有文字,高度+12,不然底部文字显示不全
if (StringUtils.hasText(description)) {
height = height + 12;
}
// 读取源图像并缩放
BufferedImage scaleImage = scale(srcImagePath, IMAGE_WIDTH, IMAGE_HEIGHT, false);
int[][] srcPixels = new int[IMAGE_WIDTH][IMAGE_HEIGHT];
for (int i = 0; i < scaleImage.getWidth(); i++) {
for (int j = 0; j < scaleImage.getHeight(); j++) {
srcPixels[i][j] = scaleImage.getRGB(i, j);
}
}
// 二维码参数设置
Map<EncodeHintType, Object> hints = new HashMap<>();
// 安全等级,最高h
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 编码设置
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 设置margin=0-10
hints.put(EncodeHintType.MARGIN, 1);
// 创建矩阵容器
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,
hints);
// 二维矩阵转为一维像素数组
int halfW = bitMatrix.getWidth() / 2;
int halfH = bitMatrix.getHeight() / 2;
int[] pixels = new int[width * height];
for (int y = 0; y < bitMatrix.getHeight(); y++) {
for (int x = 0; x < bitMatrix.getWidth(); x++) {
// 读取图片
if (x > halfW - IMAGE_HALF_WIDTH
&& x < halfW + IMAGE_HALF_WIDTH
&& y > halfH - IMAGE_HALF_WIDTH
&& y < halfH + IMAGE_HALF_WIDTH) {
pixels[y * width + x] = srcPixels[x - halfW
+ IMAGE_HALF_WIDTH][y - halfH + IMAGE_HALF_WIDTH];
} else if (
// 在图片四周形成边框
(x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
&& x < halfW - IMAGE_HALF_WIDTH + FRAME_WIDTH
&& y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH
+ IMAGE_HALF_WIDTH + FRAME_WIDTH)
|| (x > halfW + IMAGE_HALF_WIDTH - FRAME_WIDTH
&& x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
&& y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH
+ IMAGE_HALF_WIDTH + FRAME_WIDTH)
|| (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
&& x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
&& y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH
- IMAGE_HALF_WIDTH + FRAME_WIDTH)
|| (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
&& x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
&& y > halfH + IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH
+ IMAGE_HALF_WIDTH + FRAME_WIDTH)) {
pixels[y * width + x] = 0xfffffff;
} else {
// 此处可以修改二维码的颜色,可以分别制定二维码和背景的颜色;
pixels[y * width + x] = bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF;
}
}
}
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
image.getRaster().setDataElements(0, 0, width, height, pixels);
return image;
}
/**
* 把传入的原始图像按高度和宽度进行缩放,生成符合要求的图标
*
* @param srcImageFile 源文件地址
* @param height 目标高度
* @param width 目标宽度
* @param hasFiller 比例不对时是否需要补白:true为补白; false为不补白;
* @throws IOException
*/
private static BufferedImage scale(String srcImageFile, int height, int width, boolean hasFiller) throws IOException {
// 缩放比例
double ratio;
File file = new File(srcImageFile);
BufferedImage srcImage = ImageIO.read(file);
Image destImage = srcImage.getScaledInstance(width, height,
BufferedImage.SCALE_SMOOTH);
// 计算比例
if ((srcImage.getHeight() > height) || (srcImage.getWidth() > width)) {
if (srcImage.getHeight() > srcImage.getWidth()) {
ratio = (new Integer(height)).doubleValue()
/ srcImage.getHeight();
} else {
ratio = (new Integer(width)).doubleValue()
/ srcImage.getWidth();
}
AffineTransformOp op = new AffineTransformOp(
AffineTransform.getScaleInstance(ratio, ratio), null);
destImage = op.filter(srcImage, null);
}
if (hasFiller) {
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D graphic = image.createGraphics();
graphic.setColor(Color.PINK);
graphic.fillRect(10, 10, width, height);
graphic.drawRect(100, 360, width, height);
if (width == destImage.getWidth(null)) {
graphic.drawImage(destImage, 0,
(height - destImage.getHeight(null)) / 2,
destImage.getWidth(null), destImage.getHeight(null),
Color.white, null);
Shape shape = new RoundRectangle2D.Float(0, (height - destImage.getHeight(null)) / 2, width, width, 20, 20);
graphic.setStroke(new BasicStroke(5f));
graphic.draw(shape);
} else {
graphic.drawImage(destImage,
(width - destImage.getWidth(null)) / 2, 0,
destImage.getWidth(null), destImage.getHeight(null),
Color.white, null);
Shape shape = new RoundRectangle2D.Float((width - destImage.getWidth(null)) / 2, 0, width, width, 20, 20);
graphic.setStroke(new BasicStroke(5f));
graphic.draw(shape);
}
graphic.dispose();
destImage = image;
}
return (BufferedImage) destImage;
}
public static void main(String[] args) {
try {
String content = "任天豚就是世界的猪崽";
BufferedImage image = genBarcode(content, content, 300, 300, "D://二维码//任天豚就是世界的猪崽-s.jpg");
// 判断是否添加底部文字
if (StringUtils.hasText(content)) {
addText(image, content, 300);
}
if (!ImageIO.write(image, "jpg", new File("D://二维码//test.jpg"))) {
throw new IOException("Could not write an image of format ");
}
} catch (WriterException | IOException e) {
e.printStackTrace();
}
}
}
生成中心插入图片底部带文字的二维码
最新推荐文章于 2024-05-03 16:12:22 发布