2012-01-17 19 views
14

necesito ayuda, tengo este método para obtener un BitmapImage de un byte []Cómo convertir byte [] para BitmapImage

public BitmapSource ByteToBitmapSource(byte[] image) 
{ 
    BitmapImage imageSource = new BitmapImage(); 

    using (MemoryStream stream = new MemoryStream(image)) 
    { 
     stream.Seek(0, SeekOrigin.Begin); 
     imageSource.BeginInit(); 
     imageSource.StreamSource = stream; 
     imageSource.CacheOption = BitmapCacheOption.OnLoad; 
     imageSource.EndInit(); 
    } 

    return imageSource; 
} 

imageSource.EndInit(); genera un error "No encontramos ningún componente de imagen adecuada para completar esta operación "

+2

¿Qué formato es la imagen que está tratando de ¿carga? ¿Estás seguro de que es compatible? – Shimmy

Respuesta

0

Debería proporcionarnos más información sobre su imagen.
Supongo que no es compatible con el sistema, que luego le aconsejaría que utilice una herramienta externa, como imageMagik o cualquier otro convertidor específico de su imagen.

0

que he hecho algo similar, pero no es con BitmapImage, espera que pueda ayudar ...

En primer lugar, me sale la imagen de un camino, por lo que obtener una BMP y echado en un byte [] :

private byte[] LoadImage(string szPathname) 
    { 
    try 
    { 
     Bitmap image = new Bitmap(szPathname, true); 

     MemoryStream ms = new MemoryStream(); 
     image.Save(ms, ImageFormat.Bmp); 
     return ms.ToArray(); 
    }catch (Exception){...} 

    return null; 
    } 

yo llamo a esto en mi código como este:

byte[] bitmapData1 = LoadImage(@"C:\Users\toto\Desktop\test1.bmp"); 

Y cuando quiero emitir el byte [] en System.Windows.Controls.Image hago esto:

protected virtual void OnByteArrayChanged(DependencyPropertyChangedEventArgs e) 
    { 
    try 
    { 
     // PropertyChanged method 
     BitmapImage bmpi = new BitmapImage(); 
     bmpi.BeginInit(); 
     bmpi.StreamSource = new MemoryStream(ByteArray); 
     bmpi.EndInit(); 

     System.Windows.Controls.Image image1 = (get my image in my xaml); 
     image1.Source = bmpi; 
    }catch (Exception){...} 
    } 
24

Establezca Image.Source en una propiedad de matriz de bytes en XAML.

<Image x:Name="MyImage" Source="{Binding Path=MyByteArrayProperty}" /> 

Si realmente desea, puede hacerlo en código detrás de esta manera

public void DecodePhoto(byte[] byteVal) 
     { 
      if (byteVal == null) 
{ 
return ; 
} 


      try 
      { 
       MemoryStream strmImg = new MemoryStream(byteVal); 
       BitmapImage myBitmapImage = new BitmapImage(); 
       myBitmapImage.BeginInit(); 
       myBitmapImage.StreamSource = strmImg; 
       myBitmapImage.DecodePixelWidth = 200; 
       myBitmapImage.EndInit(); 
       MyImage.Source = myBitmapImage; 
      } 
      catch (Exception) 
      { 
      } 
     } 
+0

¿Cómo se puede establecer Image.Source en un byte [] cuando es de tipo ImageSource? – TimothyP

+3

@TimothyP Quiero decir en el XAML. 0x4f3759df

0

Esto también podría ayudar:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.Windows.Navigation; 
using System.Windows.Shapes; 

using System.Drawing; 
using System.Runtime.InteropServices; 
using System.IO; 
using System.ComponentModel; 


public class MakeBitmapSource 
{ 
    [DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory")] 
    public static extern void CopyMemory(IntPtr Destination, IntPtr Source, uint Length); 



    public static BitmapSource FromNativePointer(IntPtr pData, int w, int h, int ch) 
    { 
     PixelFormat format = PixelFormats.Default; 

     if (ch == 1) format = PixelFormats.Gray8; //grey scale image 0-255 
     if (ch == 3) format = PixelFormats.Bgr24; //RGB 
     if (ch == 4) format = PixelFormats.Bgr32; //RGB + alpha 


     WriteableBitmap wbm = new WriteableBitmap(w, h, 96, 96, format, null); 
     CopyMemory(wbm.BackBuffer, pData, (uint)(w * h * ch)); 

     wbm.Lock(); 
     wbm.AddDirtyRect(new Int32Rect(0, 0, wbm.PixelWidth, wbm.PixelHeight)); 
     wbm.Unlock(); 

     return wbm; 
    } 

    public static BitmapSource FromArray(byte[] data, int w, int h, int ch) 
    { 
     PixelFormat format = PixelFormats.Default; 

     if (ch == 1) format = PixelFormats.Gray8; //grey scale image 0-255 
     if (ch == 3) format = PixelFormats.Bgr24; //RGB 
     if (ch == 4) format = PixelFormats.Bgr32; //RGB + alpha 


     WriteableBitmap wbm = new WriteableBitmap(w, h, 96, 96, format, null); 
     wbm.WritePixels(new Int32Rect(0, 0, w, h), data, ch * w, 0); 

     return wbm; 
    } 
}