1

When I execute this code, only the green value gets swapped. The red value remains the same. Why is that and what should I do?

Intial RGB: 90:123:92 New RGB should be: 123:90:92 Right now, I get: 90:90:92

var img = new SimpleImage("smalllion.jpg");
var pix = img.getPixel(0,0);
print(img)
print("orginal rgb " + pix)

function swapRedGreen(pixel){
    for(var pixel of img.values()){
        var newG = pixel.getRed();
        pixel.setGreen(newG)
        var newR = pixel.getGreen();
        pixel.setRed(newR);
    }
}
swapRedGreen("smalllion.jpg")
print(img)
var pix1 = img.getPixel(0,0);
print(pix1)
panr9
  • 13
  • 3
  • you read green just after you changed it to the red value – Yurii Feb 10 '18 at 23:33
  • something tells me that manipulating directly pixeldata this operation will be 10x faster. Good start: https://stackoverflow.com/questions/8751020/how-to-get-a-pixels-x-y-coordinate-color-from-an-image – Nuthinking Feb 10 '18 at 23:38

2 Answers2

1

The reason is when you called var newR = pixel.getGreen();, the green is already being set to the red color. Instead store the original green & red to variables at the beginning.

Try this instead:

function swapRedGreen(pixel) {
    for (var pixel of img.values()) {
        var oldRed = pixel.getRed();
        var oldGreen = pixel.getGreen();

        pixel.setGreen(oldRed);
        pixel.getRed(oldGreen);
    }
}
Shuwn Yuan Tee
  • 5,578
  • 6
  • 28
  • 42
0

Issue: This might be because in line 9, you assign pixel the green value, which you then retrieve in line 10 to convert into red. You are essentially converting red --> green, and then green --> red.

Solution: Try switching line 9 and 10.

  • Ok, so that is how it works. In my initial code, the value gets stored in green then, the red stores the new green value. thanks. – panr9 Feb 11 '18 at 00:15