概述
记录下来 ,方便以后使用
package com.xhb.orc.controller;
import com.google.zxing.*;
import com.google.zxing.common.HybridBinarizer;
import com.xhb.orc.BufferedImageLuminanceSource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
public class Ocr {
public static String decodeQr(String filePath) {
String retStr = "";
if ("".equalsIgnoreCase(filePath) && filePath.length() == 0) {
return "图片路径为空!";
}
try {
BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filePath));
LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap bitmap = new BinaryBitmap(binarizer);
HashMap<DecodeHintType, Object> hintTypeObjectHashMap = new HashMap<>();
//
hintTypeObjectHashMap.put(DecodeHintType.CHARACTER_SET, "UTF-8");
//
//
hintTypeObjectHashMap.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
//
//
//
///
hintTypeObjectHashMap.put(DecodeHintType.POSSIBLE_FORMATS, BarcodeFormat.QR_CODE);
//
hintTypeObjectHashMap.put(DecodeHintType.PURE_BARCODE, Boolean.FALSE);
Result result = new MultiFormatReader().decode(bitmap, hintTypeObjectHashMap);
retStr = result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return retStr;
}
public Map doQr(String imgpath){
long stime = System.currentTimeMillis();
Map<String,Object > map = new HashMap ();
String str = null;
try {
str = decodeQr(imgpath);
map.put("result",str);
map.put("status","success");
} catch (Exception e) {
e.printStackTrace();
map.put("status","fail");
}
System.out.println(str);
long etime = System.currentTimeMillis();
long time = (etime - stime);
System.out.printf("执行时长:%d 毫秒.",time);
map.put("time",time);
return map;
}
@PostMapping("/upload")
public Map upload(@RequestParam("imgFile") MultipartFile file, @RequestParam("imgName") String name) throws Exception {
// 设置上传至项目文件夹下的uploadFile文件夹中,没有文件夹则创建
File dir = new File("uploadFile");
if (!dir.exists()) {
dir.mkdirs();
}
String filename =dir.getAbsolutePath() + File.separator + System.currentTimeMillis()+".png";
file.transferTo(new File(filename));
return doQr(filename);
}
@RequestMapping("qr")
public Map
qr(HttpServletRequest request, HttpServletResponse response)
{
String imgpath = request.getParameter("imgpath");
//
String type = request.getParameter("type");
//
Map map = new HashMap();
return doQr(imgpath);
//
}
}
最后
以上就是粗暴发夹为你收集整理的Java 解析二维码demo的全部内容,希望文章能够帮你解决Java 解析二维码demo所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复