gpt4 book ai didi

java - 将图像从java客户端发送到python服务器

转载 作者:行者123 更新时间:2023-11-30 22:42:12 25 4
gpt4 key购买 nike

我一直在尝试创建一个程序,在 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();
}

关于java - 将图像从java客户端发送到python服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30809462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com