2010-10-08 42 views
3

我将一个BitmapImage保存到一个字节[]以保存在一个数据库中。我很确定数据正在被保存和检索,所以这不是一个问题。错误在我的字节[] WPF BitmapImage转换?

在我的byte [] BitmapImage转换我不断收到“System.NotSupportedException异常:找不到适合完成此操作的成像组件。”

任何人都可以看到我在做什么错我的两个功能在这里?

private Byte[] convertBitmapImageToBytestream(BitmapImage bi) 
    { 
    int height = bi.PixelHeight; 
    int width = bi.PixelWidth; 
    int stride = width * ((bi.Format.BitsPerPixel + 7)/8); 

    Byte[] bits = new Byte[height * stride]; 
    bi.CopyPixels(bits, stride, 0); 

    return bits; 
    } 

    public BitmapImage convertByteToBitmapImage(Byte[] bytes) 
    { 
    MemoryStream stream = new MemoryStream(bytes); 
    stream.Position = 0; 
    BitmapImage bi = new BitmapImage(); 
    bi.BeginInit(); 
    bi.StreamSource = stream; 
    bi.EndInit(); 
    return bi; 
    } 

回答

0

原来的BitmapImage的CopyPixels是不正确的。我将bitmapimage的输出转换为可用的jpg格式。

public static Byte[] convertBitmapImageToBytestream(BitmapImage bi) 
    { 
    MemoryStream memStream = new MemoryStream(); 
    JpegBitmapEncoder encoder = new JpegBitmapEncoder(); 
    encoder.Frames.Add(BitmapFrame.Create(bi)); 
    encoder.Save(memStream); 
    byte[] bytestream = memStream.GetBuffer(); 
    return bytestream; 
    } 
+0

嘿@JPpers,我想看到其他方式转换... – zazkapulsk 2015-11-23 06:27:51

0

这个StackOverflow问题有帮助吗?

byte[] to BitmapImage in silverlight

编辑:

试试这个,不知道它会工作:

public BitmapImage convertByteToBitmapImage(Byte[] bytes) 
{ 
    MemoryStream stream = new MemoryStream(bytes); 
    stream.Position = 0; 
    BitmapImage bi = new BitmapImage(); 
    bi.BeginInit(); 
    bi.CacheOption = BitmapCacheOption.OnLoad; 
    bi.DecodePixelWidth = ??; // Width of the image 
    bi.StreamSource = stream; 
    bi.EndInit(); 
    return bi; 
} 

更新2:

我发现这些:

Load a byte[] into an Image at Runtime

BitmapImage from byte[] on a non UIThread

除此之外,我不知道。

+0

对不起,仍然没有工作。同样的例外 – Jippers 2010-10-08 01:06:17