当前位置: 移动技术网 > IT编程>开发语言>JavaScript > Vue 图片压缩并上传至服务器功能

Vue 图片压缩并上传至服务器功能

2020年03月09日  | 移动技术网IT编程  | 我要评论

本文主要讲解基于 vue + vant ,实现移动端图片选择,并用 canvas 压缩图片,最后上传至服务器。还会封装一个工具类,方便直接调用。

一、工具类封装

废话不多说先上代码,封装一个 compressimageutils 工具类:

**
 * 图片压缩工具类
 * 最大高度和最大宽度都为 500,如果超出大小将等比例缩放。
 *
 * 注意可能出现压缩后比原图更大的情况,在调用的地方自己判断大小并决定上传压缩前或压缩后的图到服务器。
 */
// 将base64转换为blob
export function convertbase64urltoblob(urldata) {
 let arr = urldata.split(',')
 let mime = arr[0].match(/:(.*?);/)[1]
 let bstr = atob(arr[1])
 let n = bstr.length
 let u8arr = new uint8array(n)
 while (n--) {
  u8arr[n] = bstr.charcodeat(n)
 }
 return new blob([u8arr], {type: mime})
}

// 压缩图片
export function compressimage(path) {
 //最大高度
 const maxheight = 500;
 //最大宽度
 const maxwidth = 500;
 return new promise((resolve, reject) => {
  let img = new image();
  img.src = path;
  img.onload = function () {
   const originheight = img.height;
   const originwidth = img.width;
   let compressedwidth = img.height;
   let compressedheight = img.width;
   if ((originwidth > maxwidth) && (originheight > maxheight)) {
    // 更宽更高,
    if ((originheight / originwidth) > (maxheight / maxwidth)) {
     // 更加严重的高窄型,确定最大高,压缩宽度
     compressedheight = maxheight
     compressedwidth = maxheight * (originwidth / originheight)
    } else {
     //更加严重的矮宽型, 确定最大宽,压缩高度
     compressedwidth = maxwidth
     compressedheight = maxwidth * (originheight / originwidth)
    }
   } else if (originwidth > maxwidth && originheight <= maxheight) {
    // 更宽,但比较矮,以maxwidth作为基准
    compressedwidth = maxwidth
    compressedheight = maxwidth * (originheight / originwidth)
   } else if (originwidth <= maxwidth && originheight > maxheight) {
    // 比较窄,但很高,取maxhight为基准
    compressedheight = maxheight
    compressedwidth = maxheight * (originwidth / originheight)
   } else {
    // 符合宽高限制,不做压缩
   }
   // 生成canvas
   let canvas = document.createelement('canvas');
   let context = canvas.getcontext('2d');
   canvas.height = compressedheight;
   canvas.width = compressedwidth;
   context.clearrect(0, 0, compressedwidth, compressedheight);
   context.drawimage(img, 0, 0, compressedwidth, compressedheight);
   let base64 = canvas.todataurl('image/*', 0.8);
   let blob = convertbase64urltoblob(base64);
   // 回调函数返回blob的值。也可根据自己的需求返回base64的值
   resolve(blob)
  }
 })
}

定义的最大宽度和最大高度均为 500,如果图片的宽高至少有一个超出了 500,都会被 **等比例 **压缩,不用担心变形。可以根据自己项目需要改变 maxwidth 和  maxheight 。

这里直接把压缩的最大高度和最大宽度写死为 500 了,没有在调用时传。因为一个项目压缩的逻辑和大小一般都一致的,没必要在每次调用的时候传。当然如果想写的灵活一点,可以在 compressimage 方法里再把 maxwidth 、 maxheight 和压缩质量传上。

compressimage 方法返回的是 blob 值,根据服务端接口需要可以改为返回 base64,只需将 resolve(blob) 改为 resolve(base64) 即可。

注意一点,对于有些宽高没到 500,且分辨率很小的图片,压缩之后可能比之前还大。猜测可能是 canvas 生成的图片分辨率要比原来高一些,所以最终的图片比压缩前更大。可以在调用的地方加个判断,如果压缩完的大小比原图小,就上传压缩后的图片;如果如果压缩完的大小比原图大,就上传原图。

二、如何使用

将 compressimageutils 引入到目标文件,然后调用  compressimage 方法,即可在回调里获得压缩后的结果。注意  compressimage 方法返回的是 promise。

省略其他无关代码,只保留跟压缩图片和上传相关的:

<template>
 <div>
  <van-uploader v-model="filelist" :after-read="afterread" />
 </div>
</template>
<script>
 import {compressimage} from '../../utils/compressimageutils'
 export default {
  components: {},
  methods: {
   //读取完图片后
   afterread(file) {
    console.log('afterread------', file);
    this._compressanduploadfile(file);
   },
   //压缩图片上传
   _compressanduploadfile(file) {
    compressimage(file.content).then(result => {
     console.log('压缩后的结果', result); // result即为压缩后的结果
     console.log('压缩前大小', file.file.size);
     console.log('压缩后大小', result.size);
     if (result.size > file.file.size){
      console.log('上传原图');
      //压缩后比原来更大,则将原图上传
      this._uploadfile(file.file, file.file.name);
     } else {
      //压缩后比原来小,上传压缩后的
      console.log('上传压缩图');
      this._uploadfile(result, file.file.name)
     }
    })
   },
   //上传图片
   _uploadfile(file, filename) {
    let params = new formdata();
    params.append("file", file, filename);
    this.$api.uploadimage(params).then(res => {
     console.log('uploadimage', res);
   //上传成功,写自己的逻辑
    }).catch(err => {
     console.log('err', err);
    });
   }, 
  }
 }
</script>

在返回结果中加了层判断,压缩后比原来更大,则将原图上传;压缩后比原来小,上传压缩后的。解决压缩后比原图更大的情况。

this.$api.uploadimage(params) 是调用封装的 api 方法,如下:

//上传图片
 uploadimage(params){
  return axios.post(`${base}/api/v1/file`, params, {
   headers: {'content-type': 'multipart/form-data'}
  })
 },

三、使用效果

先上传一个非常大的,尺寸为 6016 × 4016,16.8m 的大图,看输出日志,压缩后大小仅为 260k 左右。此时判断压缩后比压缩前小,上传压缩图到服务器。

 

再看个尺寸 300 × 300,12k 的小图,压缩前大小是 11252,压缩后大小是 93656,大了很多。此时判断压缩后比压缩前更大,上传的是原图。

 

总结:这个工具类对大图的压缩效果很明显,不管多大的图,压缩之后基本不会超过 300k。但对某些小图可能出现压缩完反而更大的情况。在调用的地方加层压缩后和压缩前大小的比较判断,会完美解决这个问题。

当然也可以在工具类内部判断,但个人觉得跟业务逻辑相关的代码还是不要放在公用的工具类比较好。

总结

以上所述是小编给大家介绍的vue 图片压缩并上传至服务器功能,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网