A generic error occurred in GDI+.

Micro

Member
Joined
May 23, 2013
Messages
8
Programming Experience
Beginner
Hi,
I want to update a bmp in memory to a picture box on mouse move or a button click say in vb.net 2008.

I create a .bmp in file and used following code

Public Sub create_bmp() 'Create a new bitmap
Using Bmp As New Bitmap(PictureBox1.Width, PictureBox1.Height, Imaging.PixelFormat.Format32bppPArgb)
'Set the resolution to 200 DPI
Bmp.SetResolution(200, 200)
'Create a graphics object from the bitmap
Using G = Graphics.FromImage(Bmp)
'Paint the canvas white
G.Clear(Color.White)
'Set various modes to higher quality
G.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
G.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
G.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias


'Create a font
Using F As New Font("Arial", 8)
'Create a brush
Using B As New SolidBrush(Color.Black)
'Draw some text
G.DrawString("XY", F, B, 20, 20)

End Using
End Using
End Using


'Save the file as a bmp
Bmp.Save("f:\test123.bmp", Imaging.ImageFormat.Bmp)


Dim bmp1 As Bitmap = Bitmap.FromFile("f:\test123.bmp")


PictureBox1.Image = bmp1
End Using


End Sub

This works first time ok but when i call above routine again I found err A generic error occurred in GDI+.
on line Bmp.Save("f:\test123.bmp", Imaging.ImageFormat.Bmp)
what goes wrong? plz help..:dispirited:
 
First of all, there's not really any such method as Bitmap.FromFile. FromFile is a member of the Image class, so it would be more correct to call it on that.

As for the issue, when you call Image.FromFile or use the Bitmap constructor that takes a file path, the file is opened and a Stream created to read the data. That Stream remains open until you dispose the Image object, because GDI+ will read more data from it at various times. You are trying to save to that path while the file is still locked by another Image object.

To avoid the issue, replace this:
Dim bmp1 As Bitmap = Bitmap.FromFile("f:\test123.bmp")

PictureBox1.Image = bmp1
with this:
PictureBox1.Load("f:\test123.bmp")
That will not lock the file so you can safely save to that path later.

By the way, please note how I have formatted my code snippets for easy reading. Please do so for us when posting code in future.
 
Hi
I used below code to draw a crosshair on bmp

1 G.DrawLine(Pens.Blue, x - 10, y, x + 10, y)

2 G.DrawLine(Pens.Blue, x, y - 10, x, y + 10)

and I passed (x,y) of mouse pointer to create_bmp() and called the sub on mouse move but after some time same error comes and crosshair moving is somewhat slow....
 
This is exactly why sites like this have an FAQ: so we don't have to explain the same things over and over. Read this section of the FAQ on posting new messages:

Reading and Posting Messages

Follow the link at the end of that section and read the first two sections of that next page, then click on the [xcode] link at the bottom of the second section.
 
Back
Top