file header of grafic-files

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi NG,
how can i compare, if a file ends with jpg,jpeg,gif,tif is really such a
file and not an unnamed one. Is ther a solution or an example who to do it in
c#?

Frank
 
Hi Frank,
if you try to open a file as an image that is really not an image file i.e.

Image i = Image.FromFile(@"c:\somefakepicture.jpg");

where somefakepicture.jpg is not really a jpg image, an OutOfMemoryException
will be thrown, so you can catch that. The only issue with this is that you
cannot be sure it is a bad file or if you are really out of memory, but in
this case you can report a more generic message to the user along the lines
of:

"There was an issue opening the file, please verify it is a valid image
file and that the system has free memory available"

HTH
Mark.
 
Hi Frank,

You need to parse the header info. The header will differ between image
types, but for gif files, the first six bytes should be either "GIF87a" or
"GIF89a". For jpg the first bytes should be FF D8 FF E0 with "JFIF" at
position 7-11. I'm a bit uncertain about the tiff header structure, but
you should be able to find it with a bit of web searching. There is an
excellent web site somewhere with most file formats imaginable.

The bottom line is you need to read the first bytes of the file and
compare the bytes against known values.
 
Hi Frank,
if you try to open a file as an image that is really not an image file
i.e.

Image i = Image.FromFile(@"c:\somefakepicture.jpg");

where somefakepicture.jpg is not really a jpg image, an
OutOfMemoryException
will be thrown, so you can catch that. The only issue with this is that
you
cannot be sure it is a bad file or if you are really out of memory, but
in
this case you can report a more generic message to the user along the
lines
of:

"There was an issue opening the file, please verify it is a valid image
file and that the system has free memory available"

HTH
Mark.


This will work if you are checking for valid pictures, although I would
not bet on getting an OutOfMemoryException in all cases. However, it will
not detect if a gif is really a jpg as the Image class will read the
header to determine the proper file type regardless of the file extension.
 
It would be nice if there was a Image.IsValidImageType method that you could
use to validate these kind of scenarios.

Mark.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top