Java: BufferedImage to byte array and back

后端 未结 2 1056
南方客
南方客 2020-11-27 17:14

I see that a number of people have had a similar problem, however I\'m yet to try find exactly what I\'m looking for.

So, I have a method which reads an input image

相关标签:
2条回答
  • 2020-11-27 17:30

    Note that calling close or flush will do nothing, you can see this for yourself by looking at their source/doc:

    Closing a ByteArrayOutputStream has no effect.

    The flush method of OutputStream does nothing.

    Thus use something like this:

    ByteArrayOutputStream baos = new ByteArrayOutputStream(THINK_ABOUT_SIZE_HINT);
    boolean foundWriter = ImageIO.write(bufferedImage, "jpg", baos);
    assert foundWriter; // Not sure about this... with jpg it may work but other formats ?
    byte[] bytes = baos.toByteArray();
    

    Here are a few links concerning the size hint:

    • Java: Memory efficient ByteArrayOutputStream
    • jpg bits per pixel

    Of course always read the source code and docs of the version you are using, do not rely blindly on SO answers.

    0 讨论(0)
  • 2020-11-27 17:32

    This is recommended to convert to a byte array

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(img, "jpg", baos);
    byte[] bytes = baos.toByteArray();
    
    0 讨论(0)
提交回复
热议问题