Maison > Java > javaDidacticiel > Étude de cas de la classe d'outils de génération de code QR Java (image)

Étude de cas de la classe d'outils de génération de code QR Java (image)

黄舟
Libérer: 2017-09-11 10:34:16
original
1581 Les gens l'ont consulté

二维码对现在的人们来说再熟悉不过了,我们在开发的时候也经常会用到二维码,下面这篇文章主要给大家介绍了关于利用java生成二维码工具类的相关资料,文中给了详细的示例代码,需要的朋友可以参考借鉴,下面来一起看看吧。

二维码介绍

二维条形码最早发明于日本,它是用某种特定的几何图形按一定规律在平面(二维方向上)分布的黑白相间的图形记录数据符号信息的,在代码编制上巧妙地利用构成计算机内部逻辑基础的“0”、“1”比特流的概念,使用若干个与二进制相对应的几何形体来表示文字数值信息,通过图象输入设备或光电扫描设备自动识读以实现信息自动处理。

如下为java生成二维码工具类,可以选择生成文件,或者直接在页面生成,话不多说了,来一起看看详细的示例代码吧。

示例代码


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

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;

import java.nio.file.FileSystems;

import java.util.HashMap;

import java.util.Map;

  

import javax.imageio.ImageIO;

import javax.servlet.http.HttpServletResponse;

  

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

  

import com.alibaba.fastjson.JSONObject;

import com.google.zxing.BarcodeFormat;

import com.google.zxing.Binarizer;

import com.google.zxing.BinaryBitmap;

import com.google.zxing.DecodeHintType;

import com.google.zxing.EncodeHintType;

import com.google.zxing.LuminanceSource;

import com.google.zxing.MultiFormatReader;

import com.google.zxing.MultiFormatWriter;

import com.google.zxing.NotFoundException;

import com.google.zxing.Result;

import com.google.zxing.WriterException;

import com.google.zxing.client.j2se.BufferedImageLuminanceSource;

import com.google.zxing.client.j2se.MatrixToImageWriter;

import com.google.zxing.common.BitMatrix;

import com.google.zxing.common.HybridBinarizer;

  

/**

 *

 * 二维码工具类

 * @see [相关类/方法]

 * @since [产品/模块版本]

 */

public class QRCodeUtil

{

   

 private static final Logger log = LoggerFactory.getLogger(QRCodeUtil.class);

   

   

 /**

  *

  * 生成二维码文件测试

  * @param filePath 文件路径

  * @param fileName 文件名

  * @param number 编号

  * @param phone 手机号

  * @see [类、类#方法、类#成员]

  */

 public static void generatEncodeTest(String filePath, String fileName, String number, String phone)

 {

    

  int width = 200; // 图像宽度

  int height = 200; // 图像高度

  String format = "png";// 图像类型

    

  JSONObject json = new JSONObject();

  json.put("number",number);

  json.put("phone", phone);

  String content = json.toJSONString();// 内容

    

  Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();

  hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

    

  try

  {

   BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵

   String path = FileSystems.getDefault().getPath(filePath, fileName).toString();

   File file = new File(path);

   MatrixToImageWriter.writeToFile(bitMatrix, format, file);// 输出图像

   System.out.println("二维码输出成功");

   System.out.println("图片地址:" + filePath + fileName);

   System.out.println("---------------------------");

  }

  catch (WriterException e)

  {

   e.printStackTrace();

   System.out.println("二维码输出异常");

  }

  catch (IOException e)

  {

   e.printStackTrace();

   System.out.println("二维码输出异常");

  }

 }

   

 /**

  *

  * 解析二维码内容测试

  * @param filePath 二维码绝对路径

  * @see [类、类#方法、类#成员]

  */

 public static void parseDecodeTest(String filePath)

 {

  BufferedImage image;

  try

  {

   image = ImageIO.read(new File(filePath));

   LuminanceSource source = new BufferedImageLuminanceSource(image);

   Binarizer binarizer = new HybridBinarizer(source);

   BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);

     

   Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();

   hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");

     

   Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码

   JSONObject content = JSONObject.parseObject(result.getText());

     

   StringBuffer sb = new StringBuffer();

   sb.append("编号:")

    .append(content.getString("number"))

    .append("\r\n")

    .append("手机号码:")

    .append(content.getString("phone"));

   String returnText = sb.toString();

   System.out.println(returnText);

  }

  catch (IOException e)

  {

   e.printStackTrace();

  }

  catch (NotFoundException e)

  {

   e.printStackTrace();

  }

 }

   

   

 /**

  *

  * 生成二维码输出流

  *  在jsp页面中直接展示时使用

  *  无须保存 即生成即展示

  * @param response

  * @param number 编号

  * @param phone 手机号

  * @see [类、类#方法、类#成员]

  */

 public static void generatEncode(HttpServletResponse response, String number, String phone)

 {

  JSONObject json = new JSONObject();

  json.put("number",number);

  json.put("phone", phone);

  String content = json.toJSONString();// 内容

    

  int width = 200; // 图像宽度

  int height = 200; // 图像高度

  String format = "png";// 图像类型

    

  Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();

  hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

    

  try

  {

     

   BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵

   MatrixToImageWriter.writeToStream(bitMatrix, format, response.getOutputStream());// 输出图像

   log.info("二维码输出成功");

  }

  catch (WriterException e)

  {

   e.printStackTrace();

   log.error("二维码输出异常");

  }

  catch (IOException e)

  {

   e.printStackTrace();

   log.error("二维码输出异常");

  }

 }

   

 public static void main(String[] args)

 {

  generatEncodeTest("D:\\","zxing.png","001","13019931996");

  parseDecodeTest("D:\\zxing.png");

 }

}

Copier après la connexion

总结

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers numéros
Impossible d'installer Java
Depuis 1970-01-01 08:00:00
0
0
0
Installer JAVA
Depuis 1970-01-01 08:00:00
0
0
0
Java peut-il être utilisé comme backend du Web ?
Depuis 1970-01-01 08:00:00
0
0
0
Aide : Données chiffrées JAVA Décryptage PHP
Depuis 1970-01-01 08:00:00
0
0
0
Est-ce en langage Java ?
Depuis 1970-01-01 08:00:00
0
0
0
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal