Java使用ImageIO通过网络发送图像 [英] Java sending image through network with ImageIO
本文介绍了Java使用ImageIO通过网络发送图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个网络程序,该网络程序使用ImageIO.write(..)
通过网络发送BufferedImage
s的流,此操作按预期进行,除了有时在另一端收到的图像只是一系列小的黑白图像正方形很长一段时间,然后最终将切换回发送实际图像.
I have a network program that sends a stream of BufferedImage
s 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.
我使用的是Java版本"1.8.0_65",我将图像发送为:
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();
推荐答案
尝试使用此代码可能会对您有所帮助.
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();
这篇关于Java使用ImageIO通过网络发送图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文