Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating PNG file from int Array of RGB data

Tags:

java

image

I am getting the int array from png image how I will convert this to bufferdimage or creating new PNG file ?

int[] pixel = new int[w1*h1];
        int i = 0;
        for (int xx = 0; xx < h1; xx++) {
            for (int yy = 0; yy < w1; yy++) {
                        pixel[i] = img.getRGB(yy, xx);
                        i++;
                }
         }
like image 437
Hassan Bendouj Avatar asked Oct 21 '22 17:10

Hassan Bendouj


1 Answers

If you have an array of integers which are packed RGB values, this is the java code to save it to a file:

int width = 100;
int height = 100;
int[] rgbs = buildRaster(width, height);

DataBuffer rgbData = new DataBufferInt(rgbs, rgbs.length);

WritableRaster raster = Raster.createPackedRaster(rgbData, width, height, width,
    new int[]{0xff0000, 0xff00, 0xff},
    null);

ColorModel colorModel = new DirectColorModel(24, 0xff0000, 0xff00, 0xff);

BufferedImage img = new BufferedImage(colorModel, raster, false, null);

String fname = "/tmp/whatI.png";
ImageIO.write(img, "png", new File(fname));
System.out.println("wrote to "+fname);

The reason for the arrays 0xff0000, 0xff00, 0xff is that the RGB bytes are packed with blue in the least significant byte. If you pack your ints different, alter that array.

like image 72
Mutant Bob Avatar answered Oct 23 '22 10:10

Mutant Bob