How could I resolve A generic error occurred in GDI+. in VB.Net? - vb.net

When image field property in class is set with the image raw format of the same image from my database in picture box, it always throws this exception. In contrast, if the image in the picture box has been updated with one I select from my local PC directory, the update function work fine.
Below is my code:
Try
With mEmployee
If Miscellaneous.GetImageName(ofdPhoto).ToLower = "No_Photo.jpg".ToLower Then
.Image = Nothing
Else
Dim stream As New MemoryStream
pbImage.Image.Save(stream, pbImage.Image.RawFormat)
.Image = stream.GetBuffer()
End If
End With
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

Now everything has solved. This GDI+ generic error caused by the picture box itself. Actually, When I bound the record with image from the database and update that record without updating the image in the PictureBox, the image field has been set with old byte() data from the box, and that caused the error.
To solve this, I have declare a byte() type variable to store the temp image byte() data from the database, and when update, if the image has not been changed it will be set with the data from that variable.
This is my code that solve everything:
Try
If Miscellaneous.GetImageName(ofdPhoto).ToLower = "No_Photo.jpg".ToLower Then
.Image = Nothing
Else
If isImageChanged = True Then
Dim stream As New MemoryStream
pbImage.Image.Save(stream, pbImage.Image.RawFormat)
.Image = stream.GetBuffer()
isImageChanged = False
ElseIf isRemoveImage = True Then
.Image = Nothing
isRemoveImage = False
Else
.Image = tempImage
End If
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

Related

File is in Use VB.NET

I am using VB.NET (VS-2012), I use to scan documents in my applicant software. When i scan document i resize the scanned image and save it over the original file. When the user scan all the required documents then the use click the save button. After clicking the save button the application upload the images to database and try to delete the locally created files but stuck with the error that the file is in use.
I am using the following code...
Tw.Init(Me.Handle)
If (Not msgfilter) Then
Me.Enabled = False
msgfilter = True
Application.AddMessageFilter(Me)
End If
If SelectScanner Then
Tw.Select()
SelectScanner = False
End If
Tw.Acquire(chkScanner.Checked)
This function listens the event triggered by tw.acquire()
Public Function PreFilterMessage(ByRef m As Message) As Boolean Implements IMessageFilter.PreFilterMessage
Try
Dim cmd As TwainCommand = Tw.PassMessage(m)
If (cmd = TwainCommand.Not) Then
Return False
End If
Select Case cmd
Case TwainCommand.CloseRequest
EndingScan()
Tw.CloseSrc()
Case TwainCommand.CloseOk
EndingScan()
Tw.CloseSrc()
Case TwainCommand.DeviceEvent
Case TwainCommand.TransferReady
Dim pics As ArrayList = Tw.TransferPictures()
EndingScan()
Tw.CloseSrc()
For i = 0 To pics.Count - 1 Step 1
flName = TempPath & "\" & GetNextFileName(TempPath, lstDocType.Items(cboDocTypes.SelectedIndex).ToString)
Dim img As IntPtr = CType(pics(i), IntPtr)
SaveImage(img)
lstDocuments.Items.Add(flName)
lstDocType.Items.Add(GetDocType(cboDocTypes.SelectedIndex))
SetItemData(lstDocuments, lstDocuments.Items.Count - 1, GetItemData(lstApplicants, lstApplicants.SelectedIndex))
Try
lstDocuments.SelectedIndex = lstDocuments.Items.Count - 1
Catch ex As Exception
End Try
Dim Original As Image = Image.FromFile(flName)
Dim Resized As Image = ResizeImage(Original, New Size(1024, 1407), False)
Original.Dispose()
Resized.Save(flName, ImageFormat.Jpeg)
Resized.Dispose()
img = Nothing
pics = Nothing
Next
Tw.Dispose()
Case 0
Return False
End Select
Return True
Catch ex As Exception
Return False
MsgBox(ex.Message)
End Try
End Function
In this given function you can see that the image is resized and the original image is replaced with the resized one. And then the resize object is disposed but when the software try to delete the image after uploading it to database, an error occurs.
I don't know whats the problem.

PDFsharp Beta 1.50 PdfTextField, Null Exception Error, But Still Works?

I'm using PDFsharp 1.50 beta 3b. I'm mainly using it to access the ability to use newer PDF Documents. I'm not using any newer features. Down converting my PDF docs is killing them and I don't know why. That said;
Private Sub Print_Form()
Dim filename As String = ""
If IO.File.Exists(String.Format("{0}Template\Form.pdf", AppDomain.CurrentDomain.BaseDirectory)) Then
filename = String.Format("{0}Template\Form.pdf", AppDomain.CurrentDomain.BaseDirectory)
Else
MessageBox.Show("You're missing the Templates directory. If you don't know what this means, tell your IT Administrator.", "Missing Files")
Exit Sub
End If
Dim PDFDocument As PdfSharp.Pdf.PdfDocument = PdfSharp.Pdf.IO.PdfReader.Open(filename, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Modify)
Dim form As PdfSharp.Pdf.AcroForms.PdfAcroForm = PDFDocument.AcroForm
If form.Elements.ContainsKey("/NeedAppearances") Then
form.Elements("/NeedAppearances") = New PdfSharp.Pdf.PdfBoolean(True)
Else
form.Elements.Add("/NeedAppearances", New PdfSharp.Pdf.PdfBoolean(True))
End If
Try
'the subsequent line causes the exception to be thrown
CType(form.Fields("StringTest"), PdfSharp.Pdf.AcroForms.PdfTextField).Text = "Test"
Catch ex As Exception
Clipboard.SetText(ex.StackTrace)
End Try
CType(form.Fields("CheckBoxTest"), PdfSharp.Pdf.AcroForms.PdfCheckBoxField).Checked = True
PDFDocument.Save("temp.pdf")
Dim p As New System.Diagnostics.ProcessStartInfo()
p.Verb = "print"
p.WindowStyle = ProcessWindowStyle.Hidden
p.FileName = "temp.pdf"
p.UseShellExecute = True
System.Diagnostics.Process.Start(p)
End Sub
This creates an error;
An unhandled exception of type 'System.NullReferenceException' occurred in PdfSharp.dll
Additional information: Object reference not set to an instance of an object.
at PdfSharp.Pdf.AcroForms.PdfTextField.RenderAppearance()
at PdfSharp.Pdf.AcroForms.PdfTextField.set_Text(String value)
at WOTC_FE.frmInterview.Print_ICF() in d:\Programming\FE\FE\Applications\frmInterview.vb:line 2886
Now what makes this weird and why I'm asking is that this still works with the try/catch block. It will fill the field and the file has the correct text in the PDF file. I just want to know why does it throw this exception?
I figured out the issue. The new PDFSharp uses a different access method for it's controls.
First, our declarations;
Dim PDFDocument As PdfSharp.Pdf.PdfDocument = PdfSharp.Pdf.IO.PdfReader.Open(filename, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Modify)
Dim form As PdfSharp.Pdf.AcroForms.PdfAcroForm = PDFDocument.AcroForm
For checkboxes;
CType(form.Fields(<Field Name>), PdfSharp.Pdf.AcroForms.PdfCheckBoxField).Checked = True
And for strings;
PDFDocument.AcroForm.Fields("Field Name").Value = New PdfSharp.Pdf.PdfString("Input Text")
Doing it this way works, doesn't need a try/catch block, and doesn't throw an error.

Move files only if they are image format

i just would like to be sure whether i missed something in my code or not. I want to validate before moving my files from one folder to another that file is image. I prepared this function and usegae like below. Can you please tell me is it ok? Do i need some dispose or anything else or its just quit enought. many thanks, cheers.
Function IsValidImage(filename As String) As Boolean
Try
Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(filename)
img.Dispose()
Catch generatedExceptionName As OutOfMemoryException
' Image.FromFile throws an OutOfMemoryException
' if the file does not have a valid image format or
' GDI+ does not support the pixel format of the file.
'
Return False
End Try
Return True
End Function
If IsValidImage("c:\path\to\your\file.ext") Then
'do something
'
Else
'do something else
'
End If
Let the file path be "D:\web\sample\Image\my.Image.png" then you can check whether the file is an image file or not using the following code:
Dim filepath As String = "D:\web\sample\Image\my.Image.png"
Dim imageExtensions() As String = {"bmp", "gif", "jpg", "png", "psd", "psp", "thm", "tif", "yuv"}
Dim pat As String = "\\(?:.+)\\(.+)\.(.+)"
Dim r As Regex = New Regex(pat)
Dim m As Match = r.Match(filepath)
If imageExtensions.Contains(m.Groups(2).Captures(0).ToString()) Then
MsgBox("valid Image")
End If
You are on the right way, but you should make up your mind what you want to whant to gain:
If you want to develop a method telling you wheter the content of a file is considered a .Net recognized picture image, your approach is totally fine.
I start with your (slightly) overworked code:
Function IsValidImage(filename As String) As Boolean
Try
Using img As System.Drawing.Image = System.Drawing.Image.FromFile(filename)
' the file could be opened as image so it is valid
Return True
End Using
Catch notValidException As OutOfMemoryException
' Image.FromFile throws an OutOfMemoryException
' if the file does not have a valid image format or
' GDI+ does not support the pixel format of the file.
'
Return False
End Try
' Every other Exception is considered not to be able too look whether the
' file is an Image or not, so it should be thrown to outside
End Function
Don't misjudge this approach as using Exception for control flow, you are only reacting to the one thrown if the content of the file is not usable for creating an Image. This let's the decision on the framework whether the file is valid for an Imageor not.
Let's refine your Method a little bit, so that you can determine wheter the image in the file does not exceed a given size:
Function IsValidImage(filename As String, maxSize As Size) As Boolean
Try
Using img As System.Drawing.Image = System.Drawing.Image.FromFile(filename)
' Returns True if the image is smaller or equal than maxSize
Return img.Size.Width <= maxSize.Width AndAlso
img.Size.Height <= maxSize.Height
End Using
Catch notValidException As OutOfMemoryException
Return False
End Try
End Function
Also this is not a misuse of Exceptions. It is a practice of fail fast: if I can't get an Image the file is not an Image. Otherwise I check the dimension on the opened Image, making my outcome dependent on operations done with it.
Misusing an Exception for control flow could, but must not be the following:
Sub CheckImage(filename As String)
Try
Using img As System.Drawing.Image = System.Drawing.Image.FromFile(filename)
End Using
Catch notValidException As OutOfMemoryException
Throw New FileIsNoImageException()
End Try
End Sub
Try
CheckImage("c:\path\to\your\file.ext")
'do something
'
Catch invalid As FileIsNoImageException
'do something else
'
End Try
Even this approach has a valid usage if you consider a file not beeing an Image as an error.
But normaly you would do this in functions which give you the Image as return value.
But this is a tottaly no go:
Sub CheckImage(filename As String)
Try
Using img As System.Drawing.Image = System.Drawing.Image.FromFile(filename)
Throw New FileIsImageException() ' DON'T DO SUCH A CRAP
End Using
Catch notValidException As OutOfMemoryException
Throw New FileIsNoImageException()
End Try
End Sub
Try
CheckImage("c:\path\to\your\file.ext")
Catch valid As FileIsImageException
'do something
'
Catch invalid As FileIsNoImageException
'do something else
'
End Try
#Tim, I beg your pardon, but I can't hear this Exception use is a bad practice tale any more.

How to put noone image in image column of datagridview

I have to put an image to specific column of datagridview but not in every row.
If getExists(myTable, CInt(reader.GetValue(0)), dbConn) Then
.Cells("myCol").Value = Image.FromFile("C:\myPath\myIco_16x16.ico")
Else
.Cells("myCol").Value = "" ' error here
End If
With this code I get error while executing probably because I'm try to put a string in image column. Second I try is:
.Cells("myCol").Value = Nothing
This don't cause error but put "error image" picture (with red X) to grid.
Is here a way to put no one image (blank) to datagridview's image column without loading a "blank image" from file or resource?
I've had to do this in the past and just used a 1 pixel transparent PNG. The performance was acceptable in my application even with 18 image columns and ~2000 rows and the background color of the cell shows through it just fine.
You should be able to create a 1x1 pixel transparent PNG fairly easily using a free program such as "Paint.Net".
You could just create a temporary blank bitmap and assign this to rather than loading an image from file.
Friend Function BlankImage() As Image
Try
Dim oBM As New Bitmap(1, 1)
oBM.SetPixel(0, 0, Color.Transparent)
Return oBM
Catch ex As Exception
Return Nothing
End Try
End Function
Slightly better method that can improve performance:
Friend Function BlankImage() As Image
Static oBM As New Bitmap(1, 1)
Try
If oBM Is Nothing Then
oBM.SetPixel(0, 0, Color.Transparent)
End If
Return oBM
Catch ex As Exception
Return Nothing
End Try
End Function

images vb.net file used by another process error

I'm writing a little program where I select a picture through an open file dialogue. When I selected a picture I want it to overwrite the current picture and display the new image. Now I don't have any problems with picking an image with a different extension. So when I currently have a .png I can select a .jpg but when I choose an image with the same extension as the current image I get an error:
The process cannot access the file 'C:\Users....\woontypeimages\chalet_foto.jpg' because it is being used by another process.
If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim sFilename As String = cboWoningtypesWoningtype.SelectedItem.ToString & "_foto" & System.IO.Path.GetExtension(ofd.FileName)
System.IO.File.Copy(ofd.FileName, Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\Camping Relaxx\woontypeimages\" & sFilename, True)
txtWoningtypesFoto.Text = sFilename
updateImages()
End If
Private Sub updateImages()
Try
picFoto.Image = Nothing
txtWoningtypesFoto.BackColor = clrReadonly
txtWoningtypesFoto.ForeColor = Color.Black
picFoto.Image = System.Drawing.Image.FromFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\Camping Relaxx\woontypeimages\" & txtWoningtypesFoto.Text)
Catch ex As Exception
txtWoningtypesFoto.BackColor = clrError
txtWoningtypesFoto.ForeColor = Color.White
End Try
Try
picGrondplan.Image = Nothing
txtWoningtypesGrondplan.BackColor = clrReadonly
txtWoningtypesGrondplan.ForeColor = Color.Black
picGrondplan.Image = System.Drawing.Image.FromFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\Camping Relaxx\woontypeimages\" & txtWoningtypesGrondplan.Text)
Catch ex As Exception
txtWoningtypesGrondplan.BackColor = clrError
txtWoningtypesGrondplan.ForeColor = Color.White
End Try
End Sub
If anyone could help me I would be pleased
Thanks in advance
Instead of worrying about Dispose() you can instead use the Load(string) method of the PictureBox which won't lock the file.
Me.PictureBox1.Load("C:\test.png")
Use these :
picFoto.Image.Dispose()
picGrondplan.Image.Dispose()
instead of :
picFoto.Image = Nothing
picGrondplan.Image = Nothing
The Image.FromFile method maintains a lock on the source file until the image has been disposed. Setting an object to nothing does not immediately dispose it - the garbage collector will take care of that in its own time (which might well not be until you've closed the form with the picture box on). Dispose is required to immediately free the file handle.