From: John Joyce Date: 2007-07-19T08:36:39+09:00 Subject: Re: Validating an Image file is an image file On Jul 18, 2007, at 4:13 PM, Daniel Berger wrote: > On Jul 18, 10:20 am, John Joyce > wrote: > > > >> The file command and bindings to it are OK, but results are not >> consistent across common image file types. What's worse is that the >> code would be unportable. Ideally, the solution would rely simply on >> the file format internally and thus be portable. > > How's this for a portable version? I based this on a 5 minute overview > of the Wikipedia content at http://en.wikipedia.org/wiki/ > Magic_number_(programming), > combined with some trial and error. > > class File > def self.image?(file) > bmp?(file) || jpg?(file) || png?(file) || gif?(file) > end > > def self.bmp?(file) > IO.read(file, 3) == "BM6" && File.extname(file).downcase == > '.bmp' > end > > def self.jpg?(file) > IO.read(file, 10) == "\377\330\377\340\000\020JFIF" && > File.extname(file).downcase == '.jpg' > end > > def self.png?(file) > IO.read(file, 4) == "\211PNG" && File.extname(file).downcase == > '.png' > end > > def self.gif?(file) > ['GIF89a', 'GIF97a'].include?(IO.read(file, 6)) && > File.extname(file).downcase == '.gif' > end > end > > Regards, > > Dan > > Cool, Dan, that looks pretty slick. I certainly couldn't have done that so quickly, but I knew what basically was needed. That looks like about what I was thinking of conceptually. Very nice and clean code! Nice touch with downcasing file extensions too! I hate that cameras all like to upcase filenames... (> <)! That will probably run a lot lighter than RMagick methods, I'll try it out later. I've been fiddling with the RMagick API all afternoon. There's a lot of documentation but some of it is lacking in clear examples. At this point I know how to scale images and keep the aspect ratio within a maximum new size, but I'd like to have the final output be square with matting on the sides for portrait orientation, matting on the top and bottom for landscape orientation, either one with the scaled image centered. Will this require subsequent compositing after scaling? Or did I miss a method somewhere in the docs that does all of this at once? John Joyce