Create a Bufferedimage from an int Array

Asked

Viewed 230 times

2

I have a one-dimensional array that contains the colors of an image, where at each 3-position interval the color of a pixel is represented (R,G,B):

int[] cores = {255, 0, 0, 0, 255, 0, 0, 0, 255};

In this array I would have 3 pixels, where the first would be [255, 0, 0] (Red), the second [0, 255, 0] (Green) and finally [0, 0, 255] (Blue). From this array, I am creating a Bufferedimage, trying to pass this array as parameter, but I did not understand the utility of the offset and scansize parameters (the last two parameters passed to setRGB).

BufferedImage rendered = new BufferedImage(getWidth(), getHeight(), this.imageType);

rendered.setRGB(0, 0, this.getWidth(), this.getHeight(), this.getData(), 0, this.getWidth());

The image created generates only pixels with the blue color, I wonder if it is possible to pass this array as parameter or if I will have to set pixel by pixel the new image.

1 answer

1


Do not use setRGB, because although it works, it will be less efficient (because it will be setting one pixel at a time). Use the getRaster().getDataBuffer() image to have an access to the pixel array directly.

The problem of being only blue must have something to do with the Alpha channel. The colors are encoded in a single int (and not in three or four, considering Alpha/transparency), so you have to do a conversion. I made an adjustment to the code to be efficient and give the correct result:

    int[] cores = { 255, 0, 0, 0, 255, 0, 0, 0, 255,
                    255, 0, 0, 0, 255, 0, 0, 0, 255,
                    255, 0, 0, 0, 255, 0, 0, 0, 255,
                    255, 0, 0, 0, 255, 0, 0, 0, 255,
                    255, 0, 0, 0, 255, 0, 0, 0, 255
                                                    };

    // Converte array de origem em um array RGB
    int argb[] = new int[cores.length/3];
    for(int i=0; i<cores.length; i+=3) {
       argb[i/3] = -16777216; // 255 alpha
       argb[i/3] += (((int) cores[i] & 0xff) << 16); // vermelho
       argb[i/3] += (((int) cores[i+1] & 0xff) << 8); // verde
       argb[i/3] += ((int) cores[i+2] & 0xff); // azul
    }

    int larguraImagem = 3;
    int alturaImagem = 5;

    BufferedImage bi = new BufferedImage(larguraImagem, alturaImagem, BufferedImage.TYPE_INT_ARGB );
    final int[] a = ( (DataBufferInt) bi.getRaster().getDataBuffer() ).getData();
    System.arraycopy(argb, 0, a, 0, argb.length);

The output will be a 3x5 image with a line of each color (amplified below at 50 times):

Saída do programa

Browser other questions tagged

You are not signed in. Login or sign up in order to post.