In the past two days, I have created a self-developed project and found a strange phenomenon. The general situation is like this.
I need to write an image object to the stream, using the image. Save (stream, imageformat) overload, and I have already written other data in this stream.
My development environment is win7 + vs2010, and the framework used is. Net 3.5 client profile. Everything works normally during development. But when I compile itProgramIn the XP system, a problem is found. When the image data is written to the stream, it is not written to the current position of the stream, but to the starting position of the stream, destroy the data I wrote in it.
Later, I checked the msdn description of the Save method, which contains the following sentence:
The image must be saved to the stream at an offset of zero. If any additional data has been written to the stream before saving the image, the image data in the stream will be upted.
It means that the image must be saved to a position of 0 in the stream, and the data already written to the stream will be damaged.
So, why is it good in win7. So I did a simple experiment and found that after data is written in win7, the original data in the stream will not be overwritten, but in XP, not all image formats will. I tested two formats: PNG and jpg, and found that PNG will cause data corruption, but JPG will not. TestCodeAs follows:
Test code
Public Void Test ()
{
Fileinfo File = New Fileinfo (path. gettempfilename ());
Try
{
Using (Bitmap BM = New Bitmap ( 32 , 32 ))
{
Using (VAR stream = File. openwrite ())
{
Stream. writebyte ( 9 );
Stream. writebyte ( 7 );
Stream. writebyte ( 2 );
Stream. writebyte ( 6 );
//Change the image format here
BM. Save (stream, imageformat. JPEG );
}
}
Using (VAR stream = File. openread ())
{
Byte [] Buf = New Byte [ 4 ];
Stream. Read (BUF, 0 , 4 );
//If the information displayed is, the data is not damaged.
MessageBox. Show (bitconverter. tostring (BUF ));
}
}
Catch (Exception X)
{
MessageBox. Show (X. tostring ());
}
Finally
{
File. Delete ();
}
}