如何序列化和发送BufferedImage

时间:2016-03-19 21:56:54

标签: java serialization bufferedimage instant-messaging

目前我正在尝试用Java发送BufferedImage。我知道BufferedImage不是序列化的,所以我尝试创建一个可序列化的版本。 这是代码:     import java.awt.image.BufferedImage;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import javax.imageio.ImageIO;

public class SerializableBufferedImage implements Serializable{

    private long id;
    private String name;
    private BufferedImage image;

    public SerializableBufferedImage(long id, String name, BufferedImage image){

        this.id = id;
        this.name = name;
        this.image = image;

    }

    public long getId(){return id;}   
    public void setId(long id){this.id = id;}

    public String getName(){return name;}
    public void setName(String name){this.name = name;}

    public BufferedImage getImage(){return image;}
    public void setImage(BufferedImage image){this.image = image;}

    public void writeObject(ObjectOutputStream out){

        try{
            out.writeObject(name);
            ImageIO.write(image, "jpeg", ImageIO.createImageOutputStream(out));

        }catch(IOException ioException){

            ioException.printStackTrace();

        }

    }

    public void readObject(ObjectInputStream in){

        try{

            name = (String) in.readObject();
            image = ImageIO.read(ImageIO.createImageInputStream(in));

        }catch(IOException ioException){

            ioException.printStackTrace();

        }catch(ClassNotFoundException classNotFoundException){

            classNotFoundException.printStackTrace();

        }

    }

}

这是我尝试发送图像时的操作:

private void sendImage(BufferedImage image){    

    SerializableBufferedImage test = new SerializableBufferedImage(1, "test", image);

    try{
        if(output == null){

            showMessage("MAKE SURE THAT YOU ARE CONNECTED TO SOMEONE!\n");

        }

        else{

            if(image == null)System.out.println("image is null in sendImage");

            output.writeObject("CODE - 4");
            output.flush();
            System.out.println("here");
            test.writeObject(output);
            System.out.println("done");
            output.flush();
            System.out.println("Just sent code " + 4);

        }

    }catch(IOException ioException){

        System.out.println("\nERROR! UNABLE TO SEND IMAGE CODE!");
        ioException.printStackTrace();

    }

}

每当我尝试通过此方法发送图像时,程序都会崩溃。我不明白序列化是什么,它是否实现错误,我使用它是错误的,还是其他问题。代码的输出可以在这里找到: http://pastebin.com/0n4yS2ap

0 个答案:

没有答案