欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue实现压缩图片预览并上传功能(promise封装)

程序员文章站 2023-11-20 12:38:10
本文实例为大家分享了vue实现压缩图片预览并上传的具体代码,供大家参考,具体内容如下 主要用到filereader、canvas 以及 formdata 这三个h5的ap...

本文实例为大家分享了vue实现压缩图片预览并上传的具体代码,供大家参考,具体内容如下

主要用到filereader、canvas 以及 formdata 这三个h5的api

过程大致分为三步:

用户使用input file上传图片的时候,用filereader读取用户上传的图片数据(base64格式)
把图片数据传入img对象,然后将img绘制到canvas上,再调用canvas.todataurl对图片进行压缩
获取到压缩后的base64格式图片数据,转成二进制塞入formdata,再通过xmlhttprequest提交formdata。

模板:

<template>
 <div class="image-box">
  <input type="file" accept="image/*" @change="imagehandle">
  <img ref="upimg"/>
 </div>
</template>

获取图片数据

methods: {
   //监听input file的change事件
  imagehandle(e) {
   //**这个是必不可少的,在下面的reader.onload中this就不再指vm了**
   let that = this;
   let maxsize = 100 * 1024;
   let files = e.srcelement.files;
   if (!files.length) return; //文件长度大于0
   if (!/^image\//.test(files[0].type)) return; //必须是图片才处理
   if (!window.filereader) return; //支持filereader
   //创建filereader对象
   let reader = new filereader();
   reader.readasdataurl(files[0]); //将图片转成base64格式
   reader.onload = function() {
    let result = this.result;
    let img = new image();
    img.src = result;
    let formdata = new formdata();
    if (this.result.length <= maxsize) {
     that.$refs.upimg.src = result; //预览图片
     img = null;
     //上传图片
     formdata.append("image", that._upload(result, files[0].name, files[0].type));
     that.$store.dispatch("uploadimage", formdata)
        .then(data => {
          if (data === 1) {
          that.$toast("上传成功", "success");
          } else if (data === -1) {
          that.$toast("图片为空", "error");
          } else {
          that.$toast("上传失败", "error");
          }
        })
        .catch(error => that.$toast("上传失败", "error"));
    } else {
     img.onload = function() {
      //压缩图片
      let data = that._compress(img);
      //图片预览
      that.$refs.upimg.src = data;
      //上传图片
      formdata.append("image", that._upload(data, files[0].name, files[0].type));
      that.$store.dispatch("uploadimage", formdata)
          .then(data => {
            if (data === 1) {
            that.$toast("上传成功", "success");
            } else if (data === -1) {
            that.$toast("图片为空", "error");
            } else {
            that.$toast("上传失败", "error");
            }
          })
          .catch(error => that.$toast("上传失败", "error"));
     };
    }
   };
  },

压缩图片

在ios中,canvas绘制图片是有两个限制的:

首先是图片的大小,如果图片的大小超过两百万像素,图片也是无法绘制到canvas上的,调用drawimage的时候不会报错,但是你用todataurl获取图片数据的时候获取到的是空的图片数据。

再者就是canvas的大小有限制,如果canvas的大小大于大概五百万像素(即宽高乘积)的时候,不仅图片画不出来,其他什么东西也都是画不出来的。

应对第一种限制,处理办法就是瓦片绘制了。瓦片绘制,也就是将图片分割成多块绘制到canvas上,我代码里的做法是把图片分割成100万像素一块的大小,再绘制到canvas上。

而应对第二种限制,我的处理办法是对图片的宽高进行适当压缩,我代码里为了保险起见,设的上限是四百万像素,如果图片大于四百万像素就压缩到小于四百万像素。四百万像素的图片应该够了,算起来宽高都有2000x2000了。

如此一来就解决了ios上的两种限制了。

除了上面所述的限制,还有两个坑,一个就是canvas的todataurl是只能压缩jpg的,当用户上传的图片是png的话,就需要转成jpg,也就是统一用canvas.todataurl(‘image/jpeg', 0.1) , 类型统一设成jpeg,而压缩比就自己控制了。

另一个就是如果是png转jpg,绘制到canvas上的时候,canvas存在透明区域的话,当转成jpg的时候透明区域会变成黑色,因为canvas的透明像素默认为rgba(0,0,0,0),所以转成jpg就变成rgba(0,0,0,1)了,也就是透明背景会变成了黑色。解决办法就是绘制之前在canvas上铺一层白色的底色。

_compress(img) {
   let canvas = document.createelement("canvas");
   let ctx = canvas.getcontext("2d");
   //瓦片
   let tcanvas = document.createelement("canvas");
   let tctx = tcanvas.getcontext("2d");
   let initsize = img.src.length;
   let width = img.width;
   let height = img.height;
   //如果图片大于四百万像素,计算压缩比并将大小压至400万以下
   let ratio;
   if ((ratio = (width * height) / 4000000) > 1) {
    ratio = math.sqrt(ratio);
    widht /= ratio;
    height /= ratio;
   } else {
    ratio = 1;
   }
   canvas.width = width;
   canvas.height = height;
   //铺底色
   ctx.fillstyle = "#fff";
   ctx.fillrect(0, 0, canvas.width, canvas.height);
   //如果图片像素大于100万则使用瓦片绘制
   let count;
   if ((count = (width * height) / 1000000) > 1) {
    count = ~~(math.sqrt(count) + 1); //计算要分成多少瓦片,~~在这里表示取整
    //计算每块瓦片的宽高
    let nw = ~~(width / count);
    let nh = ~~(height / count);
    tcanvas.width = nw;
    tcanvas.height = nh;
    for (let i = 0; i < count; i++) {
     for (let j = 0; j < count; j++) {
      tctx.drawimage(
       img, i * nw * ratio, j * nh * ratio, nw * ratio,nh * ratio, 0, 0, nw,nh
      );
      ctx.drawimage(tcanvas, i * nw, j * nh, nw, nh);
     }
    }
   } else {
    ctx.drawimage(img, 0, 0, canvas.width, canvas.height);
   }
   //进行压缩
   let ndata = canvas.todataurl("image/jpeg", 0.3);
   tcanvas.width = tcanvas.height = canvas.width = canvas.height = 0;
   return ndata;
  },

上传

完成图片压缩后,就可以塞进formdata里进行上传了,先将base64数据转成字符串,再实例化一个arraybuffer,然后将字符串以8位整型的格式传入arraybuffer,再通过blobbuilder或者blob对象,将8位整型的arraybuffer转成二进制对象blob,再将blob转为file对象

_upload(data, name, type) {
   let text = window.atob(data.split(",")[1]);
   let buffer = new arraybuffer(text.length);
   let ubuffer = new uint8array(buffer);
   let pecent = 0,
    loop = null;

   for (var i = 0; i < text.length; i++) {
    ubuffer[i] = text.charcodeat(i);
   }

   let builder =
    window.blobbuilder ||
    window.webkitblobbuilder ||
    window.mozblobbuilder ||
    window.msblobbuilder;
   let blob;
   if (builder) {
    var builder = new builder();
    builder.append(buffer);
    blob = builder.getblob(type);
   } else {
    blob = new window.blob([ubuffer], { type: type });
   }
   // blob 转file
   var fileofblob = new file([blob], name, { type: type });
   return fileofblob;
  }
 }

将图片压缩上传封装到一个js文件里

const uploadimg = {
  imagehandle(files, maxsize, imgdom) {
    let that = this;
    let formdata = new formdata();
    let reader = new filereader();
    reader.readasdataurl(files[0]); //将图片转成base64格式
    //reader.onload是异步,要用到promise对象将值返回出去
    return new promise((resolved, rejected) => {
      reader.onload = function () {
        let result = this.result;
        let img = new image();
        img.src = result;
        if (this.result.length <= maxsize) {
          imgdom.src = result;
          img = null;
          formdata.append("image", that._upload(result, files[0].name, files[0].type));
          resolved(formdata);
        } else {
          img.onload = function () {
            let data = that._compress(img);
            imgdom.src = data;
            formdata.append("image", that._upload(data, files[0].name, files[0].type));
            resolved(formdata);
          };
        }
      };
    })

  },
  _compress(img) {
    let canvas = document.createelement("canvas");
    let ctx = canvas.getcontext("2d");
    //瓦片
    let tcanvas = document.createelement("canvas");
    let tctx = tcanvas.getcontext("2d");
    let width = img.width;
    let height = img.height;
    //如果图片大于四百万像素,计算压缩比并将大小压至400万以下
    let ratio;
    if ((ratio = (width * height) / 4000000) > 1) {
      ratio = math.sqrt(ratio);
      widht /= ratio;
      height /= ratio;
    } else {
      ratio = 1;
    }
    canvas.width = width;
    canvas.height = height;
    //铺底色
    ctx.fillstyle = "#fff";
    ctx.fillrect(0, 0, canvas.width, canvas.height);
    //如果图片像素大于100万则使用瓦片绘制
    let count;
    if ((count = (width * height) / 1000000) > 1) {
      count = ~~(math.sqrt(count) + 1); //计算要分成多少瓦片
      //计算每块瓦片的宽高
      let nw = ~~(width / count);
      let nh = ~~(height / count);
      tcanvas.width = nw;
      tcanvas.height = nh;
      for (let i = 0; i < count; i++) {
        for (let j = 0; j < count; j++) {
          tctx.drawimage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
          ctx.drawimage(tcanvas, i * nw, j * nh, nw, nh);
        }
      }
    } else {
      ctx.drawimage(img, 0, 0, canvas.width, canvas.height);
    }
    //进行最小压缩
    let ndata = canvas.todataurl("image/jpeg", 0.3);
    tcanvas.width = tcanvas.height = canvas.width = canvas.height = 0;
    return ndata;
  },
  _upload(data, name, type) {
    let text = window.atob(data.split(",")[1]);
    let buffer = new arraybuffer(text.length);
    let ubuffer = new uint8array(buffer);

    for (var i = 0; i < text.length; i++) {
      ubuffer[i] = text.charcodeat(i);
    }

    let builder =
      window.blobbuilder ||
      window.webkitblobbuilder ||
      window.mozblobbuilder ||
      window.msblobbuilder;
    let blob;
    if (builder) {
      var builder = new builder();
      builder.append(buffer);
      blob = builder.getblob(type);
    } else {
      blob = new window.blob([ubuffer], { type: type });
    }
    // blob 转file
    var fileofblob = new file([blob], name, { type: type });
    return fileofblob;
  }
}

export default uploadimg

调用代码

import uploadimg from "../../util/uploadimg";

methods: {
  imagehandle(e) {
   let maxsize = 100 * 1024;
   let imgdom = this.$refs.upimg;
   let files = e.srcelement.files;
   if (!files.length) return; //文件长度大于0
   if (!/^image\//.test(files[0].type)) return; //必须是图片才处理
   if (!window.filereader) return; //支持filereader

   if (this.docentry === "" || this.lineid === "") {
    this.$toast("请填写完整信息", "error");
    return;
   }
   // let formdata = new formdata();
   uploadimg.imagehandle(files, maxsize, imgdom).then(formdata => {
    formdata.append("docentry", this.docentry);
    formdata.append("lineid", this.lineid);
    formdata.append("action", "productionlistimage");
    this.$store
     .dispatch("uploadimage", formdata)
     .then(data => {
      if (data === 1) {
       this.$toast("上传成功", "success");
      } else if (data === -1) {
       this.$toast("图片为空", "error");
      } else {
       this.$toast("上传失败", "error");
      }
     })
     .catch(error => this.$toast("上传失败", "error"));
   });
  }
 }

参考链接:移动端利用h5实现压缩图片上传功能

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。