1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
| package com.bhy702.common.utils.code;
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 java.awt.*; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.List; import java.util.Map;
public class ZXingCodeUtils {
private static final int CODE_WIDTH = 400; private static final int CODE_HEIGHT = 400; private static final int FRONT_COLOR = 0x000000; private static final int BACKGROUND_COLOR = 0xFFFFFF;
private static final int IMAGE_WIDTH = 650; private static final int IMAGE_HEIGHT = 450;
public static BufferedImage createQRCode(String content) throws WriterException {
BufferedImage bufferedImage = new BufferedImage(CODE_WIDTH, CODE_HEIGHT, BufferedImage.TYPE_INT_RGB);
Map<EncodeHintType, Object> hints = new HashMap(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q); hints.put(EncodeHintType.MARGIN, 1);
MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, CODE_WIDTH, CODE_HEIGHT, hints);
for (int x = 0; x < CODE_WIDTH; x++) { for (int y = 0; y < CODE_HEIGHT; y++) { bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? FRONT_COLOR : BACKGROUND_COLOR); } }
return bufferedImage; }
public static BufferedImage drawTextCodeInImage(String content, List<QRCodeFont> qrCodeFontList) throws WriterException {
BufferedImage bufferedImage = createQRCode(content);
BufferedImage image = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics graphics = image.createGraphics();
graphics.drawImage(bufferedImage, 0, 0, CODE_WIDTH, CODE_HEIGHT, null); bufferedImage.flush();
for (int x = 0; x < IMAGE_WIDTH; x++) { for (int y = 0; y < IMAGE_HEIGHT; y++) { if(x >= CODE_WIDTH || y >= CODE_HEIGHT){ image.setRGB(x, y,BACKGROUND_COLOR); } } }
qrCodeFontList.forEach((codeFont)->{
Font font = codeFont.getFont(); FontMetrics metrics = graphics.getFontMetrics(font);
int ascentHeight = metrics.getAscent();
graphics.setColor(codeFont.getColor()); graphics.setFont(font); graphics.drawString(codeFont.getText(), codeFont.getStartX(), codeFont.getStartY()+ascentHeight);
});
graphics.dispose(); return image; }
}
|