ImageIO只能加载图片的一半(套接字)

时间:2017-03-07 03:54:04

标签: java sockets javax.imageio bytebuffer bytearrayoutputstream

我正在尝试使用套接字将图像从客户端发送到服务器。我能够将图像发送到服务器目录,但发送的图像未满。 我应该改变什么?

客户代码:

Part filePart = request.getPart("file"); 
InputStream fileContent = filePart.getInputStream();        

Socket clientSocket = new Socket("localhost",51519);
OutputStream outputStream = clientSocket.getOutputStream();
try {                       
    BufferedImage image = ImageIO.read(fileContent);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ImageIO.write(image, "jpg", byteArrayOutputStream);

    byte[] size = ByteBuffer.allocate(4).putInt(byteArrayOutputStream.size()).array();

    outputStream.write(size);
    outputStream.write(byteArrayOutputStream.toByteArray());                   
}
catch (SocketException ex){
    BLL_Common.write_log(ex.toString(), "");
} catch (IOException ex) {
    BLL_Common.write_log(ex.toString(), "");
} finally {
    outputStream.flush();     
}

服务器代码:

String dir = "web/Admin/img/";     
ServerSocket serverSocket = new ServerSocket(51519);

while(true) {
 try {
  Socket socket = serverSocket.accept();

  InputStream inputStream = socket.getInputStream();

  byte[] sizeAr = new byte[4];
  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));                 

  String fileName = String.valueOf(System.currentTimeMillis());

  ImageIO.write(image, "jpg", new File(dir + fileName + ".png"));
 } 
 catch (SocketException ex) {
  //...
 } catch (IOException ex) {
  //...
 } 
} 

这是加载的图片: enter image description here

1 个答案:

答案 0 :(得分:1)

您假设read()填充缓冲区。您需要DataInputStream.readFully()

了解DataOutputStream.writeInt()时的情况。

当然,您可以直接在套接字输入流上使用ImageIO.read()并避免所有这些,并且类似地ImageIO.write()直接对套接字输出流。但除非原始图像不是JPEG,否则您应该只复制字节,而不使用ImageIOBufferedImage