Search code examples
javargbpixeljavax.imageio

Draw image with only grayscale value array in java


I am starting to learn image processing in Java, here is my question: I have an array of values (I assume pixel values) for a graycale image, one for each (x,y) position. The image is 96x96. An example of these values is:

238 
236 
237
238
240
240 
239 
241
241
243
240
239 
231 
212
190
173 
148
122
104

My question is, how can I draw this image by just using these pixel values? The reason I ask this, is because usually I have the original image available, and I extract the red, green and blue component values for each pixel. But in this case, if I want to do something like this:

// after for loop in which I do  
//Color newColor = new Color(red,green,blue);
//image.setRGB(x,y,newColor.getRGB());

JFrame frame = new JFrame();
JLabel lblimage = new JLabel(new ImageIcon(image));
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(lblimage);

// add more components here
frame.add(mainPanel);
frame.setVisible(true);

I can't create a Color class because I don't have the components for the red, blue and green values of each pixel.

What am I doing wrong? Maybe I'm mistaking concepts, if so I apologize. Thank you so much.


Solution

  • Greyscale means that all three color components - R, G, and B - are the same. So, use the greyscale values as the color components:

    Color newColor = new Color(pixelValue[x][y], pixelValue[x][y], pixelValue[x][y]);
    image.setRGB(x, y, newColor.getRGB());