【问题标题】:Sending BufferedImages Over Sockets通过套接字发送 BufferedImages
【发布时间】:2013-04-21 13:32:56
【问题描述】:

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

我目前只是 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}

}

再次感谢

【问题讨论】:

  • "发送当前正在执行的图像:" 这是一种低效的图像传输方式。将其编码为 PNG 或 JPG 1s​​t。
  • 我同意@Cratylus,但这似乎对/
  • @LmC:我认为OP的问题是如何将DataBufferByte转换为BufferedImage。该api给出了byte[],所以问题是如何将byte[]转换为BufferedImage,这在另一个SO线程中有答案。我添加了这个以获得帮助

标签: java sockets serialization bytearray bufferedimage


【解决方案1】:

如果要将其转换回 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;
    }
}

【讨论】:

    猜你喜欢
    • 2014-08-10
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 2011-02-24
    相关资源
    最近更新 更多