vue中的base64圖片轉(zhuǎn)網(wǎng)絡(luò)URL方式
更新時(shí)間:2024年10月16日 11:02:25 作者:Juliet_xmj
在Vue中,可以直接將Base64編碼的圖片賦值給img元素的src屬性,此外,也可以通過JavaScript的URL.createObjectURL()方法將Base64轉(zhuǎn)換為Blob URL,進(jìn)而轉(zhuǎn)換為File對(duì)象,并可進(jìn)一步轉(zhuǎn)換為PNG或其他格式的圖片,這種轉(zhuǎn)換技術(shù)在前端開發(fā)中非常實(shí)用
vue base64圖片轉(zhuǎn)網(wǎng)絡(luò)URL
src支持base64圖片,正常base64圖片可以直接復(fù)制到圖片src,也可以將其轉(zhuǎn)為URL
// data
url: 'XXXXXXXX' // base64編碼
imgUrl: '' // 圖片路徑
// methods
base64ImgtoFile (dataurl, filename = 'file') {
const arr = dataurl.split(',')
const mime = arr[0].match(/:(.*?);/)[1]
const suffix = mime.split('/')[1]
const bstr = atob(arr[1])
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new File([u8arr], `${filename}.${suffix}`, {
type: mime
})
},打印得到File文件,再轉(zhuǎn)為png圖片

const img = 'data:image/png;base64,' + img this.file = this.base64ImgtoFile(img) // 得到File對(duì)象 this.imgUrl = window.webkitURL.createObjectURL(file) || window.URL.createObjectURL(file) // imgUrl圖片網(wǎng)絡(luò)路徑
base64轉(zhuǎn)url、url轉(zhuǎn)base64
// url轉(zhuǎn)base64
dataURLtoBlob(dataurl) {
return new Promise((resolve, reject) => {
let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
resolve(new Blob([u8arr], {type:mime}));
})
},
const images = await Promise.all([
this.dataURLtoBlob(this.imageUrl),
this.dataURLtoBlob(this.imageUrl2),
])
// base64轉(zhuǎn)url
dataURLtoBlobURL(dataUrl) {
return new Promise((resolve, reject) => {
let arr = dataUrl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--) {
u8arr[n] = bstr.charCodeAt(n);
}
let blob = new Blob([u8arr], {type:mime});
let url = URL.createObjectURL(blob);
resolve(url);
});
},
let url1 = await this.dataURLtoBlobURL(this.imageUrl);
let url2 = await this.dataURLtoBlobURL(this.imageUrl2);
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue使用wavesurfer.js實(shí)現(xiàn)音頻可視化的示例詳解
WaveSurfer.js是一個(gè)開源的音頻可視化庫,用于創(chuàng)建交互式、可定制的波形,本文將為大家簡單介紹了Vue如何使用wavesurfer.js實(shí)現(xiàn)音頻可視化功能,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-04-04
Vue 實(shí)現(xiàn)樹形視圖數(shù)據(jù)功能
這篇文章主要介紹了Vue 實(shí)現(xiàn)樹形視圖數(shù)據(jù)功能,利用簡單的樹形視圖實(shí)現(xiàn)的,在實(shí)現(xiàn)過程中熟悉了組件的遞歸使用,感興趣的朋友跟隨腳本之家小編一起學(xué)習(xí)吧2018-05-05
el-select 下拉框多選實(shí)現(xiàn)全選的實(shí)現(xiàn)
這篇文章主要介紹了el-select 下拉框多選實(shí)現(xiàn)全選的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
詳解Vue的組件中data選項(xiàng)為什么必須是函數(shù)
這篇文章主要給大家介紹了關(guān)于Vue的組件中data選項(xiàng)為什么必須是函數(shù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者使用Vue具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
vue使用拖拽方式創(chuàng)建結(jié)構(gòu)樹
這篇文章主要為大家詳細(xì)介紹了vue使用拖拽方式創(chuàng)建結(jié)構(gòu)樹,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-10-10

