Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying "file" linux command to binary buffer in Perl

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?

like image 569
rlib Avatar asked Jun 09 '26 17:06

rlib


1 Answers

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.

like image 112
Sobrique Avatar answered Jun 12 '26 12:06

Sobrique