I'm working on JavaScript code to upload, preview, and download image. currently I have done upload and preview code. after that, How to download it?
<section class="upload" id="upload">
<h3>UPLOAD</h3>
<div class="container">
<div class="row">
<canvas id="c" class="p-3" >Here's the canvas.</canvas>
<br>
<input type="file" id="infile" accept = "image/*" onchange="handleFiles(this.files)">
<p><img id="output" /></p>
<button onclick="blurimg()" class="btnbl">Blur Image</button>
<br>
</div>
</div>
</section>
//Canvas creating with image
document.getElementById('infile').onchange = function(e) {
var img = new Image();
img.onload = draw;
img.onerror = failed;
img.src = URL.createObjectURL(this.files[0]);
};
function draw() {
var canvas = document.getElementById('c');
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0,0);
}
function failed() {
console.error("The provided file couldn't be loaded as an Image media");
}
you can do it in HTML
check this example: https://www.w3schools.com/tags/att_a_download.asp
Untested but it would be something in the lines of:
async function downloadCanvas () {
const type = 'image/jpeg'
const quality = 1
const blob = await new Promise(rs => canvas.toBlob(rs, type, quality)
const link = document.createElement('a')
a.href = URL.createObjectURL(blob)
a.download = 'cat.jpg'
a.click()
}
If you want and support newer browser, then you can use bitmap = await createImageBitmap(file) instead of painting a <img>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.