3

我正在尝试通过套接字连接发送图像,但以下代码有问题:

//stream to char array
STATSTG myStreamStats;
ULONG bytesSaved;
myStream->Stat(&myStreamStats, 0);
char* streamData = new char[myStreamStats.cbSize.QuadPart];
if(myStream->Read(streamData, myStreamStats.cbSize.QuadPart, &bytesSaved) == S_OK)
    cout<<"OK!"<<endl;
else
    cout<<"Not OK!"<<endl;

//char array to stream
if(myStreamR->Write(streamData, myStreamStats.cbSize.QuadPart, &bytesSaved) == S_OK)
    cout<<"OK!"<<endl;
else
    cout<<"Not OK!"<<endl;

//saving the image to a file
myImage = Image::FromStream(myStreamR);
myImage->Save(lpszFilename, &imageCLSID, NULL);

该程序编译并运行,但我没有得到我的图像。如果我使用原始的“myStream”而不是“myStreamR”,它是由从原始流中读取的字符数组构造的,我会得到它。

输出是两个“OK!”,这意味着所有字节都被复制到数组中,并且所有字节都被粘贴到新的流中。但是,我检查了 savedBytes,发现在 read() 之后它的值是 0(不好),而在 write() 之后它等于我给的流大小。那么,如果什么都没读,为什么 read() 会给我一个“S_OK”标志呢?

4

1 回答 1

6

在向其写入数据后,您不会MyStreamR回到起点。Image::FromStream()从流的当前位置开始读取,因此如果您不返回,则将没有数据可供读取。

尝试这个:

STATSTG myStreamStats = {0};
if (FAILED(myStream->Stat(&myStreamStats, 0)))
    cout << "Stat failed!" << endl;
else
{
    char* streamData = new char[myStreamStats.cbSize.QuadPart];

    ULONG bytesSaved = 0;
    if (FAILED(myStream->Read(streamData, myStreamStats.cbSize.QuadPart, &bytesSaved)))
        cout << "Read failed!" << endl;
    else
    {
        //char array to stream
        if (FAILED(myStreamR->Write(streamData, bytesSaved, &bytesSaved)))
            cout << "Write failed!" << endl;
        else
        {
            LARGE_INTEGER li;
            li.QuadPart = 0;

            if (FAILED(myStreamR->Seek(li, STREAM_SEEK_SET, NULL)))
                cout << "Seek failed!" << endl;
            else
            {
                //saving the image to a file
                myImage = Image::FromStream(myStreamR);
                if (myImage1->GetLastStatus() != Ok)
                    cout << "FromStream failed!" << endl;
                else
                {
                    if (myImage->Save(lpszFilename, &imageCLSID, NULL) != Ok)
                        cout << "Save failed!" << endl;
                    else
                        cout << "OK!" << endl;
                }
            }
        }
    }
}
于 2012-12-05T03:55:18.690 回答