5

我正在使用Robot该类制作一个打印屏幕,并将 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);

编辑:如果我将第二个缓冲图像类型更改为 TYPE_BYTE_GRAY,它将起作用。

4

5 回答 5

14
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);
于 2013-02-21T12:05:12.420 回答
1

变成:

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

它有效!无论如何感谢您的帮助

于 2013-01-20T13:21:56.810 回答
0

ArrayIndexOutOfBounds您尝试访问超出数组大小的索引处的元素时,会发生异常。在这种情况下,您将数组传递给setPixels方法,根据其 javadocs,该方法不会显式检查数组的边界或大小。因此,您应该在调用该方法之前明确地执行此操作。例如

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

这是SampleModelWritableRaster 使用的类的相关代码。

    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;
}
于 2013-01-19T16:10:22.387 回答
0

pixelsin的大小raster.setPixels(0, 0, screen.width, screen.height, pixels);应该是width*height*3你设置的时候BufferedImage.TYPE_INT_RGB

于 2014-06-16T08:54:59.423 回答
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);
于 2014-11-08T10:17:12.370 回答