0

我真的需要帮助,因为我根本无法弄清楚这一点。当它使用资源图像保存到字节arrat时它工作正常但是当有用户定义的图像时它应该使用那个并将它保存到数组并且程序崩溃并且我找不到问题。

编码:

        //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);
            }
        }
    }
4

1 回答 1

1

位图类对流有点挑剔。五年前,我经常使用位图,我认为错误可能是您已经处理了从 OpenFileDialog 打开的原始流。在某些图像格式中,我认为流需要打开才能执行保存等操作。

试着让它保持打开状态(注释掉using(myStream)声明),看看它是否有帮助。

于 2013-02-13T09:52:53.660 回答