Java使用ImageIO通过网络发送图像

时间:2017-03-12 19:50:14

标签: java image networking render

我有一个使用BufferedImage通过网络发送ImageIO.write(..) s流的网络程序,除了有时在另一端收到的图像只是一系列很长一段时间的小黑白方块,然后它最终会切换回发送实际图像。

我无法在任何地方找到任何帮助。

我使用的是java版本" 1.8.0_65",我这样发送图像:

        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 个答案:

答案 0 :(得分:0)

尝试此代码可能会对您有所帮助。

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();