Java- Convert bufferedimage to byte[] without writing to disk

前端 未结 6 474
生来不讨喜
生来不讨喜 2020-12-08 03:12

I\'m trying to send multiple images over a socket using java but I need a faster way to convert the images to a byte array so I can send them. I tried the following code but

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 03:49

    The code below it's really fast (few milliseconds)

    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    
    public byte[] toByteArray(BufferedImage image) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();            
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(baos);
        encoder.encode(image);            
        return baos.toByteArray();
    }
    

提交回复
热议问题