[英]Javascript - how to greyscale an image using this code?
I'm having another problem with the Image processing app.我在使用图像处理应用程序时遇到了另一个问题。 There's calculations in my workbook:
我的工作簿中有计算:
f(x.y) = (max(R, G, B) + min(R, G, B)) / 2
And that's for the average for the most prominent and least prominent colours.这是最突出和最不突出颜色的平均值。
f(x.y) = (0.21 R + 0.72 G + 0.07 B)
And that's for the Luminosity, weighted average.这是亮度,加权平均值。
f(x.y) = R + G + B) / 3
And that's for the average, but I've done that already.这是平均水平,但我已经这样做了。
Here's my code again.这是我的代码。 I'm sorry about this.
我很抱歉这件事。
var mySrcImg = new Image ();
mySrcImg.crossOrigin = "";
mySrcImg.onload = test;
mySrcImg.src = "Your image";
function test () {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.fillStyle = "rgb(0,200,0)";
context.fillRect (0, 0, 800, 800);
// Copy the image to the canvas
context.drawImage (mySrcImg, 0, 0);
// Get your image data
var myImageData;
myImageData = context.getImageData(0, 0, canvas.width, canvas.height);
// Loop over each pixel and invert the colours
var pixelComponents = myImageData.data;
var n = pixelComponents.length;
for (var i = 0; i < n; i += 4) {
// One pixel:
var average = (Math.max(pixelComponents[i ], pixelComponents[i+1],
pixelComponents[i+2]) + Math.min(pixelComponents[i ],
pixelComponents[i+1], pixelComponents[i+2])) / 2;
pixelComponents[i ]; // red
pixelComponents[i+1]; // green
pixelComponents[i+2]; // blue
// i+3 is alpha (the fourth element)
}
// Draw the ImageData object at the given (x,y) coordinates
context.putImageData(myImageData, 0, 0);
document.getElementById("srcImgDiv").appendChild(mySrcImg);
}
!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My Image Processing App</title>
</head>
<body>
<h1 id="MyHeader">Image Processing App</h1>
<p><b>Original Image:</b></p>
<div id='srcImgDiv'></div>
<p><br></p>
<p><b>Converted Image:</b></p>
<canvas id="canvas" width="800" height="800"> </canvas>
<p><br></p>
My question is: how can I make it greyscal?我的问题是:我怎样才能使它成为灰度? They've put:
他们放了:
var average = (Math.max(pixelComponents[i ], pixelComponents[i+1],
pixelComponents[i+2]) + Math.min(pixelComponents[i ],
pixelComponents[i+1], pixelComponents[i+2])) / 2;
For the greyscaling.对于灰度。
Any help would be greatly appreciated.任何帮助将不胜感激。
Thanks.谢谢。
If you want to easily grayscale an image, you could just use CSS.如果您想轻松地对图像进行灰度化,您可以使用 CSS。 It already provides a
filter: grayscale()
for you.它已经为您提供了一个
filter: grayscale()
。 See MDN .见MDN 。
If you can't use CSS, you should take a look at Jimp (JavaScript Image Manipulation Program) .如果你不能使用 CSS,你应该看看Jimp (JavaScript Image Manipulation Program) 。 This lets you do anything from grayscale to inversion to anything else.
这让您可以做任何事情,从灰度到反转再到其他任何事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.