Turn an array of pixels into an Image object with Java's ImageIO?

前端 未结 6 1163
粉色の甜心
粉色の甜心 2020-12-05 00:14

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:



        
6条回答
  •  抹茶落季
    2020-12-05 00:49

    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);
    

提交回复
热议问题