我非常需要帮助,因为我根本无法解决这个问题。当它使用资源图像保存到字节时它工作正常但是当有用户定义的图像时它应该使用那个并将它保存到数组中并且程序崩溃并且我无法找到问题。
代码:
//Check for image and if true save it to byte array
if (pictureBox1.Image != null)
{
using (MemoryStream ms = new MemoryStream())
{
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
arr = ms.ToArray();
}
}
else
{
using (MemoryStream ms = new MemoryStream())
{
AnimalMotel.Properties.Resources.nophotos.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
arr = ms.ToArray();
}
}
ELSE部分在这里工作得很完美,当有用户定义的图像然后它崩溃并且给出这个问题时会出现问题:
An unhandled exception of type
'System.Runtime.InteropServices.ExternalException'
occurred in System.Drawing.dll
Additional information: A generic error occurred in GDI+.
上一个代码:
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "(*.Bmp)|*.Bmp|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
pictureBox1.Image = new Bitmap(myStream);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
答案 0 :(得分:1)
位图类对流有点挑剔。我在五年前使用位图工作很多,我想到错误可能是你已经处理了从OpenFileDialog打开的原始流。在某些图像格式中,我认为需要打开流才能执行save等操作。
尝试将其保持打开状态(注释掉using(myStream)
语句)并查看是否有帮助。