前端圖片canvas,file,blob,DataURL等格式轉換


將file轉化成base64

  • 方法一:利用URL.createObjectURL()
 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <title>base</title>
 5 </head>
 6 <body>
 7 <input type="file" name="" id="file">
 8 <img src="" id="img">
 9 <script type="text/javascript">
10     window.onload = function () {
11         let $img = document.getElementById('img')
12         file.onchange = function (e) {
13             console.log(e.target.files[0])
14             let file = e.target.files[0]
15             let fileUrl = window.URL.createObjectURL(file)
16             $img.src = fileUrl
17             img.onload = function () {
18                 // 手動回收
19                 URL.revokeObjectURL(fileUrl)
20             }
21         }
22     }
23 </script>
24 </body>
25 </html>

當選擇圖片后,生成的img src類似"blob:null/4304d4f3-c13b-43e8-83f6-8c80426520ff",能正常顯示圖片。

  • 方法二: 利用FileReader.readAsDataURL()
<!DOCTYPE html>
<html>
<head>
    <title>base</title>
</head>
<body>
<input type="file" name="" id="file">
<img src="" id="img">
<script type="text/javascript">
    window.onload = function () {
        let $img = document.getElementById('img')
        file.onchange = function (e) {
            console.log(e.target.files[0])
            let file = e.target.files[0]
            const fr = new FileReader(file)
            fr.readAsDataURL(file)
            fr.onload = function () {
                 $img.src = this.result
            }
        }
    }
</script>
</body>
</html>

img標簽的src將會是像這樣:"data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAABkCAYAAADDhn8LAAA==,能夠正常顯示。

 

canvas 轉為DataURL

 

場景: canvas畫出來的圖片,在html中的其他地方顯示。這里的方法也是可以將canvas輸出為Dataurl的來放到img標簽中。

 

let imgSrc = canvas.toDataURL('image/png')
// canvas.toDataURL('image/jpeg')

canvas轉為blob對象

 

場景: canvas生成的圖片,如何上傳到七牛雲或服務器?答案是將canvas輸出為Blob對象,這樣就可以像File對象一樣操作它了。

 

 canvas.toBlob(function (blobObj) {
    console.log(blobObj)
})
 canvas.toBlob還有兩個參數一個是名稱name,另一個是壓縮質量quality 0~1

Blob對象顯示圖片

 

場景: 獲取到的圖片是Blob格式的,如何顯示在html中?答案還是將Blob對象轉換為DataUrl的形式。

 

canvas.toBlob(function (blobObj) {
    let imgSrc = window.URL.createObjectURL(blobObj)
    document.getElementById('img').src = imgSrc
})

下載DataURL表示的圖片

 

場景: html中一張用DataURL形式顯示出來的圖片,可以下載到本地嗎?答案是使用一個a標簽,並設置download屬性,模擬點擊。

function downloadImg () {
    let aLink = document.createElement('a')
    aLink.download = 'fileName.png' // 文件名后綴需要和dataurl表示的相同,否則可能亂碼
    aLink.href = dataUrl
    aLink.click()
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM