简体   繁体   English

如何将BufferedImage转换为int []?

[英]How to convert BufferedImage to an int[]?

I'm looking to send over an Object that has a BufferedImage through a socket. 我正在寻找通过套接字发送具有BufferedImage的对象。 BufferedImage is not serializable, so it needs to be converted to a serializable data type, and then back again. BufferedImage不可序列化,因此需要将其转换为可序列化的数据类型,然后再次返回。 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[]. 我在网上已经看了很多东西,并且byte []似乎只是发送BuffereImage的方法,但是我正尝试发送整个对象,因此我更倾向于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. 我以为我在几周前就遇到了一个对此做出解释的答案,但是经过2.5个小时的搜索,我找不到了。 I have tried the Java Oracle, but quickly got lost. 我尝试过Java Oracle,但是很快迷路了。

If there is a better way please excuse my ignorance, as I have not really worked a lot with sockets and BufferedImage manipulation. 如果有更好的方法,请原谅我的无知,因为我在套接字和BufferedImage操作方面还没有做很多工作。

Basically a BufferedImage is an array. 基本上,BufferedImage是一个数组。 The pixels are stored into the DataBuffer, which is an array. 像素存储在DataBuffer中,DataBuffer是一个数组。

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. 您还需要发送图像尺寸以及通道数。

Send the image across as a PNG: 以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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM