Currently I am trying to send a BufferedImage in Java. I am aware that BufferedImage isn't serialize, so I tried to create a serializable version. Here is the code to that: 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();
}
}
}
This is what I do when I try to send an image:
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();
}
}
The program will crash whenever I try to send an image via this method. Am I not understanding what serialization is, is it implemented wrong, am I using it wrong, or is it some other problem. The output for the code can be found here: http://pastebin.com/0n4yS2ap.