help for solving problems in a java rmi assignment

假装没事ソ 提交于 2019-12-03 21:04:44

You can't use BufferedImage as a remote parameter as it is neither Remote nor Serializable.

You could wrap the BufferedImage in an ImageIcon but that is very inefficient as it will be converted to a bitmap and transmitted over the network uncompressed.

I would make the argument to Share a byte array representing a compressed image format (e.g. PNG.)

public interface IServer extends Remote{
   public void share(byte[] imagePNGBytes) throws RemoteException;
}

public void mouseClicked(MouseEvent arg0) {
    try {
        BufferedImage screenShot = new Robot()
        .createScreenCapture(new Rectangle(Toolkit
        .getDefaultToolkit().getScreenSize()));
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        ImageIO.write(screenShot, "PNG", bytes);
        server.share(bytes.toByteArray());
    } catch (...) {
         // ...
    }
}

public class ServerFrame extends JFrame implements IServer {

    // . . .

    public void share(byte[] imagePNGBytes) throws IOException, RemoteException {
        RenderedImage image = ImageIO.read(new ByteArrayInputStream(imagePNGBytes));
        label.setIcon(new ImageIcon(image));
    }
}

As the stack trace shows, the root cause is:

Caused by: java.io.NotSerializableException: java.awt.image.BufferedImage

which means that you tried to serialize a non-serializable class, namely BufferedImage.

An alternative would be to use and ImageIcon rather than a BufferedImage.

@finnw

Your code works fine except that

label.setIcon(new ImageIcon(image));

ImageIcon class doesnot have a constructor that accepts RenderedImage object.

So you need to convert RenderedImage into a BufferedImage. And code for that goes here

public BufferedImage convertRenderedImage(RenderedImage img) {
    if (img instanceof BufferedImage) {
        return (BufferedImage) img;
    }
    ColorModel cm = img.getColorModel();
    int width = img.getWidth();
    int height = img.getHeight();
    WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
    boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
    Hashtable properties = new Hashtable();
    String[] keys = img.getPropertyNames();
    if (keys != null) {
        for (int i = 0; i < keys.length; i++) {
            properties.put(keys[i], img.getProperty(keys[i]));
        }
    }
    BufferedImage result = new BufferedImage(cm, raster, isAlphaPremultiplied, properties);
    img.copyData(raster);
    return result;
}

and now changing your code to

label.setIcon(new ImageIcon(convertRenderedImage(image)));

works

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!