简体   繁体   English

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

[英]Display an image in a Image container in WPF

I am trying to display an image in an WPF Image container 我正在尝试在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());
}

The last line of the above code generates the following error 上面的代码的最后一行生成以下错误

object reference not set to an instance of an object 你调用的对象是空的

I'm not bothered with how the datagrid displays the image as the user will never see the it. 我不担心datagrid如何显示图像,因为用户将永远不会看到它。

This is how I am filling the grid: 这就是我填充网格的方式:

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;

Set a breakpoint and validate data isn't null. 设置断点并验证数据不为空。 Also, why don't you set the image source as the byte[] instead of using a ToString(): 另外,为什么不将图像源设置为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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM