PictureBox图像无法释放导致图像文件无法修改

来源:互联网 发布:免费出题软件 编辑:程序博客网 时间:2024/06/05 17:55

一般情况下,PictureBox加载的图像,试用以下代码无法释放:

            if (pbImage.Image != null)
            {
                pbImage.Image.Dispose();
                pbImage.Image = null;
            }

解决方法是加载图像时,先将图像加载到内存流,再通过内存流创建新图像,将新图像加载到PictureBox。

        private void LoadImage(DataSet dataSet)
        {
            imagePath = _templetModel.ImageLocalPath + dataSet.Tables[0].Rows[0]["ImagePath"].ToString().Trim();
            if (File.Exists(imagePath))
            {
                MemoryStream memoryStream = new MemoryStream(File.ReadAllBytes(imagePath));
                Bitmap newImage = new Bitmap(memoryStream);
                memoryStream.Close();
                ShowImage(newImage);
            }
            else
            {
                MessageBox.Show("图像不存在,请检查路径是否正确!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


这样即使PictureBox图像无法释放,也能修改原图像。