I have a byte array obtained from an image using the following code.
String path = \"/home/mypc/Desktop/Steganography/image.png\";
File file = new File(path)
What you're using is the raw bytestream of a PNG image. PNG is a compressed format, where the bytestream doesn't reflect any of the pixel values directly and even changing one byte might irreversibly corrupt the file.
What you want instead is to extract the pixel data to a byte array with
byte[] pixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
Now you can modify the pixel values however you want. When you are ready to save that back to a file, convert the pixel byte array to a BufferedImage by putting your pixel array in a DataBufferByte
object and passing that to a WriteableRaster
, which you then use to create a BufferedImage
.
Your method would work for formats where the raw bytestream does directly represent the pixels, such as in BMP. However, even then you'd have to skip the first few bytes to avoid corrupting the header.