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?
相关问题
- Views base64 encoded blob in HTML with PHP
- How to get the background from multiple images by
- 'System.Threading.ThreadAbortException' in
- how to use special characters like '<'
- CV2 Image Error: error: (-215:Assertion failed) !s
相关文章
- vb.net 关于xps文件操作问题
- Angular Material Stepper causes mat-formfield to v
- Why doesn't Django enforce my unique_together
- Use savefig in Python with string and iterative in
- Where does this quality loss on Images come from?
- Specifying image dimensions in HTML vs CSS for pag
- Checking for DBNull throws a StrongTypingException
- How to insert pictures into each individual bar in
A very primitive check is to simply try to load the image. If it is not valid an
OutOfMemoryException
will be thrown: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:Here's the VB.NET equivalent of 0xA3's answer since the OP insisted on a VB version.
You use it as follows:
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:
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:
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.
Your first line of defense, of course, would be simply to check the file's extension:
Better yet, as SLC suggests in a comment, set your dialog's
Filter
property: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.