int数组到BufferedImage

时间:2013-01-19 16:02:21

标签: java bufferedimage pixels

我正在使用Robot类制作printcreen,并将BufferedImage转换为int数组。然后我想将int数组转换回bufferedimage,但这会产生错误。这是我的代码:

Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
BufferedImage printscreen = robot.createScreenCapture(new Rectangle(screen));
int[] pixels = ((DataBufferInt) printscreen.getRaster().getDataBuffer()).getData();

BufferedImage image = new BufferedImage(screen.width, screen.height, BufferedImage.TYPE_INT_RGB);
WritableRaster raster = (WritableRaster) image.getRaster();
raster.setPixels(0, 0, screen.width, screen.height, pixels);

但我收到错误:ArrayIndexOutOfBoundsException: 2073600,但为什么?

我在这一行得到例外:

raster.setPixels(0, 0, screen.width, screen.height, pixels);

编辑:如果我将第二个bufferedimage类型更改为TYPE_BYTE_GRAY,它会工作。

5 个答案:

答案 0 :(得分:12)

int[] bitMasks = new int[]{0xFF0000, 0xFF00, 0xFF, 0xFF000000};
SinglePixelPackedSampleModel sm = new SinglePixelPackedSampleModel(
        DataBuffer.TYPE_INT, width, height, bitMasks);
DataBufferInt db = new DataBufferInt(pixels, pixels.length);
WritableRaster wr = Raster.createWritableRaster(sm, db, new Point());
BufferedImage image = new BufferedImage(ColorModel.getRGBdefault(), wr, false, null);

答案 1 :(得分:1)

更改为:

getRaster().getPixels(0, 0, screen.width, screen.height, pixels)

它有效!无论如何,谢谢你的帮助

答案 2 :(得分:0)

当您尝试访问索引处超出数组大小的元素时,会发生ArrayIndexOutOfBounds异常。在这种情况下,您将数组传递给setPixels方法,因此其javadocs不会显式检查数组的边界或大小。所以你应该在调用该方法之前明确地这样做。 e.g。

    if(x >= 0 && x < arr.length) {
        // some code
    }

这是WritableRaster使用的SampleModel类的相关代码。

    public int[] getPixels(int x, int y, int w, int h,
                           int iArray[], DataBuffer data) {

        int pixels[];
        int Offset=0;

        if (iArray != null)
            pixels = iArray;
        else
            pixels = new int[numBands * w * h];

        for (int i=y; i<(h+y); i++) {
            for (int j=x; j<(w+x); j++) {
                for(int k=0; k<numBands; k++) {
                    pixels[Offset++] = getSample(j, i, k, data);
                }
            }
        }

    return pixels;
}

答案 3 :(得分:0)

设置pixels时,raster.setPixels(0, 0, screen.width, screen.height, pixels);width*height*3的尺寸应为BufferedImage.TYPE_INT_RGB

答案 4 :(得分:0)

BufferedImage image = new BufferedImage(screen.width*3, screen.height,BufferedImage.TYPE_INT_RGB);
WritableRaster raster = (WritableRaster) image.getRaster();

raster.setPixels(0, 0, screen.width*3, screen.height, pixels);