Search code examples
javaimagestreamjframebytearrayoutputstream

How do I display an image in JFrame from only a ByteArrayOutputStream?


I have a ByteArrayOutputStream representation of a JPEG image (although I could use GIF or PNG if that would work better). I would like to display this on the form, such as in a label or image object. I am constrained by the fact that I cannot write the image to a file, I can only ever store it in memory.


Solution

  • One of the (easiest) possibilites to solve the problem is creating a ByteArrayInputStream and then passing it to ImageIO:

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    // save the image to the output stream
    ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
    BufferedImage image = ImageIO.read(input);