Base64編碼,解碼、條碼識別


前端部分(vue + vant)

  • 引入Vant、使用Vant中的Uploader組件上傳文件(支持手機拍照)
import Vue from 'vue' 
import { Uploader } from 'vant'
Vue.use(Uploader);
  • 使用Uploader上傳組件
<van-uploader>
      <van-button icon="plus" type="primary" :after-read="afterRead">上傳文件(識別條碼)</van-button>        
</van-uploader>
  • js部分、文件上傳完畢后會觸發 after-read 回調函數,獲取到對應的 file 對象
afterRead(file) {
    var self = this;
    this.upLoad(this.$baseUrl + "upload/uploadParsing", file,
    function (response) {
          if( response.msg.length >0){
                console.log(response.msg)
          }else{
                Toast.fail('識別失敗,請重新上傳條碼!',3500)
          }
    });   
 },
  • js部分、文件上傳upload函數
upLoad(url, file, func) {
    var fileBase64 =''
    // 創建Canvas對象(畫布)
    let canvas = document.createElement("canvas");
    // 獲取對應的CanvasRenderingContext2D對象(畫筆)
    let context = canvas.getContext("2d");
    // 創建新的圖片對象
    let img = new Image();
    // 指定圖片的DataURL(圖片的base64編碼數據)
    img.src = file.content;

    // 監聽瀏覽器加載圖片完成,然后進行進行繪制
    img.onload = () => {
        // 指定canvas畫布大小,該大小為最后生成圖片的大小
        canvas.width = 400;
        canvas.height = 300; 
        context.drawImage(img, 0, 0, 400, 300);

        // 將繪制完成的圖片重新轉化為base64編碼,file.file.type為圖片類型,0.92為默認壓縮質量
        file.content = canvas.toDataURL(file.file.type, 0.92);
        baseStr = file.content

        //請求后台進行解碼、解析條碼
        this.$axios.post(url,{'fileBase64Code' :baseStr})
            .then( response => {
                  func(response.data);
            })
            .catch( error => {
                  Toast.file("識別失敗,請重新上傳條碼!",3500);
            })
      };
},

后端部分(Java )

  • 添加二維碼、條形碼解析依賴 [zxing]
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.3.3</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.3.3</version>
</dependency>    
  • 添加圖片轉碼、解碼依賴 [base64]
<!-- https://mvnrepository.com/artifact/net.iharder/base64 -->
<dependency>
    <groupId>net.iharder</groupId>
    <artifactId>base64</artifactId>
    <version>2.3.8</version>
</dependency>
  • Controller
@ResponseBody
@RequestMapping(value = "/uploadParsing", method = RequestMethod.POST)
public ResponseMessage uploadParsing(@RequestBody imgUploadMessage uploadFile){
      ResponseMessage rm=new ResponseMessage(); 
      try {
            String imgStr = uploadFile.getFileBase64Code().substring(uploadFile.getFileBase64Code().indexOf(",")+1);
            Decoder decoder = Base64.getDecoder();
            byte[] base = decoder.decode(imgStr);
            for (int i = 0; i < base.length; ++i) {
            if (base[i] < 0) {
                  base[i] += 256;
            }
      }

      ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(base);
      BufferedImage read = ImageIO.read( byteArrayInputStream);
            if (null==read) {
            rm.setMsg("解析失敗");
            rm.setSuccess(false);
            return rm;
      }

      BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(read);
      BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
      Map<DecodeHintType,Object> hints=new HashMap<>();
      hints.put(DecodeHintType.CHARACTER_SET,"GBK");
      hints.put(DecodeHintType.PURE_BARCODE,Boolean.TRUE);
      hints.put(DecodeHintType.TRY_HARDER,Boolean.TRUE);

      Result decode = new MultiFormatReader().decode(bitmap, hints);
      log.debug("條形碼的內容是:" + decode.getText());
      rm.setMsg(decode.getText());
        
      } catch (Exception e) {
            e.printStackTrace();
            rm.setSuccess(false);
            rm.setMsg("解析失敗");
      }
  return rm;
}

題外拓展

  • base64格式 開頭 [/9j/]
/9j/...AQSkZJRgABAQEAYABgAAD//gBER2VuZXJhdGVkIHdpdGggQmFyY29kZSBHZW...//2Q==


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM