步骤
- input 输入文件
- FileReader 将文件读作 DataURL
- img 元素载入 URI
- 使用 CanvasRenderingContext2D.drawImage() 在 canvas 中绘制指定图片
- 使用 HTMLCanvasElement.toDataURL() 将图片转换成 data URI
- a 元素 download 下载图片
代码
<input id="file-input" type="file" accept="image/*">
<script>
var doc = document;
var input = doc.getElementById('file-input');
function exportImageFileFromCanvas(canvas) {
var dataURL = canvas.toDataURL('image/webp', .8);
var a = doc.createElement('a');
a.href = dataURL;
a.setAttribute('download', 'img.webp');
doc.body.appendChild(a);
a.click();
doc.body.removeChild(a);
a = null;
}
function url2canvas(url) {
return new Promise((resolve, reject) => {
const image = document.createElement('img');
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
image.onload = event => {
const img = event.target;
const height = image.naturalHeight;
const width = image.naturalWidth;
canvas.height = height;
canvas.width = width;
ctx.drawImage(img, 0, 0, width, height);
resolve(canvas);
};
image.onerror = err => {
reject(err);
};
image.src = url;
});
}
function readFileAsDataURL(file) {
return new Promise((resolve, reject) => {
const fr = new FileReader();
fr.onload = event => {
resolve(event.target.result);
};
fr.onerror = err => {
reject(err);
}
fr.readAsDataURL(file);
});
}
function handleFileChange(e) {
var files = e.target.files;
if (!files || !files.length) return;
var file = e.target.files[0];
readFileAsDataURL(file)
.then(url2canvas)
.then(exportImageFileFromCanvas);
}
input.addEventListener('change', handleFileChange);
</script>