600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > 微信开发h5图片上传(拍照 图片压缩 IOS照片旋转)

微信开发h5图片上传(拍照 图片压缩 IOS照片旋转)

时间:2024-06-17 10:52:51

相关推荐

微信开发h5图片上传(拍照 图片压缩 IOS照片旋转)

微信开发h5图片上传

开发环境

vue.js,原生h5 input file, 微信公众号网页

依赖安装

exif-js:IOS下拍照照片的方向有问题, 需要exif-js来读取照片信息进行旋转处理;

axios: 异步请求支持

vuex: 主要用来存储进度信息,

npm install exif-js --save

photoHandle.js

这里面主要是这四个方法,具体用途看注释

import EXIF from 'exif-js'import axiexport default {/*图片上传方法* dom:获取图片的input节点* config:{* type: 提交到store的mutation,提交上传接口成功后返回的Url* maxSize:Number 有此参数时,超过maxSize KB的图片会被压缩* onload:function(e) 图片解析后的回调* isProgress:function(e) 图片上传过程的监听回调* success:function(res) 图片上传成功后接口回调* fail:function(res) 图片上传失败的回调* }* */* Orientation:'', //照片初始化角度uploadImg(){}, //解析图片,直接调用此方法会依次执行后面三个方法imageCompress(){}, //压缩图片dataURItoBlob(){}, //压缩后的base64字符串转为blob文件流对象upload(){}//ajax上传}

每个方法的具体代码和解释:

uploadImg(dom, config = {}) {//解析图片var $c = document.querySelector(dom),file = $c.files[0],param = new FormData(),reader = new FileReader(),fileSize = (file.size / 1024).toFixed(0),_this = this,configHeader = {headers: {"Content-Type": "multipart/form-data" }};EXIF.getData(file, function() {_this.Orientation = EXIF.getTag(this, 'Orientation');//reader.readAsDataURL(file);reader.onload = function(e) {if (config.maxSize && fileSize > config.maxSize) { //当存在最大体积限制 进入压缩方法_this.imageCompress(this,(data)=>{setTimeout(()=>{if (config.onload) config.onload(e);param.append("file", data);_this.upload(configHeader, param, config);},0)});} else {if (config.onload) config.onload(e);param.append("file", file);_this.upload(configHeader, param, config);}};});}

压缩方法,前端压缩采用将图片转为base64 然后用canvas绘制再压缩, 如不需要压缩可以省略转码和这个步骤,自行根据应用场景和需求进行代码调整吧。

imageCompress(file,callback) { //压缩文件const _this = this;var img = new Image();var data='';img.onload = function() {let w = this.naturalWidth,h = this.naturalHeight,resizeW = 0,resizeH = 0;//压缩设置let maxSize = { //在这里统一配置,也可以自行修改成传参width:680,//图片最大宽度height:680,//图片最大高度level:0.3 //图片保存质量};//计算缩放比例if(w > maxSize.width || h > maxSize.height){let multiple = Math.max(w / maxSize.width , h / maxSize.height);resizeW = w / multiple;resizeH = h / multiple;}else{resizeW = w;resizeH = h;}let canvas = document.createElement("canvas"),cxt = canvas.getContext('2d');//根据拍摄的角度进行图片旋转调整if (_this.Orientation == 3) {canvas.width = resizeW;canvas.height = resizeH;cxt.rotate(Math.PI);cxt.drawImage(img, 0, 0, -resizeW, -resizeH)} else if (_this.Orientation == 8) {canvas.width = resizeH;canvas.height = resizeW;cxt.rotate(Math.PI * 3 / 2);cxt.drawImage(img, 0, 0, -resizeW, resizeH)} else if (_this.Orientation == 6) {canvas.width = resizeH;canvas.height = resizeW;cxt.rotate(Math.PI / 2);cxt.drawImage(img, 0, 0, resizeW, -resizeH)} else {canvas.width = resizeW;canvas.height = resizeH;cxt.drawImage(img, 0, 0, resizeW, resizeH)}//base64,最终输出的压缩文件data = canvas.toDataURL('image/jpeg',maxSize.level);var str = _this.dataURItoBlob(data);callback(str);};img.src = file.result;// console.log(img.src.length+' 压缩前');},

dataURItoBlob: function (dataURI) { //base64转blob// console.log(dataURI.split(',')[1],'sss');var byteString = atob(dataURI.split(',')[1]);var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];var ab = new ArrayBuffer(byteString.length);var ia = new Uint8Array(ab);for (var i = 0; i < byteString.length; i++) {ia[i] = byteString.charCodeAt(i);}return new Blob([ab], { type: mimeString });},

upload(configHeader, param, config) {const _this = this;const baseUrl = 'http://yourapiaddress'; //接口上传地址_this.axios({url: baseUrl ,method: "post",header: configHeader,data: param,onUploadProgress: function(progressEvent) {//原生获取上传进度的事件if (progressEvent.lengthComputable) {//属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量//如果lengthComputable为false,就获取不到progressEvent.total和progressEvent.loadedif (config.isProgress) config.isProgress(progressEvent);}}}).then(res => {if (res.data.success) {if (config.type)mit(config.type, res.data.resultObject.url);if (config.success) config.success(res.data);} else {if (config.fail) config.fail();}}).catch(() => {if (config.fail) config.fail();});}

调用

import photoHandle from './photoHandle'upLoad() {const _this = this;photoHandle.uploadImg("#imgBtn", {maxSize: 50, //最大体积kbonload: e => {//todo 图片读取成功的处理,比如显示状态上传中},isProgress: res => {let loaded = res.loaded,total = res.total;//todo 进度处理},success: res => {//todo成功},fail: res => {// todo失败}});},

结言

理解这几个方法的作用便可分应用场景自由组合使用, 坑主要在IOS照片旋转和压缩的地方, 希望通过此文能解决您的一些问题

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。