tags:

views:

66

answers:

2

I have a dynamically created Image control that is populated via a OpenFileDialog like:

OpenFileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog() == true)
{
    using (FileStream stream = dialog.File.OpenRead())
    {                    
        BitmapImage bmp = new BitmapImage();
        bmp.SetSource(stream);
        myImage.Source = bmp;
    }
}

I want to send the image back to the server in a separate function call, as string via a web service.

How do I get a memory stream / base64 string from myImage.Source

+2  A: 

Make sure you have http://imagetools.codeplex.com/

Then you can do this:

ImageSource myStartImage;

var image = ((WriteableBitmap) myStartImage).ToImage();
var encoder = new PngEncoder( false );

MemoryStream stream = new MemoryStream();
encoder.Encode( image, stream );

var myStartImageByteStream = stream.GetBuffer();

Then for Base64:

string encodedData = Convert.ToBase64String(myStartImageByteStream);
Rus
+1 Nice answer however I think the Base64 bit is probably red-herring, pumping the stream directly to the server would be better.
AnthonyWJones
This looks promising and the DLLs are very small in size too. Thanks will try it now
Vaibhav Garg
AnthonyWJones- with a Windows app you could do it, but I think Silverlight does not support streamed WCF calls.
Francesco De Vittori
+1  A: 

Here's an alternative which should work (without BmpBitmapEncoder). It's uses the FileStream stream to create the byte array that is then converted to a Base64 string. This assumes you want to do this within the scope of the current code.

  Byte[] bytes = new Byte[stream.Length];
  stream.Read(bytes, 0, bytes.Length);
  return Convert.ToBase64String(bytes); 
TheCodeKing
I think you mean stream.read(), where stream is FileStream, instead of mem.write(). but yes this works without the use of additional DLLs.
Vaibhav Garg
no need for memory stream. I did: Byte[] bytes = new Byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); serialized = Convert.ToBase64String(bytes);
Vaibhav Garg
Ah yes good point, I'll update.
TheCodeKing