二维码 zip

This commit is contained in:
xiangwb
2017-11-17 15:56:37 +08:00
parent 20372cdc21
commit 56dcbcb577
14 changed files with 567 additions and 16 deletions
+11
View File
@@ -55,6 +55,17 @@
<artifactId>jedis</artifactId>
<version>2.7.3</version>
</dependency>
<!-- 二维码 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>${zxing.version}</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>${zxing.version}</version>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
@@ -9,7 +9,7 @@ import lombok.Data;
* 说明: 快递追踪信息
*/
@Data
public class Trace {
public class ExpressTrace {
private String AcceptTime;
private String AcceptStation;
}
@@ -1,6 +1,6 @@
package com.xwbing.entity.vo;
import com.xwbing.entity.Trace;
import com.xwbing.entity.ExpressTrace;
import lombok.Data;
import java.util.List;
@@ -29,7 +29,7 @@ public class ExpressInfoVo {
/**
* 物流信息
*/
private List<Trace> traces;
private List<ExpressTrace> expressTraces;
/**
* 描述
*/
@@ -70,7 +70,7 @@ public class ExpressDeliveryService {
String requestData = "{'ShipperCode':'" + info.getShipperCode() + "','LogisticCode':'" + info.getLogisticCode() + "'}";
Map<String, String> params = new HashMap<>();
try {
params.put("RequestData", urlEncoder(requestData, "UTF-8"));
params.put("RequestData", KdniaoUtil.urlEncoder(requestData, "UTF-8"));
params.put("EBusinessID", EBusinessID);
params.put("RequestType", "1002");
String dataSign = KdniaoUtil.encrypt(requestData, appKey, "UTF-8");
@@ -79,6 +79,7 @@ public class ExpressDeliveryService {
} catch (Exception e) {
logger.error("快递查询出错:{}", e.getMessage());
throw new BusinessException("快递查询出错");
}
// 返回物流信息
// status: 0|null 无信息 1已取件 2在途中 3已签收 4问题件 5待取件 6待派件 8已发货 9未发货
@@ -93,7 +94,7 @@ public class ExpressDeliveryService {
int statusValue = Integer.valueOf(status);
CommonEnum.ExpressStatusEnum expressStatus = Arrays.stream(CommonEnum.ExpressStatusEnum.values()).filter(obj -> obj.getValue() == statusValue).findFirst().get();
infoVo.setDescribe(expressStatus.getName());
// TODO: 2017/11/17 根据公司业务处理返回的信息......
// TODO: 2017/11/16 根据公司业务处理返回的信息......
}
return infoVo;
}
@@ -0,0 +1,128 @@
package com.xwbing.service;
import com.xwbing.exception.BusinessException;
import com.xwbing.util.QRCodeUtils;
import com.xwbing.util.RestMessage;
import com.xwbing.util.ZipUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 项目名称: boot-module-demo
* 创建时间: 2017/11/17 13:36
* 作者: xiangwb
* 说明:
*/
@Service
public class QRcodeZipService {
private final Logger logger = LoggerFactory.getLogger(QRcodeZipService.class);
/**
* 生成默认长度的二维码
*
* @param name 图片名
* @param text 二维码内容
* @return
*/
public RestMessage createQRCode(String name, String text) {
RestMessage result = new RestMessage();
String path = getPath();
File output = new File(path + File.separator + name + ".png");
QRCodeUtils.createCode(text, output);
result.setSuccess(true);
result.setMessage("生成二维码成功");
return result;
}
/**
* 解析二维码
*
* @param file
* @return
*/
public RestMessage decode(File file) {
RestMessage result = new RestMessage();
try {
String decode = QRCodeUtils.decode(file);
result.setData(decode);
result.setSuccess(true);
result.setMessage("解析二维码成功");
return result;
} catch (Exception e) {
logger.error("解析二维码失败");
throw new BusinessException("解析二维码失败");
}
}
/**
* 获取图片zip
*
* @return
*/
public RestMessage batchGetImage(HttpServletResponse response, String[] names, String fileName) {
List<File> files = new ArrayList<>();
if (names.length == 0)
throw new BusinessException("请选择要导出的图片");
Arrays.stream(names).forEach(name -> {
File file = getFile(name);
if (file != null && file.length() > 0) {
files.add(file);
}
});
return zipFile(response, files, fileName);
}
/**
* 根据文件名获取图片
*
* @param name
* @return
*/
private File getFile(String name) {
String path = getPath();
File output = new File(path + File.separator + name + ".png");
if (output.exists()) {
return output;
}
return null;
}
/**
* 获取pic路径
*
* @return
*/
private String getPath() {
ClassPathResource pic = new ClassPathResource("file");
String absolutePath;
try {
absolutePath = pic.getFile().getAbsolutePath();
} catch (IOException e) {
throw new BusinessException("获取图片路径错误");
}
return absolutePath;
}
/**
* 导出文件
*
* @return
*/
private RestMessage zipFile(HttpServletResponse response, List<File> files, String fileName) {
RestMessage restMessage = new RestMessage();
String path = getPath();
ZipUtil.zipFile(response, files, path, fileName);
restMessage.setSuccess(true);
restMessage.setMessage("导出zip文件成功");
return restMessage;
}
}
@@ -24,6 +24,8 @@ public class JSONUtil {
public static Object beanToMap(Object obj) {
if (obj == null)
return null;
if (obj instanceof String)
return obj;
if (obj instanceof List) {
List<?> list = (List<?>) obj;
ArrayList<JSONObject> result = new ArrayList<>();
@@ -28,8 +28,7 @@ public class KdniaoUtil {
StringBuilder result = new StringBuilder();
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl
.openConnection();
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
@@ -38,10 +37,8 @@ public class KdniaoUtil {
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.connect();
// 获取URLConnection对象对应的输出流
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
@@ -63,8 +60,7 @@ public class KdniaoUtil {
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "UTF-8"));
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
@@ -0,0 +1,285 @@
package com.xwbing.util;
import com.google.zxing.*;
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;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.io.output.ByteArrayOutputStream;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
/**
* 项目名称: boot-module-demo
* 创建时间: 2017/11/17 11:43
* 作者: xiangwb
* 说明: 二维码工具类
*/
public class QRCodeUtils {
private static QRCodeUtils.Internal internal = new QRCodeUtils.Internal();
/***
* 生成默认尺寸不带logo的二维码
* @param text 二维码内容
* @param output 图片文件
*/
public static void createCode(String text, File output) {
createCode(text, 200, 200, output);
}
/**
* 自定义尺寸不带logo的二维码
*
* @param text 二维码内容
* @param width 宽
* @param height 高
* @param output 图片文件
*/
public static void createCode(String text, int width, int height, File output) {
try {
System.out.println(output.getParentFile().getAbsolutePath());
internal._codeHeight = height;
internal._codeWidth = width;
internal._output = output;
internal.output(output, internal.createCode(text));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 生成默认尺寸带logo的二维码
*
* @param url 二维码
* @param logoImg
* @param text
*/
public static void createCodeLogo(String url, InputStream logoImg, String text) {
createCodeLogo(url, 200, 200, logoImg, text, 14);
}
/**
* 生成自定义尺寸带logo的二维码
*
* @param text
* @param width
* @param height
* @param logoImg
*/
public static InputStream createCodeLogo(String url, int width, int height, InputStream logoImg, String text, int size) {
try {
internal._codeHeight = height;
internal._codeWidth = width;
internal._logoImg = logoImg;
internal._text = text;
internal._fontSize = size;
BitMatrix bitMatrix = internal.createCode(url);
return internal.addMaterial(bitMatrix);
//internal.output(output, bitMatrix);
} catch (WriterException e) {
e.printStackTrace();
return null;
}
}
/**
* 解析二维码图片
*
* @param file
* @return
* @throws Exception
*/
public static String decode(File file) throws Exception {
if (file == null) {
return null;
}
MultiFormatReader formatReader = new MultiFormatReader();
BufferedImage image = ImageIO.read(file);
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
Hashtable<DecodeHintType, Object> hints = new Hashtable<>();
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
Result result = formatReader.decode(binaryBitmap, hints);
return result.getText();
}
private static class Internal {
// 二维码大小
private int _codeWidth;
private int _codeHeight;
//二维码导出位置
private File _output;
/**
* logo文件流,二维码文本
*/
private InputStream _logoImg;
private String _text;
private int _fontSize;
//logo大小
private int _logoWidth;
private int _logoHeight;
//logo x,y坐标
private int _logoX;
private int _logoY;
//文字x,y坐标
private int _textX;
private int _textY;
//图像类型
private final String _format = "png";
private BitMatrix createCode(String url) throws WriterException {
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
BitMatrix encode = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, _codeWidth, _codeHeight, hints);// 生成矩阵
return encode;
}
/***
* 输出生成的二维码
* @param output
* @param bitMatrix
* @throws IOException
*/
private void output(File output, BitMatrix bitMatrix) throws IOException {
Path path = FileSystems.getDefault().getPath(output.getParentFile().getAbsolutePath(), output.getName());
MatrixToImageWriter.writeToPath(bitMatrix, _format, path);// 输出图像
}
/***
* 输出带特殊需求的二维码
* @throws IOException
*/
private void output(BufferedImage image) throws IOException {
if (!ImageIO.write(image, _format, _output)) {
throw new IOException("Could not write an image of format " + _format + " to " + _output);
}
}
/**
* 在二维码基础上添加需求
*
* @param bitMatrix
*/
private InputStream addMaterial(BitMatrix bitMatrix) {
try {
BufferedImage image = toBufferedImage(bitMatrix);
//计算高宽
computeWidthHeight();
//定位logo
image = position_logo(image);
//定位文字
image = position_text(image);
//生成二维码
//output(image);
//转InputStream
return bufferImage_to_InputStream(image);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private BufferedImage position_text(BufferedImage image) {
Graphics2D gh = image.createGraphics();
gh.setColor(Color.black);
//如果linux上没有该字体的话,会出现类似乱码的情况
//Font.SANS_SERIF
gh.setFont(new Font("Microsoft YaHei", Font.BOLD, _fontSize));
gh.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_IN, 1.0f));
gh.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
gh.drawString(_text, 20, _fontSize);
return image;
}
/**
* 定位logo
*/
private BufferedImage position_logo(BufferedImage image) throws IOException {
Graphics2D gs = image.createGraphics();
//载入logo
BufferedImage logo = changeWidthHeight();
gs.drawImage(logo, _logoX, _logoY, null);
gs.dispose();
logo.flush();
return image;
}
/**
* 改变图片大小
*
* @return
* @throws IOException
*/
private BufferedImage changeWidthHeight() throws IOException {
BufferedImage img = ImageIO.read(_logoImg);
BufferedImage newLogo = new BufferedImage(_logoWidth, _logoHeight, BufferedImage.TYPE_INT_BGR);
Graphics graphics = newLogo.createGraphics();
graphics.drawImage(img, 0, 0, _logoWidth, _logoHeight, null);
graphics.setColor(Color.white);
graphics.drawRect(0, 0, _logoWidth - 1, _logoHeight - 1);
graphics.drawRect(1, 1, _logoWidth - 1, _logoHeight - 1);
graphics.drawRect(0, 0, _logoWidth - 2, _logoHeight - 2);
img.flush();
return newLogo;
}
private void computeWidthHeight() {
//计算logo大小
_logoHeight = _codeHeight * 2 / 10;
_logoWidth = _codeWidth * 2 / 10;
//计算logo坐标
_logoX = (_codeWidth - _logoWidth) / 2;
_logoY = (_codeHeight - _logoHeight) / 2;
}
/**
* BitMatrix转BufferedImage
*
* @param matrix
* @return
*/
private BufferedImage toBufferedImage(BitMatrix matrix) {
BufferedImage image = new BufferedImage(matrix.getWidth(), matrix.getHeight(), BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < matrix.getWidth(); x++) {
for (int y = 0; y < matrix.getHeight(); y++) {
image.setRGB(x, y, matrix.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
}
}
return image;
}
private InputStream bufferImage_to_InputStream(BufferedImage image) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image, _format, os);
return new ByteArrayInputStream(os.toByteArray());
}
}
public static void main(String[] args) throws Exception {
// String tomcatHome = System.getProperty("catalina.home");
// String name="QRcode";
// File output=new File(tomcatHome+File.separator+"file"+File.separator+name+".png");
File output = new File("C:/Users/10232/Desktop/xwbing.png");
createCode("xwbing", 500, 500, output);//text即QRcode
String decode = decode(output);
}
}
@@ -0,0 +1,95 @@
package com.xwbing.util;
import com.xwbing.exception.BusinessException;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 项目名称: boot-module-demo
* 创建时间: 2017/11/17 14:24
* 作者: xiangwb
* 说明:
*/
public class ZipUtil {
/**
* @param response 响应
* @param files 所有文件
* @param fileName 文件名
*/
public static void zipFile(HttpServletResponse response, List<File> files, String path, String fileName) {
try {
//classpath下有file文件夹
File zipFile = new File(path + File.separator + fileName + ".zip");
if (!zipFile.exists()) {
zipFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
FileInputStream fis;
BufferedInputStream bis;
byte[] data = new byte[1024 * 10];
if (files != null && files.size() > 0) {
for (File file : files) {
String name = file.getName();
//创建ZIP实体,并添加进压缩包
ZipEntry zipEntry = new ZipEntry(name);
zos.putNextEntry(zipEntry);
//读取待压缩的文件并写进压缩包里
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
int d;
while ((d = bis.read(data, 0, 1024 * 10)) != -1) {
zos.write(data, 0, d);
}
bis.close();
fis.close();
}
}
zos.close();
// 输出到客户端
OutputStream out = response.getOutputStream();
response.reset();
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".zip");//在消息头里命名输出的zip文件夹名称
response.setContentType("application/octet-stream; charset=utf-8");
out.write(toByte(zipFile));
// out.flush();
out.close();
zipFile.delete();
} catch (Exception e) {
throw new BusinessException("文件压缩错误");
}
}
/**
* 文件转换byte字节数组
*
* @param file
* @return
*/
private static byte[] toByte(File file) {
{
byte[] bytes;
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] data = new byte[1024 * 10];
int len;
while ((len = fis.read(data)) != -1) {
bos.write(data, 0, len);
}
bytes = bos.toByteArray();
fis.close();
bos.close();
} catch (IOException e) {
throw new BusinessException("文件转化错误");
}
return bytes;
}
}
}
@@ -1,5 +1,6 @@
#---------------快递鸟config----------------
###------------ID和Key请到官网申请:http://www.kdniao.com/ServiceApply.aspx-------------###
###------------ID和Key请到官网申请:http://www.kdniao.com/ServiceApply.aspx-------------###
###------------相关文档:http://www.kdniao.com/documents-------------###
EBusinessID=1255383
appKey=94f7286a-8ae5-4394-8809-26dd645e82ca
reqURL=http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx
@@ -60,7 +60,7 @@ public class MailTestControl {
@GetMapping("sendInlineResourceMail")
@ApiOperation(value = "发送文本内嵌图片邮件")
public JSONObject sendInlineResourceMail() {
String rscId = "pic";
String rscId = "file";
String content = "<html><body>这是有图片的邮件:<img src=\'cid:" + rscId + "\'></body></html>";
String imgPath = "C:\\Users\\admin\\Desktop\\0000001.png";
RestMessage restMessage = mailService.sendInlineResourceMail("786461501@qq.com", "内嵌图片测试邮件", content, imgPath, rscId);
@@ -6,7 +6,9 @@ import com.xwbing.entity.ExpressInfo;
import com.xwbing.entity.vo.ExpressInfoVo;
import com.xwbing.redis.RedisService;
import com.xwbing.service.ExpressDeliveryService;
import com.xwbing.service.QRcodeZipService;
import com.xwbing.util.JSONObjResult;
import com.xwbing.util.RestMessage;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
@@ -14,6 +16,8 @@ import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
/**
@@ -30,6 +34,8 @@ public class TestControl {
private RedisService redisService;
@Resource
private ExpressDeliveryService expressDeliveryService;
@Resource
private QRcodeZipService QRcodeZipService;
private final Logger logger = LoggerFactory.getLogger(TestControl.class);
@LogInfo("redis功能测试")
@@ -54,7 +60,6 @@ public class TestControl {
return JSONObjResult.toJSONObj(list, true, "");
}
@LogInfo("快递查询")
@PostMapping("expressInfo")
public JSONObject getExpressInfo(@RequestBody ExpressInfo info) {
@@ -63,4 +68,30 @@ public class TestControl {
ExpressInfoVo infoVo = expressDeliveryService.queryOrderTraces(info);
return JSONObjResult.toJSONObj(infoVo, true, "查询快递信息成功");
}
@LogInfo("生成二维码")//为什么内置tomcat会重启
@PostMapping("createQRCode")
public JSONObject createQRCode(@RequestParam String name, @RequestParam String text) {
RestMessage qrCode = QRcodeZipService.createQRCode(name, text);
return JSONObjResult.toJSONObj(qrCode);
}
@LogInfo("解析二维码")
@GetMapping("decode")
public JSONObject decode(@RequestParam String path) {
if (StringUtils.isEmpty(path))
return JSONObjResult.toJSONObj("二维码图片路径不能为空");
File file = new File(path);
RestMessage decode = QRcodeZipService.decode(file);
return JSONObjResult.toJSONObj(decode);
}
@LogInfo("导出zip")
@GetMapping("batchGetImage")
public JSONObject batchGetImage(HttpServletResponse response, @RequestParam String[] names, @RequestParam String fileName) {
if (StringUtils.isEmpty(fileName))
return JSONObjResult.toJSONObj("zip名称不能为空");
RestMessage restMessage = QRcodeZipService.batchGetImage(response, names, fileName);
return JSONObjResult.toJSONObj(restMessage);
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 326 B

+1
View File
@@ -37,6 +37,7 @@
<java.version>1.8</java.version>
<fileUpLoad.version>1.3.1</fileUpLoad.version>
<lombok.version>1.16.16</lombok.version>
<zxing.version>3.2.1</zxing.version>
<!-- 打包跳过单元测试 -->
<skipTests>true</skipTests>
<swagger2.version>2.4.0</swagger2.version>