簡體   English   中英

將圖像從Java上的客戶端發送到python上的服務器

[英]Sending image from client on java to server on python

我一直在嘗試創建一個程序,該程序在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),我與服務器/客戶端的工作量不是很大,所以此代碼可能很糟糕。

我看不到在發送圖像之前先發送圖像大小,但是在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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM