Question

I got help in a previous question on how to send an image. The thing done was to first send the lenght of the image(size), and then the actual image, then it would know when it was done.

IT looks like this:

BinaryWriter writer = new BinaryWriter(netStream);
while (someCondition) {
  Image img = SomeImage();
  MemoryStream ms = new MemoryStream();
  img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
  byte[] buffer = new byte[ms.Length];
  ms.Seek(0, SeekOrigin.Begin);
  ms.Read(buffer, 0, buffer.Length);
  writer.Write(buffer.Length);
  writer.Write(buffer);

This code is from: Angelo Geels , who helped me in my previous question.

Now, i tried to optimize this in a way. And well, it works. But ONLY when the file is bmp (uncompressed), and i don´t know why.

                    using (MemoryStream ms = PrintWindow(process))
                    {
                        writer.Write((int)ms.Length);
                        writer.Write(ms.GetBuffer());
                    }

So PrintWindow save an image to a memorystream and returns it. so ms = memorystream with my image in it.

So for me this should work perfectly, cause form what i can se i do the same thing.

i send the size of the file (length of the memorystream). Then i send the byte[] data in the memorystream.

So, it´s the same thing.

But, it only works with bmp.

The only thing i can think of is that when i save in a compressed format, the bmp is first written and then encoded, which messes up the getbuffer() or something.

But i still think it should work.

Était-ce utile?

La solution

You write too many bytes, use the Write() overload that lets you specify how much to write:

    using (MemoryStream ms = PrintWindow(process)) {
        writer.Write((int)ms.Length);
        writer.Write(ms.GetBuffer(), 0, (int)ms.Length);
    }

Autres conseils

Don't use GetBuffer. From the documentation:

Note that the buffer contains allocated bytes which might be unused. For example, if the string "test" is written into the MemoryStream object, the length of the buffer returned from GetBuffer is 256, not 4, with 252 bytes unused. To obtain only the data in the buffer, use the ToArray method; however, ToArray creates a copy of the data in memory.

Use:

 writer.Write(ms.ToArray());

Or if you are in 4.0 use the CopyTo method:

 ms.CopyTo(netStream);

Check this if you are not in 4.0 for a way to copy streams: How do I copy the contents of one stream to another?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top