前言
扫描上传图片中的二维码进行内容解析
提示:以下是本篇文章正文内容,下面案例可供参考
使用步骤
1.先在本地创建文件夹存储图片
代码如下(示例):
String path = request.getSession().getServletContext()
.getRealPath("/upload/photo/temp/");
System.out.println(path);
createFileDir(path);
path+="/photo.PNG";
String basePhoto = photo.substring(photo.indexOf(",")+1);
private void createFileDir(String path) {
File dirFile = new File(path);
boolean bFile = dirFile.exists();
if (bFile) {
log.info("文件路径[{}]存在!", path);
} else {
log.info("文件路径[{}]不存在,需要创建!", path);
bFile = dirFile.mkdirs();
log.info("文件路径[{}]创建成功!", path);
}
}
2.将base64码值转换为图片
代码如下(示例):
/**
* @param imgStr base64编码字符串
* @param path 图片路径-具体到文件
*/
public static boolean generateImage(String imgStr, String path) {
if (imgStr == null)
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// 解密
byte[] b = decoder.decodeBuffer(imgStr);
// 处理数据
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
OutputStream out = new FileOutputStream(path);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
3.检查图片中是否有二维码 有则解析
/**
* 检查图片中是否有二维码 有则解析
* @param filePath
* @return
*/
private String checkQRCode(String filePath){
try {
// 读取二维码图片到缓冲区
BufferedImage image = ImageIO.read(new File(filePath));
//缩小图片
int pw = image.getWidth();
int ph = image.getHeight();
if(pw>300)
{
ph = (int)(ph*300)/pw;
pw = 300;
}
image = resizeImage(image,pw,ph);
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);// 对图像进行解码
System.out.println("======>>encode Type: " + result.getBarcodeFormat() + " ======>>content:" + result.getText());
return result.getText();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
将图片缩小 防止过大导致无法扫描
/**
* 将图片缩小
* @param originalImage
* @param targetWidth
* @param targetHeight
* @return
* @throws IOException
*/
public static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) throws IOException {
Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_AREA_AVERAGING);
BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
outputImage.getGraphics().drawImage(resultingImage, 0, 0, null);
return outputImage;
}