Thursday, January 3, 2013

Silverlight : Ger ByteArry from Image File and Convert ByteArray to ImageSource

 Ger ByteArry from Image File

To Read ByteArray from FileInfo using OpenFileDialog, Steps Are :

1. First Create Method that takes Stream as input and return Byte[].


 public static byte[] ReadBytesFromStream(Stream stream)
 {
 byte[] size = new byte[16 * 1024];
 using (MemoryStream memoryStream = new MemoryStream())
 {
  int readCount;
  while ((readCount = stream.Read(size, 0, size.Length)) > 0)
  {
   memoryStream.Write(size, 0, readCount);
  }
  return memoryStream.ToArray();
 }
} 
 
  
2. Create Button for Upload Image, write following code on Button Click event.

private void UploadImageButton_Click(object sender, RoutedEventArgs e)
{
 OpenFileDialog filedlg = new OpenFileDialog();
 dlg.Multiselect = false;
    dlg.Filter = "All files (*.*)|*.*|PNG Images (*.png)|*.png|JPEG Images(*.jpeg)|*.jpeg";
 
 bool? retval = dlg.ShowDialog();
 
 if (retval != null && retval == true)
 {
  byte[] getArray = ReadBytesFromStream(dlg.File.OpenRead());  
 }
}


 Get Image From ByteArry


your ByteArray  : byte[] getArray

 
using (MemoryStream memoryStream = new MemoryStream(getArray, 0,
     imageBytes.Length))
{
 BitmapImage image = new BitmapImage();
 image.SetSource(memoryStream );
}

No comments:

Post a Comment