Images Processing/JavaScript

Asked by At

I am trying to write a javascript program that modifies an image by putting three vertical stripes on it. A red stripe on the left one third, a green stripe in the middle and a blue stripe on the right one third.

Here is the algorithm that i am trying to implement: 1. Start with the image you want to change.

  1. Figure out the width of the image.

  2. For each pixel in the image: Get the x-coordinate for that pixel If the pixel’s x-coordinate is less than one-third of the image’s width, set the pixel’s red value to 255. If the pixel’s x-coordinate is between one-third and two-thirds of the image’s width, set the pixel’s green value to 255. If the pixel’s x-coordinate is more than two-thirds of the image’s width, set the pixel’s blue value to 255.

  3. Print the image.

    var MyImage = new SimpleImage("hilton.jpg");
    var ImgWidth = MyImage.getWidth();
    
    for (var pix of MyImage.values()){
        var Xcoordinate = pix.getX();
        var Ycoordinate = pix.getY();
        if (Xcoordinate < ImgWidth/3){
            pix.setRed(255);
        }
    
        else if (ImgWidth/3< Xcoordinate < ImgWidth/2){
            pix.setGreen(255);
        }
    
        else{ 
            Xcoordinate > ImgWidth/3;
            pix.setBlue(255);
        }
    }
    print(MyImage);
    

The red strip is coming out as expected but the green stripe is occupying the rest of the image and the blue doesn't appear at all. No error message.

2 Answers

1
rom99 On

I think your test for the green strip doesn't do what you want it to:

ImgWidth/3< Xcoordinate < ImgWidth/2

You can't chain the boolean operators that way. Probably it should be:

ImgWidth / 3 < Xcoordinate && Xcoordinate < ImgWidth / 2 

Also this line is redundant:

Xcoordinate > ImgWidth/3;

You are not assigning the result to any variable.

0
Allos111 On

Thanks very much to SkilGG. I just reviewed my test for the green strip and deleted the redundant line in the else clause. Came up with those lines and my code is now working.

    var MyImage = new 
    SimpleImage("hilton.jpg");
    var ImgWidth = MyImage.getWidth();

    for (var pix of MyImage.values()){
        var Xcoordinate = pix.getX();
        if (Xcoordinate < ImgWidth/3){
            pix.setRed(255);
        }

        else if (Xcoordinate < 2*ImgWidth/3){
            pix.setGreen(255);
        }

        else{ 
            pix.setBlue(255);
        }
    }
    print(MyImage);