Q:

Converting ImageSource to Object Throws Binary stream error

I'm trying to convert/cast an image source to an object.  I tried to convert to a byte prior to object. 
ImageSource oImageSelectedByUser = (from ii in mySource where ii. PhotoImgStream ! = null select ii. PhotoImgStream).FirstOrDefault();
            var oImageAsByte = await ConvertStreamtoByteAsync(oImageSelectedByUser);
            var oImageAsObject =  FromByteArray<object>(oImageAsByte);

   private static async Task<byte[]> ConvertStreamtoByteAsync(ImageSource imageSource)
    {
        byte[] buffer = new byte[16 * 1024];
        try
        {
            if (imageSource is FileImageSource)
            {
                FileImageSource objFileImageSource = (FileImageSource)imageSource;
                string strFileName = objFileImageSource. File;

                var webClient = new WebClient();
                buffer = await webClient. DownloadDataTaskAsync(new Uri(strFileName));
                return buffer;
            }
        }
        catch (Exception ex)
        {
            buffer = null;
        }
        return buffer;
    }

    public T FromByteArray<T>(byte[] data)
    {
        if (data == null)
            return default(T);
        BinaryFormatter bf = new BinaryFormatter();
        using (MemoryStream ms = new MemoryStream(data))
        {
            object obj = bf. Deserialize(ms);
            return (T)obj;
        }
    }

When trying to convert to object, the error I get is:

Binary stream '0' does not contain a valid BinaryHeader.  Possible
causes are invalid stream or object version change between
serialization and deserialization. 

I wanted to ask is there a better way to do this? 
Any direction/pointers appreciated. 

A:

You could modify the code like following
 public T FromByteArray<T>(byte[] data)
    {
        if (data == null)
            return default(T);
        BinaryFormatter bf = new BinaryFormatter();
        using (MemoryStream ms = new MemoryStream(data))
        {
          
            ms. Seek(0, SeekOrigin. Begin);  // /rewinded the stream to the begining. 
            object obj = bf. Deserialize(ms);
            return (T)obj;
        }
    }

