Saturday, 31 August 2013

java.awt.image.BufferedImage.getRBG not returning expected values

java.awt.image.BufferedImage.getRBG not returning expected values

I'm trying to use the BufferedImage.getRGB method with seven parameters to
read an area of pixels and to get their colors. Sounds simple enough, but
for some reason it just won't work for me. Here's a short, self contained,
compilable example:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BufferedImageTest extends JPanel {
BufferedImage image;
public static void main(String[] args) {
BufferedImageTest mainClass = new BufferedImageTest();
mainClass.run();
}
private void run() {
initWindow();
// Create image:
image = new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB);
int[] red = new int[25];
for (int i = 0; i < 25; i++)
red[i] = Color.RED.getRGB();
image.setRGB(1, 0, 3, 5, red, 0, 0);
// Read image:
int[] rgbArray = new int[25];
int w = image.getWidth();
int h = image.getHeight();
image.getRGB(0, 0, w, h, rgbArray, 0, 0);
for (int i = 0; i < rgbArray.length; i++) {
Color c = new Color(rgbArray[i]);
System.out.print("(" + c.getRed() + "," + c.getGreen() + "," +
c.getBlue() + ")");
if (i % 5 == 4)
System.out.println("");
}
}
@Override
public void paint(Graphics g) {
g.drawImage(image, 5, 5, null);
}
private void initWindow() {
JFrame frame = new JFrame();
frame.getContentPane().add(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(40, 60);
frame.setVisible(true);
}
}
In the run() method I first create a very simple 5 by 5 pixel image like
this:

That goes fine. I then try to read in the pixels of that image, and that
doesn't work almost at all. It only gets the first line of pixels
correctly, then displays the rest as black. The output of the printing
loop is:
(0,0,0)(255,0,0)(255,0,0)(255,0,0)(0,0,0)
(0,0,0)(0,0,0)(0,0,0)(0,0,0)(0,0,0)
(0,0,0)(0,0,0)(0,0,0)(0,0,0)(0,0,0)
(0,0,0)(0,0,0)(0,0,0)(0,0,0)(0,0,0)
(0,0,0)(0,0,0)(0,0,0)(0,0,0)(0,0,0)
when I would expect it to be entirely like the first line. What am I
missing here? I have tried writing it all over from the scratch and
playing with the "scanline" and "offset" parameters in the getRGB call,
but nothing seems to work. I'm running Java 7 on Windows 7, if that makes
any difference.

No comments:

Post a Comment