Converting byte array to png

前端 未结 1 1488
借酒劲吻你
借酒劲吻你 2021-01-17 03:52

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)         


        
相关标签:
1条回答
  • 2021-01-17 04:28

    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.

    0 讨论(0)
提交回复
热议问题