Dak31
Dak31

Reputation: 82

How to convert BufferedImage to an int[]?

I'm looking to send over an Object that has a BufferedImage through a socket. BufferedImage is not serializable, so it needs to be converted to a serializable data type, and then back again. I have looked a lot online, and byte[] seems to be the go to send just a BuffereImage, but I'm trying to send an entire object so I'm leaning more towards int[]. I thought I ran across an answer that explained this on here a few weeks ago, but after 2.5 hours of searching I could not find it. I have tried the Java Oracle, but quickly got lost.

If there is a better way please excuse my ignorance, as I have not really worked a lot with sockets and BufferedImage manipulation.

Upvotes: 3

Views: 2814

Answers (2)

Zarkonnen
Zarkonnen

Reputation: 22478

Send the image across as a PNG:

// BufferedImage -> byte sequence
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "PNG", baos);
byte[] imageData = baos.toByteArray();
// byte sequence -> BufferedImage
ByteArrayInputStream bais = new ByteArrayInputStream(imageData);
BufferedImage img = ImageIO.read(bais);

Upvotes: 1

FiReTiTi
FiReTiTi

Reputation: 5878

Basically a BufferedImage is an array. The pixels are stored into the DataBuffer, which is an array.

BufferedImage source = //...
switch ( source.getType() )
    {
    case BufferedImage.TYPE_BYTE_GRAY :
    case BufferedImage.TYPE_3BYTE_BGR :
    case BufferedImage.TYPE_4BYTE_ABGR :
        final byte[] bb = ((DataBufferByte)source.getRaster().getDataBuffer()).getData() ;
        //...
        break ;
    case BufferedImage.TYPE_USHORT_GRAY :
        final short[] sb = ((DataBufferUShort)source.getRaster().getDataBuffer()).getData() ;
        //...
        break ;
    case BufferedImage.TYPE_INT_RGB :
    case BufferedImage.TYPE_INT_BGR :
    case BufferedImage.TYPE_INT_ARGB :
        final int[] ib = ((DataBufferInt)source.getRaster().getDataBuffer()).getData() ;
        break ;
    // etc.
    }

You will also need to send the image dimensions, plus the number of channels.

Upvotes: 4

Related Questions