Create a BufferedImage from an int Array

2

I have a one-dimensional array that contains the colors of an image, where each interval of 3 positions is represented by the color of a pixel (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] . From this array, I'm creating a BufferedImage, trying to pass this array as a 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 created image only generates pixels with blue color, I would like to know if it is possible to pass this array as a parameter or if I have to set pixel by pixel the new image.

    
asked by anonymous 13.03.2017 / 00:16

1 answer

1

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

The problem of just being blue should have something to do with the Alpha channel. Colors are encoded in a single int (not three or four, considering Alpha / transparency), so you have to do a conversion. I made an adjustment in 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 by 50 times):

    
13.03.2017 / 02:43