欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue+elementUI(el-upload)圖片壓縮,默認(rèn)同比例壓縮操作

 更新時間:2020年08月10日 11:34:22   作者:辣姐什么鬼  
這篇文章主要介紹了vue+elementUI(el-upload)圖片壓縮,默認(rèn)同比例壓縮操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

如下所示:

這個需求針對用戶上傳手機拍攝照片等不便修改圖片大小的情況,我們允許上傳10M以內(nèi)的圖片由前端對圖片進(jìn)行壓縮再傳給后臺存儲,結(jié)合elementUI的el-upload組件實現(xiàn)圖片上傳功能(簡單來說就是用戶是老大)

1、提取出壓縮方法,放在公共方法.js文件里

/** 圖片壓縮,默認(rèn)同比例壓縮
 * @param {Object} fileObj
 * 圖片對象
 * 回調(diào)函數(shù)有一個參數(shù),base64的字符串?dāng)?shù)據(jù)
 */
export function compress(fileObj, callback) {
 try {
 const image = new Image()
 image.src = URL.createObjectURL(fileObj)
 image.onload = function() {
  const that = this
  // 默認(rèn)按比例壓縮
  let w = that.width
  let h = that.height
  const scale = w / h
  w = fileObj.width || w
  h = fileObj.height || (w / scale)
  let quality = 0.7 // 默認(rèn)圖片質(zhì)量為0.7
  // 生成canvas
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  // 創(chuàng)建屬性節(jié)點
  const anw = document.createAttribute('width')
  anw.nodeValue = w
  const anh = document.createAttribute('height')
  anh.nodeValue = h
  canvas.setAttributeNode(anw)
  canvas.setAttributeNode(anh)
  ctx.drawImage(that, 0, 0, w, h)
  // 圖像質(zhì)量
  if (fileObj.quality && fileObj.quality <= 1 && fileObj.quality > 0) {
  quality = fileObj.quality
  }
  // quality值越小,所繪制出的圖像越模糊
  const data = canvas.toDataURL('image/jpeg', quality)
  // 壓縮完成執(zhí)行回調(diào)
  const newFile = convertBase64UrlToBlob(data)
  callback(newFile)
 }
 } catch (e) {
 console.log('壓縮失敗!')
 }
}
function convertBase64UrlToBlob(urlData) {
 const bytes = window.atob(urlData.split(',')[1]) // 去掉url的頭,并轉(zhuǎn)換為byte
 // 處理異常,將ascii碼小于0的轉(zhuǎn)換為大于0
 const ab = new ArrayBuffer(bytes.length)
 const ia = new Uint8Array(ab)
 for (let i = 0; i < bytes.length; i++) {
 ia[i] = bytes.charCodeAt(i)
 }
 return new Blob([ab], { type: 'image/png' })
}

2、el-upload上傳組件

<el-form-item ref="uploadElement" prop="picUrl" class="upload-img-form" label-width="0">
 <el-upload
 ref="uploadxls"
 class="avatar-uploader upload-img"
 :disabled="disabled"
 :auto-upload="false"
 :style="{height:'66px', backgroundImage:'url(' + dialogImageUrl + ')', backgroundRepeat:'no-repeat', backgroundPosition:'center', backgroundSize: '100%,100%'}"
 action="aaa"
 ::limit="1"
 :show-file-list="false"
 :on-change="handlePictureCardPreview"
 :before-upload="beforeupload"
 accept="image/png,image/gif,image/jpg,image/jpeg"
 >
 <!--<img v-if="dialogImageUrl" :src="dialogImageUrl" class="avatar">-->
 <i v-if="!dialogImageUrl" class="el-icon-plus avatar-uploader-icon" />
 <!--<i v-show="!dialogImageUrl" class="upload-icon" />
 <div v-show="!dialogImageUrl" slot="tip" class="el-upload__text upload__tip">上傳實景圖</div>-->
 <div v-if="showDelete" class="remove-img"><i class="el-icon-delete" @click.stop="removeImg" /></div>
 <div slot="tip" class="el-upload__tip">
  <p><span style="color:#F5222D;">*</span>上傳樓宇實景圖</p>
  <p>支持:.jpg .png .gif格式 建議比例:16:9,小于10M</p>
 </div>
 </el-upload>
</el-form-item>

3、主要在handlePictureCardPreview方法里調(diào)用壓縮方法

先在當(dāng)前vue頁面import公共js文件

import { compress } from '@/utils'

然后

// 圖片預(yù)覽
handlePictureCardPreview(file) {
 const _that = this
 const isLt10M = file.size / 1024 / 1024 < 10
 if (!isLt10M) {
 this.$message.error('上傳圖片大小不能超過 10M!')
 return false
 } else {
 this.dialogImageUrl = URL.createObjectURL(file.raw)
 compress(file.raw, function(val) {
  _that.theForm.picUrl = val
  _that.imgFile = val
  _that.showDelete = true
  _that.$refs['addBuildingForm'].validateField('picUrl')
 })
 }
}

compress傳入file.raw作為fileObj

這樣只要上傳圖片就進(jìn)行圖片壓縮

補充知識:element upload限制上傳圖片尺寸、大小、比例

我就廢話不多說了,大家還是直接看代碼吧~

// 上傳前判斷
  public async beforeUpload(file: any) {
    const is1M = file.size / 1024 / 1024 < 3; // 限制小于3M
    if (!is1M) {
      this.$message.error('圖片尺寸限制最小為270 x 270,大小不可超過3MB,比例為1:1');
      return false;
    } else {
      const isSize = new Promise((resolve, reject) => {
        const width = 270;
        const height = 270;
        const _URL = window.URL || window.webkitURL;
        const img = new Image();
        img.onload = () => {
          const valid = img.width >= width && img.height >= height && img.width === img.height;
          valid ? resolve() : reject();
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          this.$message.error('圖片尺寸限制最小為270 x 270,大小不可超過3MB,比例為1:1');
          return Promise.reject();
        },
      );
      return isSize;
    }
  }

看了很多還不如自己擼一個

以上這篇vue+elementUI(el-upload)圖片壓縮,默認(rèn)同比例壓縮操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論