50.4k views
5 votes
Program: Invert Filter

Write the function invertPixel(pixel) that takes a pixel array as a parameter and inverts
each color in the pixel array.

var IMAGE_WIDTH = 350;
var IMAGE_HEIGHT = 250;
var IMAGE_X = getWidth() / 2 - IMAGE_WIDTH / 2;
var IMAGE_Y = getHeight() / 2 - IMAGE_HEIGHT / 2;
\var MAX_COLOR_VALUE = 255;
// We need to wait for the image to load before modifying it
var IMAGE_LOAD_WAIT_TIME = 2000;

function invertPixel(newpixel) {
newpixel[RED] = RED - 255
newpixel[GREEN] = GREEN - 255
newpixel[BLUE] = BLUE - 255
}

function invert(image) {
for(var x = 0; x < image.getWidth(); x++) {
for (var y = 0; y < image.getHeight(); y++) {
// Get the current pixel
var pixel = image.getPixel(x, y);

// Modify the current pixel
pixel = invertPixel(pixel);

// Update the image with the modified pixel
image.setRed(x, y, pixel[RED]);
image.setGreen(x, y, pixel[GREEN]);
image.setBlue(x, y, pixel[BLUE]);
}
}
}
function start() {
// Set up the image
var image = new WebImage(IMAGE_URL);
image.setSize(IMAGE_WIDTH, IMAGE_HEIGHT);
image.setPosition(IMAGE_X, IMAGE_Y);

// Add it to the canvas
add(image);

// Wait for it to load before applying the filter
setTimeout(function(){
invert(image);
}, IMAGE_LOAD_WAIT_TIME);
}

1 Answer

2 votes

The function invertPixel(pixel) is supposed to invert the color values of a pixel. However, there is an issue in the code. Instead of inverting the color values, it is subtracting the color value from 255. To fix this, we need to subtract the color value from 255 and assign the result to the color value. Here is the corrected code:

function invertPixel(pixel) {

pixel[RED] = MAX_COLOR_VALUE - pixel[RED];

pixel[GREEN] = MAX_COLOR_VALUE - pixel[GREEN];

pixel[BLUE] = MAX_COLOR_VALUE - pixel[BLUE];

return pixel;

}

Also, the invert() function should modify the color values using the corrected invertPixel() function, like this:

function invert(image) {

for (var x = 0; x < image.getWidth(); x++) {

for (var y = 0; y < image.getHeight(); y++) {

// Get the current pixel

var pixel = image.getPixel(x, y);

// Modify the current pixel

pixel = invertPixel(pixel);

// Update the image with the modified pixel

image.setRed(x, y, pixel[RED]);

image.setGreen(x, y, pixel[GREEN]);

image.setBlue(x, y, pixel[BLUE]);

}

}

}

User Wildcard
by
7.8k points