当前位置:   article > 正文

File、URL、Base64、Blob、ArrayBuffer格式转换,图片压缩_dataurltofile

dataurltofile

目录

url 转 base64

File 转 Base64

base64转File对象 

dataURL转 File 对象

base64转ArrayBuffer对象

base64转blob

blob转File

图片压缩


url 转 base64

  1. /**
  2. * url转base64
  3. * @param {String} url - url地址
  4. * 可能会存在跨域问题,可以尝试转之前在url链接后面加?v=1这种方式,跟服务器更新代码文件清缓存一个原理
  5. */
  6. urlToBase64(url) {
  7. return new Promise ((resolve,reject) => {
  8. let image = new Image();
  9. image.setAttribute("crossOrigin",'Anonymous');
  10. image.src = url;
  11. image.onload = function() {
  12. let canvas = document.createElement('canvas');
  13. canvas.width = this.naturalWidth || "300px";
  14. canvas.height = this.naturalHeight || "300px";
  15. // 将图片插入画布并开始绘制
  16. canvas.getContext('2d').drawImage(image, 0, 0);
  17. // result
  18. let result = canvas.toDataURL('image/png')
  19. resolve(result);
  20. };
  21. // 图片加载失败的错误处理
  22. image.onerror = () => {
  23. reject(new Error('转换失败'));
  24. };
  25. });
  26. },

File 转 Base64

  1. fileToBase64(e) {
  2. let file = e.target.files[0];
  3. let reader = new FileReader();
  4. //读取为base64
  5. reader.readAsDataURL(file)
  6. // 读取操作完成触发
  7. reader.onload = (e) => {
  8. let data;
  9. if (typeof e.target.result === 'object') {
  10. // 把Array Buffer转化为blob 如果是base64不需要
  11. data = window.URL.createObjectURL(new Blob([e.target.result])) // 转化为url
  12. } else {
  13. data = e.target.result;
  14. }
  15. // 因为调用了readAsDataURL方法规定将文件读取为base64,所以data为当前选择文件的base64形式
  16. return data;
  17. }
  18. },
  19. fileToBase64Async(file) {
  20. return new Promise((resolve, reject) => {
  21. let reader = new FileReader();
  22. reader.readAsDataURL(file);
  23. reader.onload = (e) => {
  24. resolve(e.target.result);
  25. };
  26. });
  27. },

base64转File对象 

  1. parseBase64(base64) {
  2. let arr = base64.split(","),
  3. mime = arr[0].match(/:(.*?);/)[1];
  4. return {
  5. mime,
  6. data: arr[1],
  7. };
  8. },
  9. base64ToUint8Array(base64) {
  10. let parsedBase64 = this.parseBase64(base64);
  11. let bstr = atob(parsedBase64.data);
  12. let n = bstr.length;
  13. let u8arr = new Uint8Array(n);
  14. while (n--) {
  15. u8arr[n] = bstr.charCodeAt(n);
  16. }
  17. return u8arr;
  18. },
  19. base64ToFile(base64, fileName) {
  20. let file = null;
  21. // 浏览器兼容
  22. if (window.File != undefined) {
  23. let parsedBase64 = this.parseBase64(base64);
  24. let u8arr = this.base64ToUint8Array(base64);
  25. file = new File([u8arr], fileName, {
  26. type: parsedBase64.mime,
  27. });
  28. } else {
  29. file = this.blobToFile(base64ToBlob(base64));
  30. }
  31. return file;
  32. }

dataURL转 File 对象

  1. dataURLtoFile(dataUrl, fileName){
  2. var arr = dataUrl.split(','), mime = arr[0].match(/:(.*?);/)[1],
  3. bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  4. while(n--){
  5. u8arr[n] = bstr.charCodeAt(n);
  6. }
  7. return new File([u8arr], fileName, {type:mime});
  8. }

base64转ArrayBuffer对象

  1. function base64ToArrayBuffer(base64) {
  2. base64 = base64.replace(/^data\:([^\;]+)\;base64,/gmi, '')
  3. var binary = atob(base64)
  4. var len = binary.length
  5. var buffer = new ArrayBuffer(len)
  6. var view = new Uint8Array(buffer)
  7. for (var i = 0; i < len; i++) {
  8. view[i] = binary.charCodeAt(i)
  9. }
  10. return buffer
  11. }

base64转blob

  1. base64ToBlob(base64Val) {
  2. const arr = base64Val.split(',');
  3. // 注意base64的最后面中括号和引号是不转译的
  4. const _arr = arr[1].substring(0,arr[1].length-2);
  5. const mime = arr[0].match(/:(.*?);/)[1],
  6. bstr =atob(_arr),
  7. n = bstr.length,
  8. u8arr = new Uint8Array(n);
  9. while (n--) {
  10. u8arr[n] = bstr.charCodeAt(n);
  11. }
  12. return new Blob([u8arr], {
  13. type: mime
  14. });
  15. }

blob转File

  1. blobToFile(blobData) {
  2. let date = new Date();
  3. blobData.lastModifiedDate = date;
  4. blobData.lastModified = date.getTime();
  5. blobData.name = blobData.type.replace("/", ".");
  6. return blobData;
  7. },

图片压缩

  1. //压缩图片
  2. export function compressImg(file,target = {}){
  3. var files,name = file.name;
  4. var fileSize = parseFloat(parseInt(file['size'])/1024/1024).toFixed(2);
  5. var read = new FileReader();
  6. read.readAsDataURL(file);
  7. return new Promise(function(resolve, reject){
  8. read.onload = function (e) {
  9. var img = new Image();
  10. img.src = e.target.result;
  11. img.onload = function(){
  12. //默认按比例压缩
  13. var w = target.width || "200px",
  14. h = target.height || "200px";
  15. //生成canvas
  16. var canvas = document.createElement('canvas');
  17. var ctx = canvas.getContext('2d');
  18. var base64;
  19. // 创建属性节点
  20. canvas.setAttribute("width", w);
  21. canvas.setAttribute("height", h);
  22. ctx.drawImage(this, 0, 0, w, h);
  23. if(fileSize<1){
  24. //如果图片小于一兆 那么不执行压缩操作
  25. base64 = canvas.toDataURL(file['type'], 1);
  26. }else if(fileSize>1&&fileSize<2){
  27. //如果图片大于1M并且小于2M 那么压缩0.5
  28. base64 = canvas.toDataURL(file['type'], 0.5);
  29. }else{
  30. //如果图片超过2m 那么压缩0.2
  31. base64 = canvas.toDataURL(file['type'], 0.2);
  32. }
  33. // 回调函数返回file的值(将base64编码转成file)
  34. files = dataURLtoFile(base64,name); //如果后台接收类型为base64的话这一步可以省略
  35. resolve(files)
  36. };
  37. };
  38. })
  39. };
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/145183
推荐阅读
相关标签
  

闽ICP备14008679号