1

I'm working on a processing platform for images and my server is currently accepting images as byte arrays from the client using pythons PIL.Image methods. I'm also currently using Java as a front end to grab image frames from video with the FrameGrab utility and returning them as a BufferedImage object. What I don't understand is how I am meant to convert from this buffered image object to a jpg byte array and could use some help.'

I've found an example of writing out a

Here is the base portion of my code.

            BufferedImage frame;

            for (int i = 1; i < 100; i++) { 
                try {
                    frame = AWTUtil.toBufferedImage(FrameGrab.getFrameAtSec(videoFile, i * .3));


                } catch (IOException ex) {
                    Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
                } catch (JCodecException ex) {
                    Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

My python server backend is currently just attempting to save the file with the aforementioned library like so:

        img = Image.open(io.BytesIO(data))
        img.save('test.jpg')
harry
  • 53
  • 5
  • I dont have any problems with that part of the code, its already tested and fully functional, I need a method to get the equivalent format from a BufferedImage object. – harry Sep 21 '19 at 03:02
  • 1
    Assuming I've understood properly, you should look into [`ImageIO`](https://docs.oracle.com/en/java/javase/13/docs/api/java.desktop/javax/imageio/ImageIO.html) and [`ByteArrayOutputStream`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/io/ByteArrayOutputStream.html). – Slaw Sep 21 '19 at 03:12

1 Answers1

1

The easy way:

public static byte[] toJpegBytes(BufferedImage image) throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ImageIO.write(image, "jpeg", baos);
  return baos.toByteArray();
}

If you want more control over the conversion (compression level, etc) see Setting jpg compression level with ImageIO in Java.

dnault
  • 8,340
  • 1
  • 34
  • 53
  • Thanks, I wound up reading over the documentation and coming up with a similar function. – harry Sep 21 '19 at 06:08