¿Cómo convertir ImageSource a byte [] y volver a ImageSource?
Necesito tener la ruta del archivo de imagen del usuario y almacenar la imagen en la base de datos de mi servidor sql.
Obtengo el archivo del usuario y lo convierto en byte [] usando el método
public static byte[] ImageToByteArray( BitmapSource bitmapSource )
{
byte[] imgAsByteArray = null;
if( bitmapSource != null )
{
imgAsByteArray = ( new WriteableBitmap( ( BitmapSource )bitmapSource ) ).Pixels.SelectMany( p => new byte[]
{
( byte ) p ,
( byte )( p >> 8 ),
( byte )( p >> 16 ),
( byte )( p >> 24 )
} ).ToArray();
}
return imgAsByteArray;
}
pero ahora no puedo volver a convertirlo a BitmapSource. El código que escribí para convertirlo nuevamente arroja una excepción
El código
public static BitmapSourcebyteArrayToImage( byte[] imageBytes )
{
BitmapImage bitmapImage = null;
using( MemoryStream ms = new MemoryStream( imageBytes, 0, imageBytes.Length ) )
{
bitmapImage = new BitmapImage();
bitmapImage.SetSource( ms );
}
return (BitmapSource)bitmapImage;
}
Obtengo la excepción en la línea bitmapImage.SetSource (ms);
La información de excepción es 'falla catastrófica'