Convert file to BLOB
Using the URL. CreateObjectURL ()
let $img = document.getElementById('img')
file.onchange = function (e) {
let file = e.target.files[0]
let fileUrl = window.URL.createObjectURL(file)
$img.src = fileUrl
img.onload = function () {
// Manually reclaim
URL.revokeObjectURL(fileUrl)
}
}
Copy the code
After an image is selected, the generated IMG SRC similar to “blob: NULL / 4304D4F3-C13B-43E8-83F6-8C80426520FF “is displayed normally.
Convert file to DataURL
Using FileReader. ReadAsDataURL ()
let $img = document.getElementById('img')
file.onchange = function (e) {
console.log(e.target.files)
let file = e.target.files[0]
const fr = new FileReader(file)
fr.readAsDataURL(file)
fr.onload = function () {
$img.src = this.result
}
}
Copy the code
Canvas to DataURL
Images drawn on canvas are displayed elsewhere in THE HTML. The method here can also put the Canvas output as Dataurl into the IMG tag.
let imgSrc = canvas.toDataURL('image/png')
// canvas.toDataURL('image/jpeg')
Copy the code
Canvas becomes bloB object
Print the Canvas as a Blob object so you can manipulate it like a File object
canvas.toBlob(function (blobObj) {
Console. log(blobObj) //blobObj is a BLOB object (class file)
})
Copy the code
Blob objects display pictures
Again, if you have a BLOb object, you can also use url.createObjecturl () to convert it
canvas.toBlob(function (blobObj) {
Console. log(blobObj) //blobObj is a BLOB object (class file)
let imgSrc = window.URL.createObjectURL(blobObj)
document.getElementById('img').src = imgSrc
})
Copy the code
DataURL download method:
function downloadImg () {
let aLink = document.createElement('a')
aLink.download = 'fileName.png'// The filename suffix must be the same as the dataURL, otherwise it may be garbled
aLink.href = dataUrl
aLink.click()
}
Copy the code