2

I have image in buffer after retrieving it from the Web:

my $img = $webapi->get('http://myserver.com/image/123423.jpg');

After the call, raw data is in the $img. I want to make sure the data represents image and not text, so I save it to a file on disk and run file command:

open my $fh, '>', '/tmp/images/rawdata.bin';
print $fh $img;
close $fh;
$res = `file /tmp/images/rawdata.bin`;
if ($res =~ 'GIF|JPEG|PNG') print "Image";
else "Not image";

How do I avoid saving raw data to file and do the work in memory?

rlib
  • 7,444
  • 3
  • 32
  • 40

2 Answers2

11

file can read data from STDIN. So the easiest way might be:

open ( my $file_cmd, '|-', 'file -' ) or die $!;
print {$file_cmd} $img;
print <$file_cmd>;

There appears to be a module - File::Type which does this. My quick testing implies it's not as smart as file making it somewhat less useful.

Sobrique
  • 52,974
  • 7
  • 60
  • 101
  • Not sure, but also seems geared up to MIME types, where `file` does mor . – Sobrique Sep 18 '15 at 09:18
  • Are you referring to the direction of the pipe symbol? Because I'm pretty sure that's the right way around. (opening as `-|` means I can't then `print` to it). – Sobrique Sep 18 '15 at 15:20
0

Here's another approach: A Jpeg start with \xFF \xD8, GIFs start with "GIF89a" or "GIF87a" and PNGs start with these decimals: 137 80 78 71 13 10 26 10.

neuhaus
  • 3,886
  • 1
  • 10
  • 27
  • You've also got `/usr/share/misc/magic` you can refer to on *nix systems. Which is what `file` does. – Sobrique Sep 18 '15 at 13:14