提交 | 用户 | age
|
c0a0c6
|
1 |
package com.hx.util; |
C |
2 |
|
|
3 |
import com.google.zxing.BarcodeFormat; |
|
4 |
import com.google.zxing.MultiFormatWriter; |
|
5 |
import com.google.zxing.client.j2se.MatrixToImageWriter; |
|
6 |
import com.google.zxing.common.BitMatrix; |
|
7 |
import sun.misc.BASE64Encoder; |
|
8 |
|
|
9 |
import javax.imageio.ImageIO; |
|
10 |
import java.awt.image.BufferedImage; |
|
11 |
import java.io.ByteArrayOutputStream; |
|
12 |
|
|
13 |
public class BarCodeUtil { |
|
14 |
|
|
15 |
/** |
|
16 |
* 给前端产生一个条形码 |
|
17 |
* |
|
18 |
* @param number 编码 |
|
19 |
* @param width 宽度 |
|
20 |
* @param height 高度 |
|
21 |
*/ |
|
22 |
public static String getCode(String number, Integer width, Integer height) { |
|
23 |
// 生成条形码 |
|
24 |
BufferedImage image = getBarCode(number, width, height); |
|
25 |
// 使用流的方式 |
|
26 |
ByteArrayOutputStream out = new ByteArrayOutputStream(); |
|
27 |
try { |
|
28 |
ImageIO.write(image, "png", out); |
|
29 |
} catch (Exception e) { |
|
30 |
// log.error("generate code error! error message:{}", "出现问题!"); |
|
31 |
e.printStackTrace(); |
|
32 |
} |
|
33 |
// 将流转成数组 |
|
34 |
byte[] bytes = out.toByteArray(); |
|
35 |
BASE64Encoder encoder = new BASE64Encoder(); |
|
36 |
// 把生成的编码返回去 |
|
37 |
return "data:image/png;base64," + encoder.encodeBuffer(bytes).trim(); |
|
38 |
} |
|
39 |
|
|
40 |
/** |
|
41 |
* 产生条形码的方法 |
|
42 |
* |
|
43 |
* @param number 编码 |
|
44 |
* @param width 宽度 |
|
45 |
* @param height 高度 |
|
46 |
*/ |
|
47 |
public static BufferedImage getBarCode(String number, Integer width, Integer height) { |
|
48 |
try { |
|
49 |
BitMatrix bitMatrix = new MultiFormatWriter().encode(number, BarcodeFormat.CODE_128, width, height); |
|
50 |
return MatrixToImageWriter.toBufferedImage(bitMatrix); |
|
51 |
} catch (Exception e) { |
|
52 |
e.printStackTrace(); |
|
53 |
} |
|
54 |
return null; |
|
55 |
} |
|
56 |
|
|
57 |
} |