WPF将字节数组从数据库转换为Image控件源

时间:2014-10-24 16:19:26

标签: c# wpf entity-framework

我有一个byte数组存储在实体框架数据库中。对象列表设置为ListView源。列表视图将此模板作为其项目模板:

<DataTemplate x:Key="ItemContentTemplate">
    <Grid Height="auto" Margin="0,0,0,10">
        <Image Width="auto" Height="auto" Source="{Binding InitialImage, Converter={StaticResource ResourceKey=ImageSourceConverter}}" Margin="10"/>
    </Grid>
</DataTemplate>

我使用它作为转换器,但我在EndInit上得到了这个例外:“找不到适合完成此操作的成像组件。”内部异常:{“HRESULT异常:0x88982F50”} System.Runtime.InteropServices.COMException

public class ImageSourceConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo cultureInfo)
    {
        if (value == null)
        {
            return new BitmapImage();
        }

        try
        {
            MemoryStream strmImg = new MemoryStream((byte[])value);
            BitmapImage myBitmapImage = new BitmapImage();
            myBitmapImage.BeginInit();
            myBitmapImage.StreamSource = strmImg;
            myBitmapImage.EndInit();
            return myBitmapImage;
        }
        catch (Exception ex)
        {
            string message = ex.Message;
        }

        return new BitmapImage();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

我不确定这意味着什么......

编辑: 好的,这里有更多的信息。所以我通过directshow从托管代码以Intptr的形式从usb摄像头接收原始数据。然后我将它从指向可写位图的指针复制:

public static void CopyTo(this IBitmapImage image, WriteableBitmap writeableBitmap)
{
   Kernel32.MoveMemory(
            writeableBitmap.BackBuffer,
            image.Data,
            Convert.ToUInt32(
                writeableBitmap.PixelWidth *
                writeableBitmap.PixelHeight *
                (PixelFormats.Bgr24.BitsPerPixel / 8)));
    }

之后我将可写位图的后备缓冲区转换为字节数组并将其保存到数据库中。稍后当需要查看图片时,我会从数据库中抓取它。

var width = cameraOneBitmap.PixelWidth;
var height = cameraOneBitmap.PixelHeight;
var stride = width * ((cameraOneBitmap.Format.BitsPerPixel + 7) / 8);

var bitmapData = new byte[height * stride];

cameraOneBitmap.CopyPixels(bitmapData, stride, 0);

1 个答案:

答案 0 :(得分:2)

使用Image初始化StreamSource时,它需要编码的图像(例如,PNG,JPG等)。只有原始位图数据,你无能为力;您至少还需要尺寸和步幅(或尺寸和钻头深度,您可以从中计算步幅)。

完成后,您可以使用BitmapSource.Create

var bitmapSource = BitmapSource.Create(
    width,
    height,
    horizontalDpi, // typically 96
    verticalDpi,   // typically 96
    PixelFormats.Bgr24,
    /* palette: */ null,
    /* (byte[]) */ bitmapData,
    stride);
相关问题