0

I want to send a buffered image across the network as part of my custom class.

I currently just writeObject and readObject to get my class.

To send the image im currently doing:

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

How do i convert that back in to a BufferedImage?

Is there a better way to be doing this?

The class i send looks like:

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}

}

Thanks again

Lemex
  • 3,772
  • 14
  • 53
  • 87
  • 1
    *"To send the image im currently doing:"* That is an inefficient way to transmit images. Encode it to PNG or JPG 1st. – Andrew Thompson Apr 21 '13 at 13:38
  • Possible duplicate:http://stackoverflow.com/questions/12705385/how-to-convert-a-byte-to-a-bufferedimage-in-java – Cratylus Apr 21 '13 at 13:39
  • I agree @Cratylus but that seems unefficent there to/ – Lemex Apr 21 '13 at 13:41
  • @LmC:I think the OP problem is how to convert the `DataBufferByte` to `BufferedImage`. The api gives the `byte[]` so the problem is how to convert the `byte[]` to `BufferedImage` which has an answer in the other SO thread.I added this for help – Cratylus Apr 21 '13 at 13:44

1 Answers1

0

If you want to convert that back in to a BufferedImage, you must also know its width, height and type.

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;
    }
}
johnchen902
  • 9,531
  • 1
  • 27
  • 69