Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Memory Stream/Base64 String from Image.Source?

Tags:

silverlight

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

like image 337
Vaibhav Garg Avatar asked Dec 13 '22 19:12

Vaibhav Garg


2 Answers

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); 
like image 101
TheCodeKing Avatar answered Jan 21 '23 14:01

TheCodeKing


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);
like image 35
Rus Avatar answered Jan 21 '23 12:01

Rus