ImageIO write 只加载一半图片(socket)

Posted

技术标签:

【中文标题】ImageIO write 只加载一半图片(socket)【英文标题】:ImageIO write only load half the picture (socket) 【发布时间】:2017-03-07 03:54:03 【问题描述】:

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

客户端代码:

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) 
  //...
  
 

这是加载的图像:

【问题讨论】:

【参考方案1】:

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

看看DataOutputStream.writeInt()

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

【讨论】:

以上是关于ImageIO write 只加载一半图片(socket)的主要内容,如果未能解决你的问题,请参考以下文章

IOS设备上传图片,使用ImageIO.write 图片翻转纠正(JAVA)

JSP使用ImageIO.write能不能在本页面输出图片?

linux服务器jdk1.7下使用ImageIO.write构造图片时无法处理中文

java将base64转换成图片并保存在指定路径下ImageIO.write(bi1,"png",w2)提示image==null

Java中BufferedImage的用法,如何读取保存一个图片

ImageIO.write bmp 不起作用