CommonController.java
3 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
package com.huaheng.system.controller;
import com.google.zxing.WriterException;
import com.huaheng.system.utils.QRCodeGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.ObjectUtils;
import org.krysalis.barcode4j.HumanReadablePlacement;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@Api(tags = "通用方法")
@Controller
public class CommonController {
@ApiOperation(value = "二维码")
@GetMapping(value = "/image/{text}")
public ResponseEntity<byte[]> getImage(@PathVariable("text") String text) {
byte[] qrcode = null;
try {
qrcode = QRCodeGenerator.getQRCodeImage(text, 100, 100);
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Set headers
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
return new ResponseEntity<byte[]>(qrcode, headers, HttpStatus.CREATED);
}
/**
* 生成条形码
* @param message
* @return
*/
@ApiOperation(value = "生成条形码")
@GetMapping(value = "/code128/{message}")
public ResponseEntity<byte[]> generateBarCode128(@PathVariable("message") String message) {
Double height = 50D;
Double width = 1D;
Code128Bean bean = new Code128Bean();
// 分辨率
int dpi = 512;
// 设置两侧是否留白
bean.doQuietZone(true);
// 设置条形码高度和宽度
bean.setBarHeight((double) ObjectUtils.defaultIfNull(height, 9.0D));
bean.setModuleWidth(width);
// 设置文本位置(包括是否显示)
bean.setMsgPosition(HumanReadablePlacement.HRP_BOTTOM);
bean.setFontSize(14);
// 设置图片类型
String format = "image/png";
ByteArrayOutputStream ous = new ByteArrayOutputStream();
BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format, dpi,
BufferedImage.TYPE_BYTE_BINARY, false, 0);
// 生产条形码
bean.generateBarcode(canvas, message);
try {
canvas.finish();
} catch (IOException e) {
//ByteArrayOutputStream won't happen
}
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
return new ResponseEntity<byte[]>(ous.toByteArray(), headers, HttpStatus.CREATED);
}
}