Bitmap.save() ----- A generic error occurred in GDI+ 问题解决方法

本文介绍了解决在使用GDI+库保存Bitmap时出现的“AgenericerroroccurredinGDI+”错误的方法。该问题通常发生在尝试覆盖已锁定的文件时。通过创建新的Bitmap对象,并释放原始Bitmap对象的资源锁,可以有效地解决这一问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近的一个项目中在处理数据绘制图表时,在进行bitmap.save()时偶尔遇到上述问题“ A generic error occurred in GDI+”。由于项目中代码量较大,这里只转载网络上解决文章中的VB代码。

原文链接地址:http://blog.vishalon.net/index.php/bitmapsave-a-generic-error-occurred-in-gdi+ 

1、原因: 

This problem occurs because until the bitmap object is disposed, it creates a lock on the underlying image file. So you can save the newly generated file with different name but not overwrite the file because of lock.Now suppose you want to overwrite the file then create another bitmap from old bitmap. dispose the object of old bitmap, process new bitmap object and save the new bitmap object with original file name. The above chunk of code should be written in the following way.

2、源代码

Dim oBitmap As Bitmap                
oBitmap = New Bitmap("c:\example.jpg")                
Dim oGraphic As Graphics        
oGraphic = Graphics.FromImage(oBitmap)        
Dim oBrush As New SolidBrush(Color.Black)                
Dim ofont As New Font("Arial", 8)                
oGraphic.DrawString("Some text to write", ofont, oBrush, 10, 10)                
oBitmap.Save("c:\example.jpg",ImageFormat.Jpeg)        
oBitmap.Dispose()        
oGraphic.Dispose()
 

 3、处理后代码

Dim oBitmap As Bitmap oBitmap = New Bitmap("c:\example.jpg"
Dim oGraphic As Graphics 
' Here create a new bitmap object of the same height and width of the image. 
Dim bmpNew As Bitmap = New Bitmap(oBitmap.Width, oBitmap.Height) 
oGraphic = Graphics.FromImage(bmpNew) 
oGraphic.DrawImage(oBitmap, New Rectangle(0, 0, _ bmpNew.Width, bmpNew.Height), 0, 0, oBitmap.Width, _ oBitmap.Height, GraphicsUnit.Pixel) 
' Release the lock on the image file. Of course, 
' image from the image file is existing in Graphics object 
oBitmap.Dispose() 
oBitmap = bmpNew 
Dim oBrush As New SolidBrush(Color.Black) 
Dim ofont As New Font("Arial", 8) 
oGraphic.DrawString("Some text to write", ofont, oBrush, 10, 10) 
oGraphic.Dispose() 
ofont.Dispose() 
oBrush.Dispose() 
oBitmap.Save("c:\example.jpg", ImageFormat.Jpeg) 
oBitmap.Dispose()
 


转载于:https://www.cnblogs.com/fsyiyun/archive/2011/09/16/2178809.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值