vue+element 將圖片壓縮并轉(zhuǎn)換成base64上傳圖片

一:???我用的是具有拖拽功能的上傳圖片的組件:

<el-form-item label="產(chǎn)品圖片:" prop="pictureUrl" class="itemClass">
 <el-upload
 class="avatar-uploader"
 drag
 :http-request="httpRequest"
 :action="upUrl"
 :show-file-list="false"
 :on-success="handleAvatarSuccess">
 <img v-if="addRule.pictureUrl" :src="addRule.pictureUrl" class="avatar">
 <p v-else style=" height: 20px;line-height: 20px;">
  <p v-if="!addRule.pictureUrl" style="font-size: 12px; height: 20px;line-height: 20px; position: absolute; top: 50px; color: #ccc;">點(diǎn)擊上傳,或者拖拽圖片至該位置,圖片大小2MB以內(nèi)</p>
  <i class="el-icon-plus avatar-uploader-icon"></i>
</p>
</el-upload>
</el-form-item>

二:???上傳圖片,因?yàn)橐拗茍D片的格式,還要轉(zhuǎn)換成base64,所以我用的http-request參數(shù),這個(gè)參數(shù)可以覆蓋覆蓋默認(rèn)的上傳行為,可以自定義上傳的實(shí)現(xiàn):

???圖片小的話,轉(zhuǎn)換成base64可以成功上傳,但是圖片超過1.5M的轉(zhuǎn)換成base64上傳不成功,后臺(tái)說我沒有傳給他參數(shù),我后來(lái)了解了一下,說是超過1.5M的轉(zhuǎn)換成base64有問題,所以我在轉(zhuǎn)換base64之前給進(jìn)行了壓縮。 不說了上完整的代碼。

  httpRequest (options) {
    var that = this
    // 獲取文件對(duì)象
    let file = options.file
    //判斷圖片類型
    if (file.type == 'image/jpeg' || file.type == 'image/png' || file.type == 'image/JPG') {
     var  isJPG =  true
    } else {
     isJPG =  false
    }
   // 判斷圖片大小
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isJPG) {
      this.$message.error('上傳產(chǎn)品圖片只能是 JPG/PNG/JPEG 格式!')
    }
    if (!isLt2M) {
      this.$message.error('上傳產(chǎn)品圖片大小不能超過 2MB!')
    }
   // 創(chuàng)建一個(gè)HTML5的FileReader對(duì)象
    var reader = new FileReader();
    //創(chuàng)建一個(gè)img對(duì)象
   var  img = new Image();
    let filename = options.filename
    if (file) {
      reader.readAsDataURL(file)
    }
    if (isJPG && isLt2M) {
      reader.onload = (e) => {
      let base64Str = reader.result.split(',')[1]
       img.src = e.target.result
        // base64地址圖片加載完畢后執(zhí)行
            img.onload = function () {
                // 縮放圖片需要的canvas(也可以在DOM中直接定義canvas標(biāo)簽,這樣就能把壓縮完的圖片不轉(zhuǎn)base64也能直接顯示出來(lái))
                var canvas = document.createElement('canvas');
                var context = canvas.getContext('2d');
                // 圖片原始尺寸
                var originWidth = this.width;
                var originHeight = this.height;
                // 最大尺寸限制,可通過設(shè)置寬高來(lái)實(shí)現(xiàn)圖片壓縮程度
                var maxWidth = 300,
                    maxHeight = 300;
                // 目標(biāo)尺寸
                var targetWidth = originWidth,
                    targetHeight = originHeight;
                // 圖片尺寸超過最大尺寸的限制
                if(originWidth > maxWidth || originHeight > maxHeight) {
                    if(originWidth / originHeight > maxWidth / maxHeight) {
                        // 更改寬度,按照寬度限定尺寸
                        targetWidth = maxWidth;
                        targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                    } else {
                        targetHeight = maxHeight;
                        targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                    }
                }
                //對(duì)圖片進(jìn)行縮放
                canvas.width = targetWidth;
                canvas.height = targetHeight;
                // 清除畫布
                context.clearRect(0, 0, targetWidth, targetHeight);
                // 圖片壓縮
                context.drawImage(img, 0, 0, targetWidth, targetHeight);
                /*第一個(gè)參數(shù)是創(chuàng)建的img對(duì)象;第二三個(gè)參數(shù)是左上角坐標(biāo),后面兩個(gè)是畫布區(qū)域?qū)捀?/
                //壓縮后的base64文件
                var newUrl = canvas.toDataURL('image/jpeg', 0.92);
                 that.Api.post("/app/uploadPicture",{ fileContent:newUrl})
                 .then(res => {
                  that.addRule.pictureUrl = res.data;
                })
                 .catch(err => {
                 })
            }
     }
    }
  },

親測(cè)有用,?( ′???` )比心

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1.ios高性能編程 (1).內(nèi)層 最小的內(nèi)層平均值和峰值(2).耗電量 高效的算法和數(shù)據(jù)結(jié)構(gòu)(3).初始化時(shí)...
    歐辰_OSR閱讀 30,264評(píng)論 8 265
  • 我們?yōu)槭裁匆褕D片轉(zhuǎn)換成base64代碼? base64是一種網(wǎng)絡(luò)上常用的8bit字節(jié)代碼的編碼方式,base64...
    ppmoon閱讀 23,918評(píng)論 3 53
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,653評(píng)論 19 139
  • 1、通過CocoaPods安裝項(xiàng)目名稱項(xiàng)目信息 AFNetworking網(wǎng)絡(luò)請(qǐng)求組件 FMDB本地?cái)?shù)據(jù)庫(kù)組件 SD...
    陽(yáng)明AI閱讀 16,213評(píng)論 3 119
  • 機(jī)器學(xué)習(xí)算法工程師玖富集團(tuán)北京 算法工程師捷通華聲海淀區(qū) 算法工程師騰訊北京 搜索算法工程師今日頭條海淀區(qū) 搜索算...
    CodeYangX閱讀 724評(píng)論 0 0

友情鏈接更多精彩內(nèi)容