I was just wondering what the best way to read pixels from a BufferedImage
. I want the pixels contained in a int[]
.
Here is my code right now:
try {
BufferedImage img = ImageIO.read(new File("C:\\Users\\Hardish\\Pictures\\test.png"));
BufferedImage intimg = Util.convertBufferedImage(img, BufferedImage.TYPE_INT_RGB);
int[] pixels = ((DataBufferInt)intimg.getRaster().getDataBuffer()).getData();
int co = Util.randomColor(255).getRGB();
if(co < 0)
co = -co;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < pixels.length; i++){
Pixel px = new Pixel(Util.convertPixel(i, img.getWidth()), pixels[i]);
sb.append(px.toCompactString(true));
pixels[i] += co;
}
ImageIO.write(intimg, "jpg", new FileOutputStream("C:\\Users\\Hardish\\Pictures\\test.jpg"));
SaveHandler.saveCompressed(sb.toString(), "C:\\Users\\Hardish\\Pictures\\test.dat");
SaveHandler.saveString(sb.toString(), "C:\\Users\\Hardish\\Pictures\\test.sdat");
String pixDat = (String)(SaveHandler.readCompressed("C:\\Users\\Hardish\\Pictures\\test.dat"));
String[] pixs = pixDat.split(Pixel.PIXEL_SEPARATOR);
int[] pixelsRead = new int[pixs.length];
for(int i = 0; i < pixelsRead.length; i++){
pixelsRead[i] = Pixel.parseCompactPixel(pixs[i], true).val;
}
BufferedImage img2 = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
int[] pixelsW = ((DataBufferInt)img2.getRaster().getDataBuffer()).getData();
for(int i = 0; i < pixelsW.length; i++){
pixelsW[i] = pixelsRead[i];
}
ImageIO.write(img2, "jpg", new FileOutputStream("C:\\Users\\Hardish\\Pictures\\testRead.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
Here is the original:
Here is the change the pixels output:
Here is the read from file output: