I have an image resized program and it works. The problem is when a user selects a non-image file in the file select dialog, it crashes. How can I check for image files?
- 2Related: C# How can I test a file is a jpeg?. Your problem is very similar, you only have to add additional checks if you want to support further formats.Dirk Vollmar– Dirk Vollmar2010-08-24 15:06:38 +00:00Commented Aug 24, 2010 at 15:06
- The best way to achieve what you wnat is what's suggested by 0xA3. Wrap the Image.FromFile in a Try block. If it's a valid image, you'll get the image output. If it isn't a valid image, you'll get an OutOfMemory Exception and your code will be safe.Alex Essilfie– Alex Essilfie2010-08-24 16:55:47 +00:00Commented Aug 24, 2010 at 16:55
- (again): If you insist you want VB, check my solution.Alex Essilfie– Alex Essilfie2010-08-24 16:57:26 +00:00Commented Aug 24, 2010 at 16:57
5 Answers
UPDATE: 2022-04-05
Since it may not be feasible to validate the binary structure of every supported image, the fastest way to check if a file contains an image is to actually load it. If it loads successfully, then it is valid. If it doesn't then it is not.
The code below can be used to check if a file contains a valid image or not. This code is updated to prevent locking the file while the method is called. It also handles resource disposal after the tests (thanks for pointing out this issue user1931470).
Public Function IsValidImage(fileName As String) As Boolean Dim img As Drawing.Image = Nothing Dim isValid = False Try ' Image.FromFile locks the file until the image is disposed. ' This might not be the wanted behaviour so it is preferable to ' open the file stream and read the image from it. Using stream = New System.IO.FileStream(fileName, IO.FileMode.Open) img = Drawing.Image.FromStream(stream) isValid = True End Using Catch oome As OutOfMemoryException ' Image.FromStream throws an OutOfMemoryException ' if the file does not have a valid image format. isValid = False Finally ' clean up resources If img IsNot Nothing Then img.Dispose() End Try Return isValid End Function ORIGINAL ANSWER
⚠️⚠️ WARNING ⚠️⚠️
This code has a bug that causes a high memory consumption when called several times in a program's lifetime.
DO NOT USE THIS CODE!!
Here's the VB.NET equivalent of 0xA3's answer since the OP insisted on a VB version.
Function IsValidImage(filename As String) As Boolean Try Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(filename) 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 You use it as follows:
If IsValidImage("c:\path\to\your\file.ext") Then 'do something ' Else 'do something else ' End If Edit:
I don't recommend you check file extensions. Anyone can save a different file (text document for instance) with a .jpg extension and trick you app into beleiving it is an image.
The best way is to load the image using the function above or to open the first few bytes and check for the JPEG signature.
You can find more information about JPEG files and their headers here:
3 Comments
A very primitive check is to simply try to load the image. If it is not valid an OutOfMemoryException will be thrown:
static bool IsImageValid(string filename) { try { System.Drawing.Image img = System.Drawing.Image.FromFile(filename); } catch (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; } return true; } If I understood your question correctly your application it going to load the image anyway. Therefore simply wrapping the load operation in a try/catch block does not mean any additional overhead. For the VB.NET solution of this approach check the answer by @Alex Essilfie.
The ones wondering why Image.FromFile is throwing an OOM on invalid files should read the answer of Hans Passant to the following question:
Is there a reason Image.FromFile throws an OutOfMemoryException for an invalid image format?
2 Comments
OutOfMemoryException but I assume there was reason for it.Your first line of defense, of course, would be simply to check the file's extension:
Function IsImageFile(ByVal filename As String) As Boolean Dim ext As String = Path.GetExtension(filename).ToLowerInvariant() ' This supposes your program can deal only with JPG files; ' ' you could add other extensions here as necessary. ' Return ext = ".jpg" OrElse ext = ".jpeg" End Function Better yet, as SLC suggests in a comment, set your dialog's Filter property:
dialog.Filter = "Image files|*.jpg;*.jpeg" This isn't a guarantee -- ideally you'd want to check the file itself to verify it's an image, and theoretically you should also be able to load files with anomalous extensions if they are in fact image files (maybe just ask for the user's acknowledgement first) -- but it's an easy start.
8 Comments
string.Equals(ext, ".jpg", StringComparison.InvariantCultureIgnoreCase).ToLower as it's less typing than writing out potentially several string.Equals method calls.ToLower() is fine for simple samples like this. However, not only that a new string object is created, it is also not safe and failes the Turkey Test. At least one should use ToLowerInvariant() in production code.ext.Equals(".jpg", StringComparison.InvariantCultureIgnoreCase) || ext.Equals(".jpeg", StringComparison.InvariantCultureIgnoreCase) || [...] -- obviously in a performance-critical scenario, things would be different. I had forgotten about the Turkey test, though!The VB and C# answers are great but also contain a "gotcha" if you plan to alter or move the file: the created 'img' object will lock the image file unless the dispose() method is invoked to release it. See below:
VB Function IsValidImage(filename As String) As Boolean Try Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(filename) img.dispose() ' Removes file-lock of IIS 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 C# static bool IsImageValid(string filename) { try { System.Drawing.Image img = System.Drawing.Image.FromFile(filename); img.dispose(); // Removes file-lock of IIS } catch (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; } return true; } Comments
The most robust way would be to understand the signatures of the files you need to load.
JPEG has a particular header format, for example.
This way your code won't be as easily fooled if you just look at the extension.
163's answer should get you most of the way along these lines.