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;
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();
}
}
public static BufferedImage createQRImage(String content) throws WriterException {
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
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;
}
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;
}
private static void addText(BufferedImage source, String description, int qrWidth) {
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);
int width = textImage.getWidth(null);
int height = textImage.getHeight(null);
graph.drawImage(textImage, 0, qrWidth - 8, width, height, Color.WHITE, null);
graph.dispose();
}
private static BufferedImage genBarcode(String content, String description, int width, int height, String srcImagePath) throws WriterException, IOException {
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<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
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;
}
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();
}
}
}