0

So, I'm trying to create an image in Java where it represents every color in the RGB spectrum. However, I'm brand new in Java (just finished my first programming course, Introduction into Java) and I'm having trouble because my loops for r, g, and b end up returning a color of whatever value they end at, for my code below (3,3,3). I need a way to return each color at each index of the picture. So at index 0 of the picture (0,0,0), index 1 (0,0,1) and so on. Here's my code right now:

public static Color rainbowColor(int colorValue, int x){
Color newColor = null;
for(int r = 0; r < colorValue; r++){
  for(int g = 0; g < colorValue; g++){
    for(int b = 0; b < colorValue; b++){
      System.out.println(x + ": " + r + "--" + g + "--" + b);
      newColor = new Color(r,g,b);
    }
  }
}
return newColor;
}

public static Color[] rainbowPixels(int colorValue, int size){
Color[] newArray = new Color[size];
for(int x = 0; x < size; x++){
  newArray[x] = Rainbow.rainbowColor(colorValue, x);
}
return newArray;
}

public static Image rainbow(){
int colorValue = 4;
int size = colorValue*colorValue*colorValue;
int width = (int)Math.sqrt(size);
int height = (int)Math.sqrt(size);
Color[] pixels = Rainbow.rainbowPixels(colorValue, size);
System.out.println(size + "," + colorValue);
return new Image(width, height, pixels);
}

Right now colorValue is set to 4 just so I'm working with a small image and running it in Powershell doesn't take forever. Also, that's all inside a class called Rainbow.java.

cybernetic.nomad
  • 6,100
  • 3
  • 18
  • 31
Sam Kent
  • 1
  • 4
  • you need to pass the `x` into `rainbowColor` and decide which color you want to give the pixel at that index, for example `return new Color(x, x, x)` or whatever specific logic you want to write there. Looping over rgb does not make sense here since you already loop over the pixels. – luk2302 Dec 07 '18 at 10:37
  • your first method is returning only ONE color, there is no way to have all colors in one... you could return all colors in an array (`colorValue*colorValue*colorValue` elements) , but probably better to create `BufferedImage` and draw all colors on it (using the Graphics from the image) – user85421 Dec 07 '18 at 10:37
  • If you draw the image first on a BufferedImage then it's fairly simple to examine the colour values at any given point in the image, if I were trying this I would first draw the image and then do something like [this](https://stackoverflow.com/questions/22391353/get-color-of-each-pixel-of-an-image-using-bufferedimages) to look up the colour value at whichever point(s) you need. – Old Nick Dec 07 '18 at 11:44
  • So, as I mentioned, I'm very new to Java. Could someone explain BufferedImage to me? – Sam Kent Dec 07 '18 at 17:35

0 Answers0