您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關(guān)vue如何實現(xiàn)將圖像文件轉(zhuǎn)換為base64的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
直入主題,上代碼(其實用的還是FileReader)
imageToBase64 (file) { var reader = new FileReader() reader.readAsDataURL(file) reader.onload = () => { console.log('file 轉(zhuǎn) base64結(jié)果:' + reader.result) this.iconBase64 = reader.result } reader.onerror = function (error) { console.log('Error: ', error) } }
<el-form-item prop="iconBase64"> <img :src="iconBase64" v-show="isShow" /> </el-form-item>
<script> methods: { //異步執(zhí)行 imageUrlToBase64() { //一定要設(shè)置為let,不然圖片不顯示 let image = new Image(); //解決跨域問題 image.setAttribute('crossOrigin', 'anonymous'); let imageUrl = "http://img1.imgtn.bdimg.com/it/u=4012470373,3540768040&fm=26&gp=0.jpg"; image.src = imageUrl let that = this; //image.onload為異步加載 image.onload = () => { var canvas = document.createElement("canvas"); canvas.width = image.width; canvas.height = image.height; var context = canvas.getContext('2d'); context.drawImage(image, 0, 0, image.width, image.height); var quality = 0.8; //這里的dataurl就是base64類型 var dataURL = canvas.toDataURL("image/jpeg", quality);//使用toDataUrl將圖片轉(zhuǎn)換成jpeg的格式,不要把圖片壓縮成png,因為壓縮成png后base64的字符串可能比不轉(zhuǎn)換前的長! } }, } </script>
<script> data() { return { base64Datas: [], } methods: { imageUrlToBase64(){ let data = [ "https://cache.yisu.com/upload/information/20220209/112/953450.png", "https://cache.yisu.com/upload/information/20220209/112/953450.png", "https://cache.yisu.com/upload/information/20220209/112/953450.png" ] this.imageUrlToBase64(data, 1, data.length); }, //采用遞歸同步執(zhí)行 onloadImg(data, i, len) { //一定要設(shè)置為let,不然圖片不顯示 let image = new Image(); //解決跨域問題 image.setAttribute('crossOrigin', 'anonymous'); let imageUrl = "https://cache.yisu.com/upload/information/20220209/112/953450.png"; image.src = imageUrl let that = this; //image.onload為異步加載 image.onload = () => { var canvas = document.createElement("canvas"); canvas.width = image.width; canvas.height = image.height; var context = canvas.getContext('2d'); context.drawImage(image, 0, 0, image.width, image.height); var quality = 0.8; //這里的dataurl就是base64類型 var dataURL = canvas.toDataURL("image/jpeg", quality);//使用toDataUrl將圖片轉(zhuǎn)換成jpeg的格式,不要把圖片壓縮成png,因為壓縮成png后base64的字符串可能比不轉(zhuǎn)換前的長! //數(shù)組存放圖片base64 that.base64Datas.push(dataURL); //遞歸執(zhí)行圖片url轉(zhuǎn)base64 i = i + 1; if (i <= len) { that.onloadImg(data1, i, len) } } }, } </script>
感謝各位的閱讀!關(guān)于“vue如何實現(xiàn)將圖像文件轉(zhuǎn)換為base64”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。