Java - Sending an object that points to a BufferedImage through a Socket

后端 未结 3 396
别那么骄傲
别那么骄傲 2020-12-22 10:17

Me and a group of friends are working on a project in Java, and we need some help regarding sending objects through sockets.

So far, we have achieved to send simple

相关标签:
3条回答
  • 2020-12-22 10:55

    on each node you can use writeObject() and readObject() check http://java.sun.com/developer/technicalArticles/Programming/serialization/ for more info

    essentially it will become

    public Node implements Serializable{
    
        transient BufferedImage buff;//transient make it so it won't be written with defaultWriteObject (which would error)
    
        private void writeObject(ObjectOutputStream out)throws IOException{
            out.defaultWriteObject();
            //write buff with imageIO to out
        }
    
        private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{
            in.defaultReadObject();
            //read buff with imageIO from in
        }
    }
    
    0 讨论(0)
  • 2020-12-22 11:10

    If you want to use Objects Streams, you can wrap buffered image inside a class that implements Serializable and has a attribute that is a array of bytes (image data as byte array). You'll have to modify your code, changing BufferedImage references to SerializableImage(class name example)..

    If you do that, your class will be serialized and transferred..

    0 讨论(0)
  • 2020-12-22 11:19

    You can convert BufferedImage to byte array on client side and send then as normal byte array and on the server side create BufferedImage from that byte array. Below is the code to convert BufferedImage to byte array and vice versa.

    import java.awt.image.BufferedImage;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import javax.imageio.ImageIO;
    
    public class ImageTest {
    
    public static void main(String[] args) {
    
        try {
    
            byte[] imageInByte;
            BufferedImage originalImage = ImageIO.read(new File(
                    "c:/darksouls.jpg"));
    
            // convert BufferedImage to byte array
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(originalImage, "jpg", baos);
            baos.flush();
            imageInByte = baos.toByteArray();
            baos.close();
    
            // convert byte array back to BufferedImage
            InputStream in = new ByteArrayInputStream(imageInByte);
            BufferedImage bImageFromConvert = ImageIO.read(in);
    
            ImageIO.write(bImageFromConvert, "jpg", new File(
                    "c:/new-darksouls.jpg"));
    
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
    }
    
    0 讨论(0)
提交回复
热议问题