- Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathCodeImgUtil.java
More file actions
Latest commit
341 lines (309 loc) · 11.6 KB
/
Copy pathCodeImgUtil.java
File metadata and controls
341 lines (309 loc) · 11.6 KB
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/* Copyright (C) 2022 GrmPay - All Rights Reserved */
packagegrm.agent.util;
importcom.alibaba.fastjson.JSON;
importcom.alibaba.fastjson.JSONObject;
importcom.google.zxing.*;
importcom.google.zxing.client.j2se.BufferedImageLuminanceSource;
importcom.google.zxing.client.j2se.MatrixToImageWriter;
importcom.google.zxing.common.BitMatrix;
importcom.google.zxing.common.HybridBinarizer;
importcom.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importjavax.imageio.ImageIO;
importjava.awt.*;
importjava.awt.geom.AffineTransform;
importjava.awt.image.AffineTransformOp;
importjava.awt.image.BufferedImage;
importjava.io.File;
importjava.io.IOException;
importjava.io.OutputStream;
importjava.net.URL;
importjava.nio.file.FileSystems;
importjava.nio.file.Path;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
/*
* 二维码生成器
*
* @author GrmPayDev
*/
publicclassCodeImgUtil {
privatestaticfinalLogger_log = LoggerFactory.getLogger(CodeImgUtil.class);
// 二维码尺寸List
privatestaticList<Integer> sizeList = newArrayList<Integer>();
static {
sizeList.add(258);
sizeList.add(344);
sizeList.add(430);
sizeList.add(860);
sizeList.add(1280);
}
publicstaticList<Integer> getEwmSizeList() {
returnsizeList;
}
// 图片宽度的一般
privatestaticfinalintIMAGE_WIDTH = 25;
privatestaticfinalintIMAGE_HEIGHT = 25;
privatestaticfinalintIMAGE_HALF_WIDTH = IMAGE_WIDTH / 2;
privatestaticfinalintFRAME_WIDTH = 2;
// 二维码写码器
privatestaticMultiFormatWritermutiWriter = newMultiFormatWriter();
/**
*
* @param content
* 二维码显示的文本
* @param width
* 二维码的宽度
* @param height
* 二维码的高度
* @param srcImagePath
* 中间嵌套的图片
* @param destImagePath
* 二维码生成的地址
*/
publicstaticvoidencode(Stringcontent, intwidth, intheight,
StringsrcImagePath, StringdestImagePath, StringfileName) {
try {
Filedir = newFile(destImagePath);
_log.error("==================" + destImagePath);
_log.error("==================" + srcImagePath);
if (!dir.exists()) {
_log.error("==================notExist");
booleanresult = dir.mkdirs();
_log.error("==================midirsResult" + result);
}
// ImageIO.write 参数 1、BufferedImage 2、输出的格式 3、输出的文件
ImageIO.write(genBarcode(content, width, height, srcImagePath),
"jpg", newFile(destImagePath + fileName));
} catch (Exceptione) {
_log.error("生成二维码出错", e);
}
}
/**
* 得到BufferedImage
*
* @param content
* 二维码显示的文本
* @param width
* 二维码的宽度
* @param height
* 二维码的高度
* @param srcImagePath
* 中间嵌套的图片
* @return
* @throws WriterException
* @throws IOException
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
privatestaticBufferedImagegenBarcode(Stringcontent, intwidth,
intheight, StringsrcImagePath) throwsWriterException,
IOException {
// 读取源图像
BufferedImagescaleImage = scale(srcImagePath, IMAGE_WIDTH,
IMAGE_HEIGHT, false);
int[][] srcPixels = newint[IMAGE_WIDTH][IMAGE_HEIGHT];
for (inti = 0; i < scaleImage.getWidth(); i++) {
for (intj = 0; j < scaleImage.getHeight(); j++) {
srcPixels[i][j] = scaleImage.getRGB(i, j);
}
}
java.util.Hashtablehint = newjava.util.Hashtable();
hint.put(EncodeHintType.CHARACTER_SET, "utf-8");
hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hint.put(EncodeHintType.MARGIN, 1);
// 生成二维码
BitMatrixmatrix = mutiWriter.encode(content, BarcodeFormat.QR_CODE,
width, height, hint);
// 二维矩阵转为一维像素数组
inthalfW = matrix.getWidth() / 2;
inthalfH = matrix.getHeight() / 2;
int[] pixels = newint[width * height];
for (inty = 0; y < matrix.getHeight(); y++) {
for (intx = 0; x < matrix.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];
}
// 在图片四周形成边框
elseif ((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] = matrix.get(x, y) ? 0xff000000
: 0xfffffff;
}
}
}
BufferedImageimage = newBufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
image.getRaster().setDataElements(0, 0, width, height, pixels);
returnimage;
}
/**
* 把传入的原始图像按高度和宽度进行缩放,生成符合要求的图标
*
* @param srcImageFile
* 源文件地址
* @param height
* 目标高度
* @param width
* 目标宽度
* @param hasFiller
* 比例不对时是否需要补白:true为补白; false为不补白;
* @throws IOException
*/
privatestaticBufferedImagescale(StringsrcImageFile, intheight,
intwidth, booleanhasFiller) throwsIOException {
doubleratio = 0.0; // 缩放比例
URLurl = newURL(srcImageFile);
BufferedImagesrcImage = ImageIO.read(url);
ImagedestImage = srcImage.getScaledInstance(width, height,
BufferedImage.SCALE_SMOOTH);
// 计算比例
if ((srcImage.getHeight() > height) || (srcImage.getWidth() > width)) {
if (srcImage.getHeight() > srcImage.getWidth()) {
ratio = (newInteger(height)).doubleValue()
/ srcImage.getHeight();
} else {
ratio = (newInteger(width)).doubleValue()
/ srcImage.getWidth();
}
AffineTransformOpop = newAffineTransformOp(AffineTransform
.getScaleInstance(ratio, ratio), null);
destImage = op.filter(srcImage, null);
}
if (hasFiller) {// 补白
BufferedImageimage = newBufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2Dgraphic = image.createGraphics();
graphic.setColor(Color.white);
graphic.fillRect(0, 0, 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);
} else {
graphic.drawImage(destImage,
(width - destImage.getWidth(null)) / 2, 0, destImage
.getWidth(null), destImage.getHeight(null),
Color.white, null);
}
graphic.dispose();
destImage = image;
}
return (BufferedImage) destImage;
}
/**
* 生成图像
* filePath 存放图片的路径
* fileName 图片的名称
* info 生成图片的链接地址(例如:weixin://wxpay/s/Anp43md)
* width 图片的宽度
* height 图片的高度
* @throws WriterException
* @throws IOException
*/
publicstaticStringcodeImgEncode(StringfilePath, StringfileName, Stringinfo, intwidth, intheight) throwsWriterException, IOException {
Stringformat="png";
Map<EncodeHintType, Object> hints = newHashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrixbitMatrix = newMultiFormatWriter().encode(info,
BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
Pathpath = FileSystems.getDefault().getPath(filePath, fileName);
Filedir = newFile(filePath);
_log.error("==================" + filePath);
if (!dir.exists()) {
_log.error("==================notExist");
booleanresult = dir.mkdirs();
_log.error("==================midirsResult" + result);
}
MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像
returnpath.toString();
}
publicstaticvoidwriteQrCode(OutputStreamstream, Stringinfo, intwidth, intheight) throwsWriterException, IOException {
Stringformat="png";
Map<EncodeHintType, Object> hints = newHashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.MARGIN,0);
BitMatrixbitMatrix = newMultiFormatWriter().encode(info,
BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
bitMatrix = deleteWhite(bitMatrix);
BufferedImagebi = MatrixToImageWriter.toBufferedImage(bitMatrix);
bi = zoomInImage(bi,width,height);
ImageIO.write(bi,format,stream); // 输出图像
//MatrixToImageWriter.writeToStream(bitMatrix, format, stream);// 输出图像
}
/**
* 解析图像
*/
publicstaticvoidcodeImgDecode() {
StringfilePath = "D://zxing.png";
BufferedImageimage;
try {
image = ImageIO.read(newFile(filePath));
LuminanceSourcesource = newBufferedImageLuminanceSource(image);
Binarizerbinarizer = newHybridBinarizer(source);
BinaryBitmapbinaryBitmap = newBinaryBitmap(binarizer);
Map<DecodeHintType, Object> hints = newHashMap<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Resultresult = newMultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码
JSONObjectcontent = JSON.parseObject(result.getText());
System.out.println("图片中内容: ");
System.out.println("author: " + content.getString("author"));
System.out.println("zxing: " + content.getString("zxing"));
System.out.println("图片中格式: ");
System.out.println("encode: " + result.getBarcodeFormat());
} catch (IOExceptione) {
e.printStackTrace();
} catch (NotFoundExceptione) {
e.printStackTrace();
}
}
/**
* 去除白边
* */
privatestaticBitMatrixdeleteWhite(BitMatrixmatrix) {
int[] rec = matrix.getEnclosingRectangle();
intresWidth = rec[2] + 1;
intresHeight = rec[3] + 1;
BitMatrixresMatrix = newBitMatrix(resWidth, resHeight);
resMatrix.clear();
for (inti = 0; i < resWidth; i++) {
for (intj = 0; j < resHeight; j++) {
if (matrix.get(i + rec[0], j + rec[1])) {
resMatrix.set(i, j);
}
}
}
returnresMatrix;
}
publicstaticBufferedImagezoomInImage(BufferedImageoriginalImage, intwigth, intheight){
BufferedImagenewImage = newBufferedImage(wigth,height,originalImage.getType());
Graphicsg = newImage.getGraphics();
g.drawImage(originalImage,0,0,wigth,height,null);
g.dispose();
returnnewImage;
}
}