2

我试图将位图从我的 android 发送到 pc(C++ 套接字服务器)但失败了。发送完成后无法打开PNG文件

1 - 这是我将位图压缩为 png 格式的代码

ByteArrayOutputStream bos = new ByteArrayOutputStream();
tmpBM.compress(CompressFormat.PNG, 0, bos); // compress to png format
byte[] bitmapdata = bos.toByteArray(); // new byte[] to send via socket
sendFile(bitmapdata, bitmapdata.length); // call sendFile method

2 - 这里是 sendFile 方法代码。arr 是字节数组, len 是 arr.length

public void sendFile(byte[] arr, int len) throws Exception{

    byte[] buf = new byte[1024];
    int cur = 0; // current byte reading
    sendMessage("Send\n"); // talk server

    sendMessage(String.valueOf(len)); // send file size
    // OutputStream outStream = ...;
    while (len-cur>0){
        if (len-cur>=1024){
            buf = copy(arr, cur, 1024); // copy to buf, from arr, offset cur, size 1024 byte
            outStream.write(buf, 0, 1024);
            cur+=1024;
        }// send 1024 byte if file size >1024
        else {
            buf = copy(arr, cur, len-cur);
            buf[len-cur] = '\0';
            outStream.write(buf, 0, len-cur);
        }// send remaining byte
    }
    outStream.flush();
}

3 - 这是代码接收文件

    char rec[50] = "";
    FILE *fw = fopen("tmp.png", "wb");
    printf("\n Created file");
    int recs = recv( current_client, rec, 32, 0 );
    rec[recs]='\0';
    int size = atoi(rec);
    printf("\n Have size %d", size);
    while(size > 0)
    {
        char buffer[1030]; // create buffer
        printf("\nLoop %d", size);
        if(size>=1024) // if remaining >1024 byte, read 1024 byte
        {
            recv( current_client, buffer, 1024, 0 );
            fwrite(buffer, 1024, 1, fw);
        }
        else // else read all
        {
            recv( current_client, buffer, size, 0 );
            buffer[size]='\0';
            fwrite(buffer, size, 1, fw);
        }
            size -= 1024;
    }
    fclose(fw);
4

0 回答 0