How to Fix this Error quot;A generic error occurred in GDI+quot;?(如何修复此错误“GDI+ 中发生一般错误?)
问题描述
Open An Image from default name and save it by default name.(overwrit it)
I need make graphics from Image("Default.jpg") that put it on picturebox1.image and draw some graphic on picurebox1.(it works and it is not my problem) But I can't save picturebox1.Image overwrite on "Default.jpg"(this is My problem).If I change the save name it work but I need to overwrite it and open it manytimes. Thank You
Boolean Play = false;
Pen P = new Pen(Color.Black, 2);
Graphics Temp;
int X1, X2, Y1, Y2;
Image Default_Image = new Bitmap("Default.jpg");
public Form1()
{
InitializeComponent();
Temp = pictureBox1.CreateGraphics();
}
private void PictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (Play)
{
X2 = e.X;
Y2 = e.Y; ;
Temp.DrawLine(P, X1, Y1, X2, Y2);
pictureBox1.Image.Save("Default.jpg");
Play = false;
}
else
{
Default_Image = new Bitmap("Default.jpg");
Temp = Graphics.FromImage(Default_Image);
pictureBox1.Image =Default_Image;
X1 = e.X;
Y1 = e.Y;
Play = true;
}
}
{"A generic error occurred in GDI+."}
To overwrite an image you need to make sure no connections remain to it. Closing
, Disposing
or Cloning
are not quite enough...
Here is a function that creates a truly independent copy:
Bitmap GetClone(string imageName)
{
if (!File.Exists(imageName)) return null;
Bitmap bmp2 = null;
using (Bitmap bmp = (Bitmap)Bitmap.FromFile(imageName))
{
bmp2 = new Bitmap(bmp.Width, bmp.Height, bmp.PixelFormat);
bmp2.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);
using (Graphics g = Graphics.FromImage(bmp2))
{
g.DrawImage(bmp, 0, 0);
}
}
return bmp2;
}
Now you can do this:
string file = yourImageFileName;
Bitmap bmp = GetClone(file);
using (Graphics g = Graphics.FromImage(bmp))
{
// draw what you want..
g.DrawRectangle(Pens.Red, 11, 11, 199, 199);
}
bmp.Save(file, ImageFormat.Png); // use your own format etc..
You should also take care to not leak old PictureBox.Image
versions.. Here is a helper function:
void SetPBoxImage(PictureBox pbox, Bitmap bmp)
{
Bitmap dummy = (Bitmap)pbox.Image;
pbox.Image = null;
if (dummy != null) dummy.Dispose();
pbox.Image = bmp;
}
这篇关于如何修复此错误“GDI+ 中发生一般错误"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何修复此错误“GDI+ 中发生一般错误"?
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- WebMatrix WebSecurity PasswordSalt 2022-01-01