使用 Java 的 ImageIO 将像素数组转换为 Image 对象?

发布于 2024-07-05 15:07:29 字数 505 浏览 11 评论 0 原文

我目前正在使用以下代码将像素值数组(最初使用 java.awt.image.PixelGrabber 对象创建)转换为 Image 对象:

public Image getImageFromArray(int[] pixels, int width, int height) {
    MemoryImageSource mis = new MemoryImageSource(width, height, pixels, 0, width);
    Toolkit tk = Toolkit.getDefaultToolkit();
    return tk.createImage(mis);
}

是否可以使用 ImageIO 包中的类实现相同的结果(s) 所以我不必使用 AWT Toolkit?

Toolkit.getDefaultToolkit() 似乎不是 100% 可靠,有时会抛出 AWTError,而 ImageIO 类应该始终可用,这是为什么我有兴趣改变我的方法。

I'm currently turning an array of pixel values (originally created with a java.awt.image.PixelGrabber object) into an Image object using the following code:

public Image getImageFromArray(int[] pixels, int width, int height) {
    MemoryImageSource mis = new MemoryImageSource(width, height, pixels, 0, width);
    Toolkit tk = Toolkit.getDefaultToolkit();
    return tk.createImage(mis);
}

Is it possible to achieve the same result using classes from the ImageIO package(s) so I don't have to use the AWT Toolkit?

Toolkit.getDefaultToolkit() does not seem to be 100% reliable and will sometimes throw an AWTError, whereas the ImageIO classes should always be available, which is why I'm interested in changing my method.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

风筝在阴天搁浅。 2024-07-12 15:07:29

您可以在不使用 ImageIO 的情况下创建图像。 只需使用与像素数组内容匹配的图像类型创建 BufferedImage 即可。

public static Image getImageFromArray(int[] pixels, int width, int height) {
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            WritableRaster raster = (WritableRaster) image.getData();
            raster.setPixels(0,0,width,height,pixels);
            return image;
        }

使用 PixelGrabber 时,不要忘记在调用 getImageFromArray 之前从像素数组中提取 RGBA 信息。 handlepixelmethod 在 PixelGrabber javadoc 中。 完成此操作后,请确保 BufferedImage 构造函数中的图像类型为 BufferedImage.TYPE_INT_ARGB 。

You can create the image without using ImageIO. Just create a BufferedImage using an image type matching the contents of the pixel array.

public static Image getImageFromArray(int[] pixels, int width, int height) {
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            WritableRaster raster = (WritableRaster) image.getData();
            raster.setPixels(0,0,width,height,pixels);
            return image;
        }

When working with the PixelGrabber, don't forget to extract the RGBA info from the pixel array before calling getImageFromArray. There's an example of this in the handlepixelmethod in the PixelGrabber javadoc. Once you do that, make sure the image type in the BufferedImage constructor to BufferedImage.TYPE_INT_ARGB.

ζ澈沫 2024-07-12 15:07:29

使用栅格,即使当我使用 TYPE_INT_ARGB 创建 BufferedImage 时,我也会遇到 ArrayIndexOutOfBoundsException 。 但是,使用 BufferedImagesetRGB(...) 方法对我有用。

Using the raster I got an ArrayIndexOutOfBoundsException even when I created the BufferedImage with TYPE_INT_ARGB. However, using the setRGB(...) method of BufferedImage worked for me.

沧笙踏歌 2024-07-12 15:07:29

JavaDoc on BufferedImage.getData() 说:“一个 Raster,是图像数据的副本。”

这段代码对我有用,但我怀疑它的效率:

        // Получаем картинку из массива.
        int[] pixels = new int[width*height];
            // Рисуем диагональ.
            for (int j = 0; j < height; j++) {
                for (int i = 0; i < width; i++) {
                    if (i == j) {
                        pixels[j*width + i] = Color.RED.getRGB();
                    }
                    else {
                        pixels[j*width + i] = Color.BLUE.getRGB();
                        //pixels[j*width + i] = 0x00000000;
                    }
                }
            }

BufferedImage pixelImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);    
    pixelImage.setRGB(0, 0, width, height, pixels, 0, width);

JavaDoc on BufferedImage.getData() says: "a Raster that is a copy of the image data."

This code works for me but I doubt in it's efficiency:

        // Получаем картинку из массива.
        int[] pixels = new int[width*height];
            // Рисуем диагональ.
            for (int j = 0; j < height; j++) {
                for (int i = 0; i < width; i++) {
                    if (i == j) {
                        pixels[j*width + i] = Color.RED.getRGB();
                    }
                    else {
                        pixels[j*width + i] = Color.BLUE.getRGB();
                        //pixels[j*width + i] = 0x00000000;
                    }
                }
            }

BufferedImage pixelImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);    
    pixelImage.setRGB(0, 0, width, height, pixels, 0, width);
没企图 2024-07-12 15:07:29

我使用 java.awt.Robot 来抓取屏幕截图(或屏幕的一部分)取得了很好的成功,但要使用 ImageIO,您需要将其存储在 BufferedImage 而不是内存图像源中。 然后您可以调用 ImageIO 的一个静态方法并保存文件。 尝试类似的方法:

// Capture whole screen
Rectangle region = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capturedImage = new Robot().createScreenCapture(region);

// Save as PNG
File imageFile = new File("capturedImage.png");
ImageIO.write(capturedImage, "png", imageFile);

I've had good success using java.awt.Robot to grab a screen shot (or a segment of the screen), but to work with ImageIO, you'll need to store it in a BufferedImage instead of the memory image source. Then you can call one static method of ImageIO and save the file. Try something like:

// Capture whole screen
Rectangle region = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capturedImage = new Robot().createScreenCapture(region);

// Save as PNG
File imageFile = new File("capturedImage.png");
ImageIO.write(capturedImage, "png", imageFile);
余厌 2024-07-12 15:07:29

由于这是在 SO 上用 ImageIO 标记的投票最高的问题之一,我认为即使这个问题很旧,仍然有更好的解决方案的空间。 :-)

看看 BufferedImageFactory.java 类来自我在 GitHub 上的开源 imageio 项目。

有了它,您可以简单地写:

BufferedImage image = new BufferedImageFactory(image).getBufferedImage();

另一个好处是,在最坏的情况下,这种方法的性能(时间)与该线程中基于 PixelGrabber 的示例大致相同。 对于大多数常见情况(通常是 JPEG),速度大约是原来的两倍。 无论如何,它使用的内存更少。

附带的好处是,原始图像的颜色模型和像素布局被保留,而不是使用默认颜色模型转换为 int ARGB。 这可能会节省额外的内存。

(PS:如果有人感兴趣的话,工厂还支持子采样、感兴趣区域和进度侦听器。:-)

As this is one of the highest voted question tagged with ImageIO on SO, I think there's still room for a better solution, even if the question is old. :-)

Have a look at the BufferedImageFactory.java class from my open source imageio project at GitHub.

With it, you can simply write:

BufferedImage image = new BufferedImageFactory(image).getBufferedImage();

The other good thing is that this approach, as a worst case, has about the same performance (time) as the PixelGrabber-based examples already in this thread. For most of the common cases (typically JPEG), it's about twice as fast. In any case, it uses less memory.

As a side bonus, the color model and pixel layout of the original image is kept, instead of translated to int ARGB with default color model. This might save additional memory.

(PS: The factory also supports subsampling, region-of-interest and progress listeners if anyone's interested. :-)

情未る 2024-07-12 15:07:29

我和其他人试图应用这个问题的正确答案时遇到了同样的问题,我的 int 数组实际上得到了一个 OutOfboundException ,我修复了它,添加了一个索引,因为在此之后数组的长度必须是 widht*height*3无法获取图像,所以我修复了它,将光栅设置为图像

public static Image getImageFromArray(int[] pixels, int width, int height) {
        BufferedImage image = new BufferedImage(width, height,     BufferedImage.TYPE_INT_ARGB);
        WritableRaster raster = (WritableRaster) image.getData();
        raster.setPixels(0,0,width,height,pixels);
        image.setData(raster); 
        return image;
    }

一样,你就可以看到图像

    JFrame frame = new JFrame();
    frame.getContentPane().setLayout(new FlowLayout());
    frame.getContentPane().add(new JLabel(new ImageIcon(image)));
    frame.pack();
    frame.setVisible(true);

,如果你将图像显示在 jframe 上的标签上,就像在 imageIcon() 上设置图像 。
最后的建议你可以尝试将 Bufferedimage.TYPE_INT_ARGB 更改为与你从这种类型获得的图像相匹配的其他内容,该数组非常重要我有一个 0 和 -1 的数组,所以我使用了这种类型 BufferedImage.TYPE_3BYTE_BGR

I had the same problem of everyone else trying to apply the correct answer of this question, my int array actually get an OutOfboundException where i fixed it adding one more index because the length of the array has to be widht*height*3 after this i could not get the image so i fixed it setting the raster to the image

public static Image getImageFromArray(int[] pixels, int width, int height) {
        BufferedImage image = new BufferedImage(width, height,     BufferedImage.TYPE_INT_ARGB);
        WritableRaster raster = (WritableRaster) image.getData();
        raster.setPixels(0,0,width,height,pixels);
        image.setData(raster); 
        return image;
    }

And you can see the image if u show it on a label on a jframe like this

    JFrame frame = new JFrame();
    frame.getContentPane().setLayout(new FlowLayout());
    frame.getContentPane().add(new JLabel(new ImageIcon(image)));
    frame.pack();
    frame.setVisible(true);

setting the image on the imageIcon().
Last advice you can try to change the Bufferedimage.TYPE_INT_ARGB to something else that matches the image you got the array from this type is very important i had an array of 0 and -1 so I used this type BufferedImage.TYPE_3BYTE_BGR

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文