首页  :: 新随笔  :: 订阅 订阅  :: 管理

Bitmap.save(): A generic error occurred in GDI+

Posted on 2007-11-05 15:51  礼拜一  阅读(4682)  评论(0编辑  收藏  举报

Try the following code

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, 1010)
oBitmap.Save(
"c:\\example.jpg",ImageFormat.Jpeg)
oBitmap.Dispose()
oGraphic.Dispose()

You will get the above mentioned error:A generic error occurred in GDI+. 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.

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(00, _
 bmpNew.Width, bmpNew.Height), 
00, 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, 1010)
oGraphic.Dispose()
ofont.Dispose()
oBrush.Dispose()
oBitmap.Save(
"c:\\example.jpg", ImageFormat.Jpeg)
oBitmap.Dispose()