需求
新增App的版本信息时,将App的下载地址转成二维码图标,以base64的方式存储在数据库中
准备
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
关键
/**
* 生成二维码
*
* @param imgPath 生成的二维码图片的保存路径
* @param format 图片格式
* @param content 二维码保存的信息
* @param width
* @param height
* @throws Exception
*/
public static void encodeZx(String imgPath,String format,String content,int width,int height) {
File file = new File(imgPath);
/*
*hints存放加密参数
* 编码格式,排错率,
*/
Map<EncodeHintType,Object> hints = new Hashtable<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
hints.put(EncodeHintType.MARGIN,1);
try {
//BarcodeFormat.QR_CODE:要解析的类型(二维码)
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,width,height,hints);
BufferedImage bufimg = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
for (int x=0;x < width;x++){
for (int y=0;y<height;y++){
bufimg.setRGB(x,y,(bitMatrix.get(x,y)? Color.BLACK:Color.WHITE).getRGB());
}
}
//生成图片:format:图片格式
ImageIO.write(bufimg,format,file);
} catch (IOException | WriterException e) {
String errorMsg = "生成二维码错误";
log.error(errorMsg);
}
}
/**
* 图片转化成base64字符串
*
* @param imgPath
* @return
*/
public static String getImageStr(String imgPath) {
String imgFile = imgPath;
InputStream in = null;
byte[] data;
// 返回Base64编码过的字节数组字符串
String encode = null;
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
try {
// 读取图片字节数组
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
encode = encoder.encode(data);
} catch (IOException e) {
String errorMsg = "读取图片文件错误";
log.error(errorMsg);
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
String errorMsg = "图片文件流关闭错误";
log.error(errorMsg);
e.printStackTrace();
}
}
return encode;
}