2

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • 1
    Draw the image to a `BufferedImage` - [for example](https://stackoverflow.com/questions/32714751/how-to-convert-image-to-bufferedimage-in-java/32715012#32715012) ;) – MadProgrammer Oct 28 '19 at 00:18
  • Looks like a better way to go is to use a library such as [`imgscalr`](https://github.com/rkalla/imgscalr) or [`java-image-scaling`](https://github.com/mortennobel/java-image-scaling) rather than the outmoded and troublesome `java.awt.Image.getScaledInstance` route I was using when I posted this Question. – Basil Bourque Oct 28 '19 at 08:14
  • For discussion about the problems with [`java.awt.Image.getScaledInstance`](https://docs.oracle.com/en/java/javase/11/docs/api/java.desktop/java/awt/Image.html#getScaledInstance(int,int,int)), see [*The Perils of Image.getScaledInstance() Blog*](https://community.oracle.com/docs/DOC-983611) posted 2007-2015 by [Chris Adamson](https://www.linkedin.com/in/invalidname/). – Basil Bourque Oct 28 '19 at 08:21
  • You don’t have to use getScaledInstance. You can use a [draw method that scales](https://docs.oracle.com/en/java/javase/13/docs/api/java.desktop/java/awt/Graphics.html#drawImage%28java.awt.Image,int,int,int,int,java.awt.image.ImageObserver%29), or, when your source is a BufferedImage, you can use [RescaleOp](https://docs.oracle.com/en/java/javase/13/docs/api/java.desktop/java/awt/image/RescaleOp.html). – VGR Oct 28 '19 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... :-) – Harald K Oct 28 '19 at 14:31
  • @haraldK Oops, you’re right, my mistake. – VGR Oct 28 '19 at 15:26

1 Answers1

-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.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72