Finding image file dimensions

by Richard Russell, October 2018

The routines listed below will return the image dimensions (width and height, in pixels) of the most common image file formats (BMP, JPG, PNG and GIF). If the file cannot be opened, the width and height parameters will be returned unchanged; if necessary this may be detected by initialising them to zero and checking their values on return.

      DEF PROCbmpdims(bmp$, RETURN W%, RETURN H%)
      LOCAL F%
      F% = OPENIN(bmp$) : IF F% = 0 ENDPROC
      PTR#F% = 18 : W% = BGET#F% + 256 * BGET#F%
      PTR#F% = 22 : H% = BGET#F% + 256 * BGET#F%
      CLOSE #F%
      ENDPROC
 
      DEF PROCjpgdims(jpg$, RETURN W%, RETURN H%)
      LOCAL F%
      F% = OPENIN(jpg$) : IF F% = 0 ENDPROC
      PTR#F% = 4
      REPEAT PTR#F% = PTR#F% + 256 * BGET#F% + BGET#F%
      UNTIL BGET#F% = &FF AND (BGET#F% AND &F0) = &C0 OR EOF#F%
      PTR#F% = PTR#F% + 3
      H% = 256 * BGET#F% + BGET#F%
      W% = 256 * BGET#F% + BGET#F%
      CLOSE #F%
      ENDPROC
 
      DEF PROCpngdims(png$, RETURN W%, RETURN H%)
      LOCAL F%
      F% = OPENIN(png$) : IF F% = 0 ENDPROC
      PTR#F% = 18 : W% = 256 * BGET#F% + BGET#F%
      PTR#F% = 22 : H% = 256 * BGET#F% + BGET#F%
      CLOSE #F%
      ENDPROC
 
      DEF PROCgifdims(gif$, RETURN W%, RETURN H%)
      LOCAL F%
      F% = OPENIN(gif$) : IF F% = 0 ENDPROC
      PTR#F% = 6 : W% = BGET#F% + 256 * BGET#F%
      PTR#F% = 8 : H% = BGET#F% + 256 * BGET#F%
      CLOSE #F%
      ENDPROC