通过套接字发送BufferedImages

时间:2013-04-21 13:32:56

标签: java sockets serialization bytearray bufferedimage

我希望通过网络发送缓冲图像作为自定义类的一部分。

我目前只需要writeObject和readObject来获取我的课程。

要发送当前正在执行的图像:

((DataBufferByte) i.getData().getDataBuffer()).getData();

如何将其转换回BufferedImage?

有更好的方法吗?

我发送的课程如下:

public class imagePack{

public byte[] imageBytes;
public String clientName;
public imagePack(String name, BufferedImage i){
    imageBytes = ((DataBufferByte) i.getData().getDataBuffer()).getData();
    clientName = name;
}

    public BufferedImage getImage(){
     //Do something to return it}

}

再次感谢

1 个答案:

答案 0 :(得分:0)

如果要将其转换回BufferedImage,您还必须知道它的宽度,高度和类型。

class imagePack {

    public byte[] imageBytes;
    public int width, height, imageType;
    public String clientName;

    public imagePack(String name, BufferedImage i) {
        imageBytes = ((DataBufferByte) i.getData().getDataBuffer())
                .getData();
        width = i.getWidth();
        height = i.getHeight();
        imageType = i.getType();
        clientName = name;
    }

    public BufferedImage getImage() {
        if (imageType == BufferedImage.TYPE_CUSTOM)
            throw new RuntimeException("Failed to convert.");
        BufferedImage i2 = new BufferedImage(width, height, imageType);
        byte[] newImageBytes = ((DataBufferByte) i2.getData()
                .getDataBuffer()).getData();
        System.arraycopy(imageBytes, 0, newImageBytes, 0, imageBytes.length);
        return i2;
    }
}