[英]Image download using JavaScript
我正在使用 JavaScript 代碼來上傳、預覽和下載圖像。 目前我已經完成了上傳和預覽代碼。 之后,如何下載呢?
<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");
}
你可以在HTML
檢查這個例子: https://www.w3schools.com/tags/att_a_download.asp
未經測試,但它會是這樣的:
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()
}
如果您想要並支持更新的瀏覽器,那么您可以使用bitmap = await createImageBitmap(file)而不是繪制<img>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.