我發現這個腳本將圖像轉換爲黑白圖像,效果很好,但我希望能夠更好地理解代碼。我以評論的形式將我的問題放在代碼中。瞭解畫布如何將圖像轉換爲黑白圖像
任何人都可以在一個小更詳細的解釋這裏發生了什麼:
function grayscale(src){ //Creates a canvas element with a grayscale version of the color image
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var imgObj = new Image();
imgObj.src = src;
canvas.width = imgObj.width;
canvas.height = imgObj.height;
ctx.drawImage(imgObj, 0, 0); //Are these CTX functions documented somewhere where I can see what parameters they require/what those parameters mean?
var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
for(var y = 0; y < imgPixels.height; y++){
for(var x = 0; x < imgPixels.width; x++){
var i = (y * 4) * imgPixels.width + x * 4; //Why is this multiplied by 4?
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2])/3; //Is this getting the average of the values of each channel R G and B, and converting them to BW(?)
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}
}
ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
return canvas.toDataURL();
}
+1提到做「灰度」的「正確」方式。 –
即使是黑白/灰度圖像,圖像是否仍然保存爲全綵模式?如果我想要將純黑白畫布保存爲黑白圖像(小得多的文件大小),該怎麼辦? –