Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BufferedImage Raster Data to BufferedImage

here's my code:

byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
WritableRaster raster = newImage.getRaster();
raster.setDataElements(0, 0, image.getWidth(), image.getHeight(), pixels);
newImage.setData(raster);
ImageIO.write(newImage, "jpg", new File("newimage.jpg"));

This code looks right to me and should do what I want. It gets the image's pixel data, then uses it to create a new image which should look exactly the same as the original image. However, the image that is saved has different colors than the original. Why?

Eventually, I'll need to manipulate the pixel bytes but for now, I don't know why it's giving me a different image.

like image 847
Altherat Avatar asked Jan 31 '26 01:01

Altherat


1 Answers

This post may be of help java buffered image created with red mask

It seems to be a common problem with ImageIO so its best to use Toolkit instead.

like image 87
Scott Pearson Avatar answered Feb 01 '26 14:02

Scott Pearson