【问题标题】:Sending image from client on java to server on python将图像从java上的客户端发送到python上的服务器
【发布时间】:2015-08-28 20:11:04
【问题描述】:

我一直在尝试创建一个在 Java 中运行客户端和在 Python 中运行服务器的程序。 我的总体目标是将图片从 Java 上的客户端上传到 Python 上的服务器并将其存储在 mysql 服务器上。我还没有尝试从 Python 上的图像转换为 mysql 上的 blob 和已经陷入上传到 python 阶段。这是以下代码:

客户端:(java)

        client.send("upload##user##pass##"); //this is how i know that upload    request has been sent.
        String directory = "/home/michael/Pictures/"+field.getText();// a valid directory of a picture.
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(new File(directory));
        } catch (IOException err) {
            err.printStackTrace();
        }

        try {

            ImageIO.write(bufferedImage, "png", client.socket.getOutputStream());//sending the picture via socket.
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

这是服务器:(Python)

 elif mar[0]=="upload":##this is how i know that the request is to upload

  buf = ''
  while len(buf)<4:
     buf += clientsock.recv(4-len(buf))
  size = struct.unpack('!i', buf)
  print "receiving %s bytes" % size

  with open('tst.jpg', 'wb') as img:
      while True:
         data = clientsock.recv(1024)
         if not data:
           break
         img.write(data)
  print 'received, yay!'

此代码实际上不起作用并打印出我想发送的大量字节(图片大约为 2 gb) 我没有经常使用服务器/客户端,所以这段代码可能很糟糕。

【问题讨论】:

    标签: java python mysql sockets server


    【解决方案1】:

    我看不到您在发送图像之前发送了图像大小,但在 Python 代码中,您首先读取 4 字节的图像大小。
    您需要在 Java 代码中添加图像大小的发送:

    try {
        OutputStream outputStream = client.socket.getOutputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
        // get the size of image
        byte[] size = ByteBuffer.allocate(4).putInt(byteArrayOutputStream.size()).array();
        outputStream.write(size);
        outputStream.write(byteArrayOutputStream.toByteArray());
        outputStream.flush();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    

    【讨论】:

    • 首先,感谢您的评论。然而,它运行这个错误: Type mismatch: cannot convert from java.io.OutputStream to org.omg.CORBA.portable.OutputStream 这两种类型由于某种原因在第一行似乎不一样。
    • 尝试导入 java.io.OutputStream 而不是 org.omg.CORBA.portable.OutputStream
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 2019-03-12
    • 2014-04-28
    • 1970-01-01
    相关资源
    最近更新 更多