赞
踩
目录
- /**
- * url转base64
- * @param {String} url - url地址
- * 可能会存在跨域问题,可以尝试转之前在url链接后面加?v=1这种方式,跟服务器更新代码文件清缓存一个原理
- */
- urlToBase64(url) {
- return new Promise ((resolve,reject) => {
- let image = new Image();
- image.setAttribute("crossOrigin",'Anonymous');
- image.src = url;
- image.onload = function() {
- let canvas = document.createElement('canvas');
- canvas.width = this.naturalWidth || "300px";
- canvas.height = this.naturalHeight || "300px";
- // 将图片插入画布并开始绘制
- canvas.getContext('2d').drawImage(image, 0, 0);
- // result
- let result = canvas.toDataURL('image/png')
- resolve(result);
- };
- // 图片加载失败的错误处理
- image.onerror = () => {
- reject(new Error('转换失败'));
- };
- });
- },
- fileToBase64(e) {
- let file = e.target.files[0];
- let reader = new FileReader();
- //读取为base64
- reader.readAsDataURL(file)
- // 读取操作完成触发
- reader.onload = (e) => {
- let data;
- if (typeof e.target.result === 'object') {
- // 把Array Buffer转化为blob 如果是base64不需要
- data = window.URL.createObjectURL(new Blob([e.target.result])) // 转化为url
- } else {
- data = e.target.result;
- }
- // 因为调用了readAsDataURL方法规定将文件读取为base64,所以data为当前选择文件的base64形式
- return data;
- }
- },
-
- fileToBase64Async(file) {
- return new Promise((resolve, reject) => {
- let reader = new FileReader();
- reader.readAsDataURL(file);
- reader.onload = (e) => {
- resolve(e.target.result);
- };
- });
- },
- parseBase64(base64) {
- let arr = base64.split(","),
- mime = arr[0].match(/:(.*?);/)[1];
- return {
- mime,
- data: arr[1],
- };
- },
- base64ToUint8Array(base64) {
- let parsedBase64 = this.parseBase64(base64);
- let bstr = atob(parsedBase64.data);
- let n = bstr.length;
- let u8arr = new Uint8Array(n);
- while (n--) {
- u8arr[n] = bstr.charCodeAt(n);
- }
- return u8arr;
- },
- base64ToFile(base64, fileName) {
- let file = null;
- // 浏览器兼容
- if (window.File != undefined) {
- let parsedBase64 = this.parseBase64(base64);
- let u8arr = this.base64ToUint8Array(base64);
- file = new File([u8arr], fileName, {
- type: parsedBase64.mime,
- });
- } else {
- file = this.blobToFile(base64ToBlob(base64));
- }
- return file;
- }
- dataURLtoFile(dataUrl, fileName){
- var arr = dataUrl.split(','), mime = arr[0].match(/:(.*?);/)[1],
- bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
- while(n--){
- u8arr[n] = bstr.charCodeAt(n);
- }
- return new File([u8arr], fileName, {type:mime});
- }
- function base64ToArrayBuffer(base64) {
- base64 = base64.replace(/^data\:([^\;]+)\;base64,/gmi, '')
- var binary = atob(base64)
- var len = binary.length
- var buffer = new ArrayBuffer(len)
- var view = new Uint8Array(buffer)
- for (var i = 0; i < len; i++) {
- view[i] = binary.charCodeAt(i)
- }
- return buffer
- }
-
- base64ToBlob(base64Val) {
- const arr = base64Val.split(',');
- // 注意base64的最后面中括号和引号是不转译的
- const _arr = arr[1].substring(0,arr[1].length-2);
- const mime = arr[0].match(/:(.*?);/)[1],
- bstr =atob(_arr),
- n = bstr.length,
- u8arr = new Uint8Array(n);
- while (n--) {
- u8arr[n] = bstr.charCodeAt(n);
- }
- return new Blob([u8arr], {
- type: mime
- });
- }
- blobToFile(blobData) {
- let date = new Date();
- blobData.lastModifiedDate = date;
- blobData.lastModified = date.getTime();
- blobData.name = blobData.type.replace("/", ".");
- return blobData;
- },
- //压缩图片
- export function compressImg(file,target = {}){
- var files,name = file.name;
- var fileSize = parseFloat(parseInt(file['size'])/1024/1024).toFixed(2);
- var read = new FileReader();
- read.readAsDataURL(file);
- return new Promise(function(resolve, reject){
- read.onload = function (e) {
- var img = new Image();
- img.src = e.target.result;
- img.onload = function(){
- //默认按比例压缩
- var w = target.width || "200px",
- h = target.height || "200px";
- //生成canvas
- var canvas = document.createElement('canvas');
- var ctx = canvas.getContext('2d');
- var base64;
- // 创建属性节点
- canvas.setAttribute("width", w);
- canvas.setAttribute("height", h);
- ctx.drawImage(this, 0, 0, w, h);
- if(fileSize<1){
- //如果图片小于一兆 那么不执行压缩操作
- base64 = canvas.toDataURL(file['type'], 1);
- }else if(fileSize>1&&fileSize<2){
- //如果图片大于1M并且小于2M 那么压缩0.5
- base64 = canvas.toDataURL(file['type'], 0.5);
- }else{
- //如果图片超过2m 那么压缩0.2
- base64 = canvas.toDataURL(file['type'], 0.2);
- }
- // 回调函数返回file的值(将base64编码转成file)
- files = dataURLtoFile(base64,name); //如果后台接收类型为base64的话这一步可以省略
- resolve(files)
- };
- };
- })
- };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。