我正在通过套接字通信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 :关于汉斯回答,我让他做出以下更改:
将我的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,现在就显示它。不知道为什么会这样,但现在它正常工作。
答案 0 :(得分:0)
这是一个例子,您可以尝试我刚刚使用我自己的方法测试了这个,所以用我的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;
}