java.awt.image.BufferedImage.getRBG未返回预期值

时间:2013-08-31 17:03:53

标签: java image-processing bufferedimage

我正在尝试使用带有七个参数的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像素图像,如下所示:

example image

没关系。然后我尝试读取该图像的像素,这几乎根本不起作用。它只能正确获取第一行像素,然后将其余部分显示为黑色。打印循环的输出是:

(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 调用中使用“scanline”和“offset”参数进行播放,但似乎没有任何效果。我在Windows 7上运行Java 7,如果这有任何区别的话。

1 个答案:

答案 0 :(得分:3)

指定正确的scansize以获取所有行:

image.getRGB(0, 0, w, h, rgbArray, 0, w);

点击此处:BufferedImage#setRGB()BufferedImage#getRGB()