赞
踩
当前在做得小程序设计拍照识别,而服务器方需要前端提供图片的base64编码作为参数进行解析识别,一开始想着走原生JS的base64方法——借助canvas,当然我也试了,就在自己觉得没问题的时候,调试时终端报错了:ReferenceError: Image is not defined.
我着实懵了,也就是说Image对象实例化在小程序这边是无效的,查资料后真的很打脸,虽然人家微信不给Image用,但是人家给提供了转base64的方法。咱直接用就行了,唉,要是早一点对目标问题进行查询,早点看文档也许不用走一遭弯路喽。
我的需求:
1、图像来源:可以拍照,也可以从相册上传进行图像识别
2、后端限制:只对png、jpeg格式图片进行识别处理
- getPhoto(){
- uni.chooseMedia({
- count:1,// 限制选取图像数量
- mediaType:["image"],// 设置选取资源为图片类型
- sourceType:["album","camera"],// 设置图像来源:相册或相机
- camera:"back",// 设置相机为后置摄像头
- success:(res)=>{
- // 获取微信拿到的图片的临时地址并保存到本地
- this.photoPath=res.tempFiles[0].tempFilePath;
- // 获取当前图片信息
- uni.getImageInfo({
- src: res.tempFiles[0].tempFilePath,
- success: (image)=> {
- // 做png/jpeg的类型判断————对不同类型的图像添加不同的转换头信息
- if(image.type=='png'||image.type=='jpeg'){
- // 对符合类型的图片转换为base64类型
- uni.getFileSystemManager().readFile({// 【重点来啦】人家自提供的转码API
- filePath:image.path,// 所需转码图像路径
- encoding:"base64",// 转码类型
- success:(res)=>{
- // 生成base64
- let imageBase64='data:image/'+image.type+';base64,'+res.data;
- console.log('转base64后:',imageBase64);
- }
- })
- }else{// 友好一点,不是以上类型做出提醒
- uni.showToast({
- title:'当前只支持png/jpeg格式',
- duration:2500,
- icon:'none'
- })
- }
- }
- });
- }
- })
- },

如果看上去有些乱,可以看下面这个,也就是uni/wx提供的转码方法:
- // (由于uniapp开发所以uni打头)
- uni.getFileSystemManager().readFile({// 【重点来啦】人家自提供的转码API
- filePath:image.path,// 所需转码图像路径
- encoding:"base64",// 转码类型
- success:(res)=>{
- // 生成base64
- let imageBase64='data:image/'+image.type+';base64,'+res.data;
- console.log('转base64后:',imageBase64);
- }
- })
原生JS-canvas图像转base64的写法是这样的:(用到了jQuery的Deferred,记得引jQuery)
- let imgSrc = "";// 图片地址(可本地可网络)
- //width、height调用时传入具体像素值,控制大小 ,不传则默认图像大小
- function getBase64Image(img, width, height) {
- var canvas = document.createElement("canvas");
- canvas.width = width ? width : img.width;
- canvas.height = height ? height : img.height;
- var ctx = canvas.getContext("2d");
- ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
- var dataURL = canvas.toDataURL();
- return dataURL;
- }
-
- function getCanvasBase64(img) {
- var image = new Image();
- //至关重要-允许跨域
- image.crossOrigin = '';
- image.src = img;
- //至关重要——借用jQuery的Deferred方法
- var deferred = $.Deferred();
- if (img) {
- image.onload = function () {
- deferred.resolve(getBase64Image(image));//将base64传给done上传处理
- // document.getElementById("container2").appendChild(image);// 测试时用于页面显示
- }
- return deferred.promise();//要让onload完成后再return
- }
- }
-
- getCanvasBase64(imgSrc)
- .then(function (base64) {
- // 转成之后的就是base64了
- console.log("转base64:",base64);
- }, function (err) {
- console.log(err);
- });

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。