最近用到一些圖片相關的操做,記錄一下筆記。javascript
場景: 獲取到一個file類型的圖片,若是直接在html中預覽?這裏就是利用html5的新特性,將圖片轉換爲Base64的形式顯示出來。有兩種方法:html
<!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]
let fileUrl = window.URL.createObjectURL(file)
$img.src = fileUrl
img.onload = function () {
// 手動回收
URL.revokeObjectURL(fileUrl)
}
}
}
</script>
</body>
</html>
複製代碼
當選擇圖片後,生成的img src相似"blob:null/4304d4f3-c13b-43e8-83f6-8c80426520ff"
,能正常顯示圖片。前端
<!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==
,可以正常顯示。html5
場景: canvas畫出來的圖片,在html中的其餘地方顯示。這裏的方法也是能夠將canvas輸出爲Dataurl的來放到img標籤中。java
let imgSrc = canvas.toDataURL('image/png')
// canvas.toDataURL('image/jpeg')
複製代碼
場景: canvas生成的圖片,如何上傳到七牛雲或服務器?答案是將canvas輸出爲Blob對象,這樣就能夠像File對象同樣操做它了。canvas
canvas.toBlob(function (blobObj) {
console.log(blobObj)
})
複製代碼
場景: 獲取到的圖片是Blob格式的,如何顯示在html中?答案仍是將Blob對象轉換爲DataUrl的形式。api
canvas.toBlob(function (blobObj) {
let imgSrc = window.URL.createObjectURL(blobObj)
document.getElementById('img').src = imgSrc
})
複製代碼
場景: html中一張用DataURL形式顯示出來的圖片,能夠下載到本地嗎?答案是使用一個a標籤,並設置download屬性,模擬點擊。bash
function downloadImg () {
let aLink = document.createElement('a')
aLink.download = 'fileName.png' // 文件名後綴須要和dataurl表示的相同,不然可能亂碼
aLink.href = dataUrl
aLink.click()
}
複製代碼