js將圖片轉(zhuǎn)base64的兩種實(shí)現(xiàn)方法
第一種:Image + canvas
const getBase64Image = src => {
return new Promise(resolve => {
const img = new Image()
img.crossOrigin = ''
img.src = src
img.onload = function () {
const canvas = document.createElement('canvas')
canvas.width = img.width
canvas.height = img.height
const ctx = canvas.getContext('2d')
ctx?.drawImage(img, 0, 0, img.width, img.height)
const ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
const dataURL = canvas.toDataURL('image/' + ext)
resolve(dataURL)
}
})
}第二種:xhr + FileReader
const getBase64Image = src => {
return new Promise(resolve => {
let xhr = new XMLHttpRequest()
xhr.open('get', src, true)
xhr.responseType = 'blob'
xhr.onload = function () {
if (this.status == 200) {
let blob = this.response
let oFileReader = new FileReader()
oFileReader.onloadend = function (e) {
const base64 = e.target.result
resolve(base64)
}
oFileReader.readAsDataURL(blob)
}
}
xhr.send()
})
}總結(jié)
到此這篇關(guān)于js將圖片轉(zhuǎn)base64的兩種實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān)js圖片轉(zhuǎn)base64內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于javascript滾動圖片具體實(shí)現(xiàn)
這篇文章主要介紹了javascript滾動圖片具體實(shí)現(xiàn),有需要的朋友可以參考一下2013-11-11
關(guān)于HTTP傳輸中g(shù)zip壓縮的秘密探索分析
Gzip是一種流行的文件壓縮算法,現(xiàn)在的應(yīng)用十分廣泛,尤其是在Linux平臺。下面這篇文章主要給大家介紹了關(guān)于HTTP傳輸中g(shù)zip壓縮的相關(guān)資料,文中介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-01-01
javascript實(shí)現(xiàn)博客園頁面右下角返回頂部按鈕
這篇文章主要介紹了使用javascript實(shí)現(xiàn)博客園頁面右下角返回頂部按鈕的思路及源碼,非常不錯,這里推薦給小伙伴們2015-02-02
element el-input 刪除邊框的實(shí)現(xiàn)
本文主要介紹了element el-input 刪除邊框的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04
js RuntimeObject() 獲取ie里面自定義函數(shù)或者屬性的集合
取得ie 里面 自定義函數(shù)或者屬性的集合 使用RuntimeObject()實(shí)現(xiàn),需要的朋友可以參考下。2010-11-11
細(xì)數(shù)localStorage的用法及使用注意事項(xiàng)
這篇文章主要介紹了細(xì)數(shù)localStorage的用法及使用注意事項(xiàng),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04
javascript 驗(yàn)證碼生成代碼 推薦學(xué)習(xí)
非常不錯的用javascript實(shí)現(xiàn)的驗(yàn)證碼實(shí)現(xiàn)代碼。2009-07-07

