[Javascript] Image detection

Roland Neilands rneilands at pulsemining.com.au
Thu Apr 7 19:33:07 CDT 2005


Thankyou Terry, Shawn, Andrew. 
You know more than Google and my Javascript books (about this at least) ;)

Andrew, you are right about the CGI apps too, I hadn't considered that & it will be an issue in some cases.

Cheers,
Roland

> -----Original Message-----
> From: javascript-bounces at LaTech.edu
> [mailto:javascript-bounces at LaTech.edu]On Behalf Of Andrew Clover
> Sent: Friday, 8 April 2005 2:42 AM
> To: [JavaScript List]
> Subject: Re: [Javascript] Image detection
> 
> 
> Roland Neilands <rneilands at pulsemining.com.au> wrote:
> 
> > Does anyone know of a simple way of detecting in Javascript
> > if a given file is an image or not?
> 
> Try setting the src of an <img> to point to the file in question. If you 
> get an onload event, it was an image in a format the browser recognises. 
> If you get an onerror event, it wasn't (or the resource was unfetchable).
> 
> > Is checking a list of files extensions the only way?
> 
> Pedantically speaking, it isn't a way at all - a URI's file extension 
> may not have anything to do with the type of the resource it returns. A 
> common example is a .cgi script, which could spit out a file with any 
> MIME type. I don't know if there are cases like this in your intranet 
> though.
> 
> If you *do* go for guessing-from-extension, a regexp might not be the 
> clearest solution. The shortest solution, perhaps, but traditionally not 
> necessarily the most correct. For example the version you posted:
> 
>  > new RegExp("jpg|gif|bmp|tif","i");
> 
> would match anywhere in the string, so 'stiff_gift.exe' would be 
> considered an image. One way to do it without regexps might be:
> 
>    var path= uri.split('?', 1)[0];  // remove any query string
>    var parts= path.split('.');
>    var ext= path[path.length-1];    // get the last .xxx part
>    var isim= ext=='jpg'||ext=='jpeg'||ext=='gif'||ext=='png'||ext=='bmp';
> 
> If you want TIFF in there too you should probably test for .tiff as well 
> as .tif, but typically web browsers won't display this format anyway.
> 
> -- 
> Andrew Clover
> mailto:and at doxdesk.com
> http://www.doxdesk.com/
> _______________________________________________
> Javascript mailing list
> Javascript at LaTech.edu
> https://lists.LaTech.edu/mailman/listinfo/javascript
> 




More information about the Javascript mailing list