1

Width and Height of an image inside a jpg file can be retrieved by reading all file data into an Image.

System.Drawing.Image img = System.Drawing.Image.FromFile("a.jpg");
var w = img.Width
var h = img.Height

This is costly however and if only width and height are needed, there might be a better way.

So I wonder if there is a less resource intensive way to get the image dimensions. In my (common) scenario, the jpg is uploaded to the web server and the web application shall just get width and height and store that. I thought, the jpg file format might have width and height as easy readable metadata and if so, someone knows how to access it.

citykid
  • 9,916
  • 10
  • 55
  • 91
  • 1
    You could read the file metadata. You'll have to read the file as a binary stream and look up the standard re: the header. Not sure if any libraries exist to do this for you. – Ed S. Apr 23 '15 at 17:03
  • @bradley you are right. the link is helpful. its a bit tougher than expected, but anyway, great answer there. thx – citykid Apr 23 '15 at 17:09
  • 1
    The problem is the answer linked to is WRONG for JPEG. Original poster should repost but only with the JPEG tag so you don't get zapped by a bunch of YAHOOs who don't know what they are doing. – user3344003 Apr 23 '15 at 17:48
  • 1
    I am limited here but the problem with the "answer" is that it only handles a limited set of JPEG files. First look for an SOI market to be sure its a JPEG stream (Not just a JFIF stream as in the "answer"). Then you need to scan the stream for a SOF marker (there are three types-the "answer" only has one). The image size is in the SOF marker in big endian format. – user3344003 Apr 24 '15 at 01:24
  • very helpful, thx a lot! will digg into the jpeg file format soon. will use System.Drawing.Image.FromFile to test if my results from file reading are correct. – citykid Apr 24 '15 at 11:00

1 Answers1

2

You may want to parse the file header directly instead of constructing an image, the width and height are in there http://en.wikipedia.org/wiki/JPEG_File_Interchange_Format#File_format_structure

Ronan Thibaudau
  • 3,413
  • 3
  • 29
  • 78
  • 1
    thx. looks like width and height are indirectly specified, as Density units, X and Y density. – citykid Apr 23 '15 at 17:07