3

If I have a java.awt.Image object in hand, how can I get a byte array of the image data?


If I had the subclass BufferedImage I could do this:

ByteArrayOutputStream baos = new ByteArrayOutputStream() ;
ImageIO.write( thumbnail , "jpeg" , baos ) ;
baos.flush();
final byte[] bytes = baos.toByteArray() ;

…where ImageIO.write takes an RenderedImage — an interface implemented by BufferedImage but not implemented by its superclass java.awt.Image.

Unfortunately, I do not have a BufferedImage or RenderedImage. After having called getScaledInstance on my original BufferedImage object to get a reduced thumbnail image, I have only a java.awt.Image object in hand. I am trying to get a byte array of the data in that java.awt.Image object.

6
  • 1
    Draw the image to a BufferedImage - for example ;) Commented Oct 28, 2019 at 0:18
  • Looks like a better way to go is to use a library such as imgscalr or java-image-scaling rather than the outmoded and troublesome java.awt.Image.getScaledInstance route I was using when I posted this Question. Commented Oct 28, 2019 at 8:14
  • For discussion about the problems with java.awt.Image.getScaledInstance, see The Perils of Image.getScaledInstance() Blog posted 2007-2015 by Chris Adamson. Commented Oct 28, 2019 at 8:21
  • You don’t have to use getScaledInstance. You can use a draw method that scales, or, when your source is a BufferedImage, you can use RescaleOp. Commented Oct 28, 2019 at 13:51
  • @VGR RescaleOp "scales" color sample values (making them lighter, darker etc), it does not change image dimensions. For that, use AffineTransformOp. Otherwise, good advice. I'd still use a library like imgscalr to get good quality thumbnails though... :-) Commented Oct 28, 2019 at 14:31

1 Answer 1

-1

You can make a new BufferedImage object, then get its graphics object by calling .getGraphics() on that, and then draw your image into it, using .drawImage on the graphics object, and then convert the BufferedImage to a PNG or JPG.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.