uni-app用uni.chooseImage API调用相机或从相册中选择图片并转成base64

我的业务场景是将单据拍照后进行压缩,然后转base64,再调用百度的iOCR文字识别接口。

// 拍照
camera(){
    
    
	let that = this;
	uni.chooseImage({
    
    
	    count: 1, //默认9
	    sizeType: ['compressed'], //可以指定是原图还是压缩图,默认二者都有
	    sourceType: ['camera','album'], //从相册选择
	    success: function (res) {
    
    
			console.log('img',res)
			imgToBase64(res)
		}
	})
	
	// 图片转base64
	function imgToBase64(data){
    
    
		 plus.zip.compressImage({
    
      
			src: data.tempFilePaths[0],  
			dst: "_doc/a.jpg",  
			overwrite: true,  
			width: '1920px',  
			height:'1080px',  
			format: 'jpg',  
			quality: 100  
		  },  
		  function(e) {
    
      
			let reader = new plus.io.FileReader();  
				reader.readAsDataURL(e.target);  
				reader.onloadend = function (e) {
    
     
					//这是转成功的base64文件,需要正则去一下换行
					let base64 = e.target.result.split(',')[1].replace(/[\r\n]/g,"") 
					iOCR(base64)
				};  
		  },  
		  function(err) {
    
      
			plus.nativeUI.alert('未知错误!',function() {
    
      
			});  
		  }  
		);  
	}
	
	// iOCR文字识别
	function iOCR(image){
    
    
		uni.request({
    
    
			url:`https://aip.baidubce.com/rest/2.0/solution/v1/iocr/recognise/finance?access_token=${
      
      that.access_token}`,
			header:{
    
    
				'Content-Type':'application/x-www-form-urlencoded'
			},
			method:"POST",
			data:{
    
    
				image:image,
				// 模版id
				templateSign:that.templateSign,
			},
			success:(res)=>{
    
    
				console.log('识别结果',res)
			},
			fail:(err)=>{
    
    
				console.log('err',err)
			}
		})
	}
},

猜你喜欢

转载自blog.csdn.net/weixin_35958891/article/details/108284292