pictureBox.InvokeRequired not showing img

本文关键字:img showing not InvokeRequired pictureBox | 更新日期: 2024-09-20 18:22:08

我从套接字通信接收到一个image作为byte[],然后我尝试在pictureBox中显示它。当我运行代码时,它显示一条消息错误,只说:"NullReferenceException"

处理异常的catch是ex1,我检查过了,而pic不是null,所以我不知道为什么会发生这种异常。

这是我的代码:

try
{
    if (pictureBox1.InvokeRequired)
    {
        try
        {
            pic = imageEmp;
            addControlHandler c = new addControlHandler(addPic);
            this.Invoke(c);
        }
        catch (Exception exc) { MessageBox.Show(exc.Message); }
    }
    else
    {
        pictureBox1.Image = ByteToImage(imageEmp);
    }
}
catch (Exception ex1) 
{
    MessageBox.Show(ex1.Message);                
}
public void addPic()  //when invokeRequired == true
{
    pictureBox1.Image = ByteToImage(pic); 
}

以下是将byte[]转换为Image:的代码

public Image ByteToImage(byte[] imageBytes)  //convert byte[] to image
{
    MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
    ms.Write(imageBytes, 0, imageBytes.Length);
    Image image = new Bitmap(ms); 
    return image;
}

更新1:关于Hans的回答,我做了以下更改:

将我的ByteToImage更改为Hans的答案,并检查错误在哪里,我在this.Invoke(c)所在的位置添加了这几行:

if (c != null)
{
    try
    {
        this.Invoke(c);
    }
    catch (Exception e_c)
    {
        MessageBox.Show(e_c.Message, "exc from e_c");
    }
}

这给了我一个例外:NullReferenceException

谢谢你的帮助!

更新2:现在它工作了,我发送JPEG图像而不是JPG,它现在显示它。不知道为什么会发生这种情况,但现在一切正常。

pictureBox.InvokeRequired not showing img

这里有一个你可以尝试的例子我刚刚用我自己的方法测试了这个,它很有效,所以用我的btnStudentPic_Click中的代码行替换你的代码,让我知道这是否适用于你。。

对于Compact Framework,请尝试使用

public static byte[] ReadAllBytes(string path)
{
byte[] buffer;
using (FileStream fs = new FileStream(path, FileMode.Open,
FileAccess.Read, FileShare.Read))
{
int offset = 0;
int count = (int)fs.Length;
buffer = new byte[count];
while (count > 0)
{
int bytesRead = fs.Read(buffer, offset, count);
offset += bytesRead;
count -= bytesRead;
}
}
return buffer;
}

//下面的Windows示例不用于CF

    private void btnStudentPic_Click(object sender, EventArgs e)
    {
        Image picture = (Image)BrowseForPicture();
        this.picStudent.Image = picture;
        this.picStudent.SizeMode = PictureBoxSizeMode.StretchImage;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    private Bitmap BrowseForPicture()
    {
       // Bitmap picture = null;
        try
        {
            if (this.fdlgStudentPic.ShowDialog() == DialogResult.OK)
            {
                byte[] imageBytes = File.ReadAllBytes(this.fdlgStudentPic.FileName);
                StudentPic = new Bitmap( this.fdlgStudentPic.FileName);
                StuInfo.StudentPic = imageBytes;
            }
            else
            {
                StudentPic = Properties.Resources.NoPhotoAvailable;
            }
        }
        catch (Exception)
        {
            MessageBox.Show("That was not a picture.", "Browse for picture");
            StudentPic = this.BrowseForPicture();
        }
        return StudentPic;
    }