封装上传图片大于2M按比例压缩上传

1.封装的js文件

import {baseUrl, imgBaseUrl, captchaWebKey} from '@/config/env'
import {msgToast} from '@/config/utils.js'

const local = {}
//base64 转 Blob 格式 和file格式---引用于:http://www.45fan.com/article.php?aid=19122395289136679857867305
local.base64UrlToBlob = function (urlData) {
  let arr = urlData.split(','),
    mime = arr[0].match(/:(.*?);/)[1], // 去掉url的头,并转化为byte
    bstr = atob(arr[1]), // 处理异常,将ascii码小于0的转换为大于0
    n = bstr.length,
    u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  // 转blob
  // return new Blob([u8arr], {type: mime})
  let filename = Date.parse(new Date()) + '.jpg'
  // 转file
  return new File([u8arr], filename, {type: mime})
}
/*
 压缩图片
 file:文件(类型是图片格式),
 obj:文件压缩后对象width, height, quality(0-1)
 callback:容器或者回调函数
 ---引用于:http://www.45fan.com/article.php?aid=19122395289136679857867305
*/
local.photoCompress =  function (file, obj, callback) {
  let that = this
  let ready = new FileReader()
  /* 开始读取指定File对象中的内容. 读取操作完成时,返回一个URL格式的字符串. */
  ready.readAsDataURL(file)
  ready.onload = function () {
    let re = this.result
    that.canvasDataURL(re, obj, callback) // 开始压缩
  }
},
/* 利用canvas数据化图片进行压缩 */
/* 图片转base64 
---引用于:http://www.45fan.com/article.php?aid=19122395289136679857867305*/
local.canvasDataURL =  function (path, obj, callback) {
  let img = new Image()
  img.src = path
  img.onload = function () {
    let that = this // 指到img
    // 默认按比例压缩
    let w = that.width,
      h = that.height,
      scale = w / h
    w = obj.width || w
    h = obj.height || (w / scale)
    let quality = 0.2 // 默认图片质量为0.7
    // 生成canvas
    let canvas = document.createElement('canvas')
    let ctx = canvas.getContext('2d')
    // 创建属性节点
    let anw = document.createAttribute('width')
    anw.nodeValue = w
    let anh = document.createAttribute('height')
    anh.nodeValue = h
    canvas.setAttributeNode(anw)
    canvas.setAttributeNode(anh)
    ctx.drawImage(that, 0, 0, w, h)
    // 图像质量
    if (obj.quality && obj.quality >= 1 && obj.quality < 0) {
      quality = obj.quality
    }
    // quality值越小,所绘制出的图像越模糊
    let base64 = canvas.toDataURL('image/jpeg', quality)
    // 回调函数返回base64的值
    callback(base64)
  }
},

2.main.js中引入

import localGlobal from './config/global'
Vue.prototype.gb = localGlobal

3.上传图片页面

<div class="userImg" @click="tipUpload">
	<span>头像:</span>
	<img :src="gb.imgPath(memberInfo.avatar_url, require('@/images/personCenter/imgBg.png'))" class="person-head-img" alt=" ">
	<i class="icon fa fa-angle-right"></i>
</div>
methods: {
	uploadImg(){
      let fileObj = $("input[name='headUpload']")[0].files[0]
      this.changeAvatar(fileObj)
    },
    tipUpload(){
      $("input[name='headUpload']").click()
    },
    //上传图片
    async upAddUserImg (fileRaw) {
      let token = getStore('access_token')
      let res = await updateAvatar(fileRaw, token)
      if (res.ret_code === 200) {
        this.memberInfo.avatar_url = res.result.image_url
        this.imageUrl = URL.createObjectURL(fileRaw)
        // this.userInfo.avatar_url = this.imageUrl
      }
    },
    changeAvatar (file) {// 更换头像
      let fileRaw = file
      let self = this
      const isJPG = fileRaw.type == 'image/jpg' || fileRaw.type == 'image/jpeg' || 		fileRaw.type == 'image/png'
      const isLt2M = fileRaw.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$toast.fail('个人头像只能是 JPG/PNG 格式!')
        return ;
      }
      if (!isLt2M) {
        self.gb.photoCompress(fileRaw, { // 调用压缩图片方法---引用于:http://www.45fan.com/article.php?aid=19122395289136679857867305
          quality: 0.2
        }, function (base64Codes) {
          // console.log("压缩后:" + base.length / 1024 + " " + base);
          let bl = self.gb.base64UrlToBlob(base64Codes)
          // file.append('file', bl, 'file_' + Date.parse(new Date()) + '.jpg') // 文件对象
          self.upAddUserImg(bl) // 请求图片上传接口
        })
        // this.$toast.fail('个人头像大小不能超过 2MB!')
        // return ;
      }
      if (isJPG && isLt2M) {
        this.upAddUserImg(fileRaw)
      }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值