在WPF中的Image容器中显示图像

时间:2012-04-25 14:00:04

标签: c# sql wpf

我正在尝试在WPF图像容器中显示图像

string imageContent = ((DataRowView)dgQuestions.SelectedItem)["QuestionImage"].ToString();
if (imageContent.Length >= 5)
{
    byte[] data = (byte[])((DataRowView)dgQuestions.SelectedItem)["QuestionImage"];
    ImageSourceConverter imgConv = new ImageSourceConverter();
    imageSource = (ImageSource)imgConv.ConvertFromString(data.ToString());
}

上述代码的最后一行产生以下错误

  

对象引用未设置为对象的实例

我并不担心数据网格如何显示图像,因为用户永远不会看到它。

这就是我填充网格的方式:

SqlCommand cmd = new SqlCommand();
cmd.Connection = Con;
cmd.CommandText = "getQuizQuestions";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@quizid", SqlDbType.Int)).Value = quizId;
cmd.ExecuteNonQuery();
SqlDataAdapter daSubject = new SqlDataAdapter(cmd);
DataSet dsSubject = new DataSet();
daSubject.Fill(dsSubject, "QuizSubject");
dgQuestions.ItemsSource = dsSubject.Tables[0].DefaultView;

1 个答案:

答案 0 :(得分:1)

设置断点并验证数据不为空。另外,为什么不将图像源设置为byte []而不是使用ToString():

public BitmapImage ImageFromBuffer(Byte[] bytes)
{
    MemoryStream stream = new MemoryStream(bytes);
    BitmapImage image = new BitmapImage();
    image.BeginInit();
    image.StreamSource = stream;
    image.EndInit();
    return image;
}

public Byte[] BufferFromImage(BitmapImage imageSource)
{
    Stream stream = imageSource.StreamSource;
    Byte[] buffer = null;
    if (stream != null && stream.Length > 0)
    {
        using (BinaryReader br = new BinaryReader(stream))
        {
            buffer = br.ReadBytes((Int32)stream.Length);
        }
    }

    return buffer;
}