2

I am trying to read an image file to a stream. But there is a difference in length for stream when I run the program on Windows XP and Windows 7 (same image file on both system). Here is my code:

private void ImageToStream(Stream stream, string imgPath)
{
   System.Drawing.Image img = null;
   img = System.Drawing.Image.FromFile(imgPath, true);
   img.Save(stream, img.RawFormat);
}

Of course, I am using the same image for testing on both system.

The file system is NTFS. While I'm posting this photo to website, it's working fine for Windows 7 and wrong for Windows XP. I wonder there is a difference while reading an image from a stream in Windows 7 and Windows XP?

Thank in advance!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mr Tung
  • 49
  • 1
  • 11
  • 1
    What is the question?, do both OS use the same file system (Fat vs NTFS), compression, encryption etc? – sa_ddam213 Sep 26 '14 at 04:44
  • Is there any error while reading the stream or you want to ask why the stream length is different?? – User2012384 Sep 26 '14 at 04:44
  • Different by how much? Are the files compressed in one but not other? – Mrchief Sep 26 '14 at 04:51
  • Thank for your help. Here is the image that im using for test: http://i.imgur.com/NIbQ6D0.png Difference around 50 bytes but i do not know why are there difference on two OS. – Mr Tung Sep 26 '14 at 05:00
  • Do both the OSes have same file system? NTFS or FAT? – bit Sep 26 '14 at 06:06

2 Answers2

0

I have solved problem.

private void ImageToStream(Stream stream, string imgPath)
        {
            FileStream fileStream = new FileStream(imgPath,
                                    FileMode.Open, FileAccess.Read);
            byte[] buffer = new Byte[checked((uint)Math.Min(4096,
                                 (int)fileStream.Length))];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                stream.Write(buffer, 0, bytesRead);
        }

Its working fine for both system now. I think because Image.FromFile uses the native GDI calls to load the image. I have used new code and its working fine now.

Mr Tung
  • 49
  • 1
  • 11
0

What you seem to be attempting to do is to copy from one stream to another. That is a very simple operation, one that certainly does not require knowledge of the content of the source stream. Instead your code will decode the image, and then recode it. There is no reason why that should result in an identical file. Indeed for lossy compression algorithms that would result in a loss of quality.

What you need to do instead is simply copy the content of the source stream directly to the output stream. This question covers that topic in some detail: How do I copy the contents of one stream to another?

Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490