views:

61

answers:

4

What is the best way to transfer an image in C#?

  • Bitmap object
  • Byte array
  • Image Object?
+5  A: 

There is no single "best" way. If there were, then there would probably be only one way. It really depends on your situation, needs, and priorities.

That said, I use Base64 encoding every chance I get because it's fun and easy! :)

Greg D
this answer made me lol.
tster
+1  A: 

I've recently implemented this using a WCF service and chose to use Byte[] as the method of transporting the file, as it was quite simple to implement:

public byte[] DownloadFile(string fileName)
{
    var stream = System.IO.File.OpenRead(fileName);

    byte[] fileContent = new byte[stream.Length];
    stream.Read(fileContent, 0, fileContent.Length);

    return fileContent;
}

The example above is simplified as I wasn't passing a filename directly to the WCF service, but I'm sure you get the general idea =)

Rob
+2  A: 

In WCF you can return a Stream object from a method:

public Stream GetImage(string name)
{ ... }

If you have a pure SOAP based protocol you will need to stick to primitives like byte[]. This is a poor-performing option but there really isn't a better way. You may need to segment the file in multiple parts for this to work for all clients. Some SOAP clients will not allow large responses so we used to chunk the response into 30k pieces.

The best way to transfer the image is to not use either approach above, rather perform an HTTP request directly to the image and avoid all this. This is what we use now, no encoding, no client processing, streamed directly to disk. You'll have to examine your specific use case to determine if this can be applied.

csharptest.net
A: 

You could also return just the URL to the image and then let the client make a raw HTTP call to the returned URL to fetch the image.

Thanks
VM

Vikas