我正在尝试使用带有七个参数的BufferedImage.getRGB方法来读取像素区域并获取它们的颜色。听起来很简单,但由于某种原因,它对我不起作用。这是一个简短的、独立的、可编译的示例:
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);
}
}
在run()方法中,我首先创建了一个非常简单的 5 x 5 像素图像,如下所示:
这很好。然后我尝试读取该图像的像素,这几乎不起作用。它只正确获取第一行像素,然后将其余像素显示为黑色。打印循环的输出是:
(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)
当我希望它完全像第一行一样时。我在这里想念什么?我尝试从头开始编写它并在getRGB调用中使用“扫描线”和“偏移”参数,但似乎没有任何效果。我在 Windows 7 上运行 Java 7,如果这有什么不同的话。