Java 套接字损坏 PNG-图像

标签 java image sockets transfer corruption

我目前正在尝试使用套接字将 PNG 或 JPEG 图像从一个客户端发送到另一个客户端(在 Java 中),但图像总是损坏(当我尝试打开它时,它只是说无法打开)因为它已损坏、有缺陷或太大)。 我已经尝试过将图像加载到 byte[] 中的方法,如果我只是将图像加载到 byte[] 中然后将其保存回来,它可以完美工作,因此问题一定出在 byte[] 的发送中。 以下是我用于发送的函数:

/**
 * Attempts to send data through the socket with the BufferedOutputStream. <p>
 * Any safety checks should be done beforehand
 * @param data - the byte[] containing the data that shall be sent
 * @return - returns 'true' if the sending succeeded and 'false' in case of IOException
 */
public boolean sendData(byte[] data){
    try {
        //We simply try to send the data
        outS.write(data, 0, data.length);
        outS.flush();
        return true;    //Success
    } catch (IOException e) {
        e.printStackTrace();
        return false;   //Failed
    }
}

/**
 * Attempts to receive data sent to the socket. It uses a BufferedInputStream
 * @param size - the number of bytes that should be read
 * @return - byte[] with the received bytes or 'null' in case of an IOException
 */
public byte[] receiveData(int size){
    try {
        int read = 0, r;
        byte[] data = new byte[size];
        do{
            //We keep reading until we have gotten all data
            r = inS.read(data, read, size-read);
            if(r > 0)read += r;
        }while(r>-1 && read<size);  //We stop only if we either hit the end of the 
                            //data or if we have received the amount of data we expected
        return data;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

到达的图像似乎大小正确,因此数据至少到达了,只是损坏了。

最佳答案

扔掉您的 receiveData() 方法并使用 DataInputStream.readFully()

关于Java 套接字损坏 PNG-图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28459044/

相关文章:

java - 获取 div 标签 jsoup 中的 src 属性

python - Python遍历灰度图像中的连接组件

html - 图像未加载/飞走按钮

sockets - 为什么 UDP 数据包被识别为 LLC 协议(protocol)?

java - tomcat 7 + freebsd 7.2(32 位)多线程应用程序抛出 OutOfMemoryError : could not create native thread

Java小程序: actionlistener of button with noname

java - 覆盖同一工具的多个方法

java - Tika in Action 书中的示例 Lucene StandardAnalyzer 不起作用

.net - 如何在VB.NET中与服务器交换数据包?

javascript - 嵌入来自第三方的图像相册(imgur、picasa)