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

前端 未结 6 448
生来不讨喜
生来不讨喜 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:28
    ByteArrayOutputStream baos;
    ImageIO.write(bufferedImage, "png", baos);
    byte[] imageBytes = baos.toByteArray();
    
    0 讨论(0)
  • 2020-12-08 03:46

    Use Apache Commons IO Utils Apache Commons

    IOUtils.copy(inputStream,outputStream);

    IO Utils API supports the large buffers easily

    0 讨论(0)
  • 2020-12-08 03:48

    Try using:

    ImageIO.setUseCache(false);
    

    Before writing, maybe that helps.

    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
  • 2020-12-08 03:51

    This should work:

    byte[] imageBytes = ((DataBufferByte) bufferedImage.getData().getDataBuffer()).getData();
    
    0 讨论(0)
  • 2020-12-08 03:52
    BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));
    byte[] bytes = new byte[buf.capacity()];
    buf.get(bytes, 0, bytes.length);
    
    0 讨论(0)
提交回复
热议问题