gpt4 book ai didi

Java套接字,获取图像文件但无法打开

转载 作者:行者123 更新时间:2023-12-01 14:59:24 25 4
gpt4 key购买 nike

这是我的第一个问题,所以我希望我写得正确。

我正在尝试通过 Java 套接字发送一个 byte[] 数组,该数组包含一个图像。

这是发送文件的代码:

public void WriteBytes(FileInputStream dis) throws IOException{
//bufferEscritura.writeInt(dis.available()); --- readInt() doesnt work correctly
Write(String.valueOf((int)dis.available()) + "\r\n");
byte[] buffer = new byte[1024];
int bytes = 0;
while((bytes = dis.read(buffer)) != -1){
Write(buffer, bytes);
}
System.out.println("Photo send!");
}
public void Write(byte[] buffer, int bytes) throws IOException {
bufferEscritura.write(buffer, 0, bytes);
}
public void Write(String contenido) throws IOException {
bufferEscritura.writeBytes(contenido);
}

我的图片:

URL url = this.getClass().getResource("fuegos_artificiales.png");
FileInputStream dis = new FileInputStream(url.getPath());
sockManager.WriteBytes(dis);

我的获取图像文件的代码:

public byte[] ReadBytes() throws IOException{
DataInputStream dis = new DataInputStream(mySocket.getInputStream());
int size = Integer.parseInt(Read());
System.out.println("Recived size: "+ size);
byte[] buffer = new byte[size];
System.out.println("We are going to read!");
dis.readFully(buffer);
System.out.println("Photo received!");
return buffer;

}

public String Leer() throws IOException {
return (bufferLectura.readLine());
}

并创建图像文件:

byte[] array = tcpCliente.getSocket().LeerBytes();
FileOutputStream fos = new FileOutputStream("porfavor.png");
try {
fos.write(array);
}
finally {
fos.close();
}

图像文件已创建,但当我尝试使用 Paint 打开它时,它说无法打开它,因为它已损坏......我还尝试用记事本打开两个图像(原始图像和新图像),它们里面有相同的数据!

我不知道发生了什么......

希望你能帮助我。

谢谢!

最佳答案

  1. 不要使用 available() 作为文件长度的度量。事实并非如此。 Javadoc 中对此有一个具体警告。

  2. 使用 DataOutputStream.writeInt() 写入长度,使用 DataInputStream.readInt() 读取长度,并使用相同的流读取图像数据。不要在同一个套接字上使用多个流。

也在此:

URL url = this.getClass().getResource("fuegos_artificiales.png");
FileInputStream dis = new FileInputStream(url.getPath());

第二行应该是:

InputStream in = URL.openConnection.getInputStream();

类资源不是文件。

关于Java套接字,获取图像文件但无法打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13893087/

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