我有一个将图像颜色更改为黑白的功能,我想在使用按钮更改后下载图像
function preview(file) {
if (file) {
var reader = new FileReader()
reader.readAsDataURL(file);
reader.onloadend = function () {
document.getElementById("img").src = reader.result;
document.getElementById("img").style.filter = "grayscale(100%)";
}
}
}
<input type="file" accept="image/*" onchange="preview(this.files[0])"/>
<br>
<img id="img"/>
答案 0 :(得分:0)
您可以使用Javascript完成此操作
首先,使用CSS在Canvas中绘制图像,然后以编程方式创建anchor
标记并为其分配点击
function preview(file) {
if (file) {
var reader = new FileReader()
reader.readAsDataURL(file);
reader.onloadend = function() {
document.getElementById("img").src = reader.result;
var canvas = document.getElementById('cnimage');
var ctx = canvas.getContext('2d');
ctx.filter = "grayscale(100%)"
var img = document.getElementById("img");
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
anchor = document.createElement('a');
document.body.appendChild(anchor);
anchor.download = name;
var data = canvas.toDataURL("image/png");
anchor.href = data;
anchor.click();
ctx.clearRect(0, 0, canvas.width,canvas.height);
}
}
}
<input type="file" accept="image/*" onchange="preview(this.files[0])"/>
<br>
<img id="img"/>
<canvas id="cnimage" height="400px" width="400px"></canvas>
答案 1 :(得分:0)
这里有两件事:
我们必须先等待img.onload
函数再执行操作
我们需要将滤镜从图像复制到画布上
function downloadImage(imgNode, name = 'fileName', format = 'png') {
const canvas = document.createElement('canvas');
canvas.width = imgNode.width;
canvas.height = imgNode.height;
const context = canvas.getContext('2d');
context.filter = getComputedStyle(imgNode).filter; // Add the image filter to the canvas
imgNode.setAttribute('crossOrigin', 'anonymous');
context.drawImage(imgNode, 0, 0, canvas.width, canvas.height);
const url = canvas.toDataURL(`image/${format}`);
const anchor = document.createElement('a');
anchor.href = url;
anchor.download = `${name}.${format}`;
document.body.appendChild(anchor);
anchor.click();
}
function preview(file) {
if (file) {
var reader = new FileReader()
reader.readAsDataURL(file);
reader.onloadend = function () {
var img = new Image();
img.src = reader.result;
img.style.filter = "grayscale(100%)"; // Apply the CSS filter on the image
document.body.appendChild(img); // Display image
img.onload = function() {
downloadImage(img); // Download image
img.onload = null; // Prevent onload function called twice
};
}
}
}
<input type="file" accept="image/*" onchange="preview(this.files[0])"/>
<br/>