0

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

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;
4

1 回答 1

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;
}
于 2012-04-25T14:11:46.887 回答