Java sending image through network with ImageIO

微笑、不失礼 提交于 2019-12-12 01:14:42

问题


I have a network program that sends a stream of BufferedImages through a network using ImageIO.write(..), this is working as intended apart from sometimes the Image received on the other end will just be a series of small black and white squares for a long time, then it will eventually switch back to sending the actual images.

I can't find any help with this anywhere.

I'm using java version "1.8.0_65", I send the image like so:

        BufferedImage capture = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));

        BufferedImage newImage = new BufferedImage(capture.getWidth(), capture.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE);
        newImage.createGraphics().drawImage(capture, 0, 0, newImage.getWidth(), newImage.getHeight(), null);

        capture = newImage;

        BufferedImage difference = null;
        if (lastImage != null) {
            difference = getDifferenceImage(capture, lastImage);
        } else {
            difference = capture;
        }

        long generated = System.currentTimeMillis() - start;

        ImageIO.write(difference, "png", socket.getOutputStream());
        socket.getOutputStream().flush();

回答1:


Try this code may be it will help you.

public byte[] getCustomImageInBytes(BufferedImage originalImage) {
    byte[] imageInByte = null;
    try {
        // convert BufferedImage to byte array
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(originalImage, "png", baos);
        baos.flush();
        imageInByte = baos.toByteArray();
        baos.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return imageInByte;
}

socket.getOutputStream().write(getCustomImageInBytes(difference));
socket.getOutputStream().flush();


来源:https://stackoverflow.com/questions/42752299/java-sending-image-through-network-with-imageio

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