我正在做一个简单的应用程序,以在Java上发送图像,但是我遇到一些我不知道如何解决它的问题。主要问题是,当我发送大图像(大约1000 * 600)时,图像没有被完全接收,这意味着图像的一部分与原始图像不同。我认为这是一个溢出问题,但我要求其他观点。谢谢!
originalImage:https://imgur.com/hK8zwX1 receiveImage:https://imgur.com/8O2I0rc
sendImage
public void sendFile(File inputFile) throws IOException {
try {
Socket socket = new Socket("localhost", 1414);
OutputStream outputStream = socket.getOutputStream();
System.out.println("Conexion establecida");
File f = inputFile;
BufferedImage image = ImageIO.read(f);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", byteArrayOutputStream);
byte[] size = ByteBuffer.allocate(1024).putInt(byteArrayOutputStream.size()).array();
outputStream.write(size);
outputStream.write(byteArrayOutputStream.toByteArray());
outputStream.flush();
System.out.println("Flushed: " + System.currentTimeMillis());
Thread.sleep(1);
System.out.println("Closing: " + System.currentTimeMillis());
socket.close();
} catch (InterruptedException ex) {
Logger.getLogger(ButPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
客户:
try {
ServerSocket serverSocket = new ServerSocket(1414);
while (true) {
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
System.out.println(socket.getInetAddress() + " conectandose..." + System.currentTimeMillis());
byte[] sizeAr = new byte[1024];
inputStream.read(sizeAr);
int size = ByteBuffer.wrap(sizeAr).asIntBuffer().get();
byte[] imageAr = new byte[size];
inputStream.read(imageAr);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageAr));
System.out.println("Received " + image.getHeight() + "x" + image.getWidth() + ": " + System.currentTimeMillis());
ImageIO.write(image, "jpg", new File("C:\\Users\\Public\\Pictures\\imgTemp.jpg"));
File f = new File ("C:\\Users\\Public\\Pictures\\imgTemp.jpg");
System.out.println("Closing: " + System.currentTimeMillis());
this.repaint();
serverSocket.close();
}
} catch (IOException ex) {
System.err.println(ex.getMessage());
}