I'm trying to send an image through a socket connection, but I have a problem with the following code:
//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);
The program compiles and runs, but I don't get my image. I do get it if I use the original "myStream" but not with "myStreamR" which is constructed from the char array read from the original stream.
The output is two "OK!"s which means that all the bytes are copied into the array and all of them are pasted into the new stream. However, I checked savedBytes and I discovered that after read() it's value is 0(not good), while after write() it's equal to the stream size I gave. Then why on Earth is read() giving me a "S_OK" flag if nothing is read?
You are not seeking MyStreamR
back to the beginning after writing data to it. Image::FromStream()
starts reading at the stream's current position, so if you don't seek back then there will be no data for it to read.
Try this:
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;
}
}
}
}
}