Skip to content

Instantly share code, notes, and snippets.

Created December 31, 2012 05:01
Show Gist options
  • Save anonymous/4417444 to your computer and use it in GitHub Desktop.
Save anonymous/4417444 to your computer and use it in GitHub Desktop.
A tool I wrote to extract embedded images from raw canon image files, and then scale and rotate them appropriately for uploading to Facebook. It spawns an appropriate number of threads based upon how many cores your machine has. Written because it was easier than figuring out how to compile the 3.0.0 release candidate of digikam.
# /usr/bin/perl -w
use 5.010;
use strict;
use warnings;
use threads;
use Thread::Queue;
use autodie qw(:all);
use Image::ExifTool qw(ImageInfo);
use Data::Dumper;
use Imager;
use File::Slurp qw(read_file);
# Imager needs to be preloaded if we're using threads.
Imager->preload;
# Set up our work queue. Right now it's just @ARGV.
my $work_queue = Thread::Queue->new;
$work_queue->enqueue(@ARGV);
$work_queue->end;
# Spawn our threads, each of which will process files until we're done.
my @threads;
my $cores = get_cores();
for (1..$cores) {
push(@threads,
threads->create( sub {
while (my $src = $work_queue->dequeue) {
process_image($src);
}
})
);
}
# Join threads.
foreach my $thread (@threads) { $thread->join; }
sub process_image {
my ($raw) = @_;
my ($new) = $raw =~ m{(.*).CR2$}i;
next if not $new; # Skip non-CR2 files
$new .= ".jpg";
say "$raw -> $new...";
my $exif = ImageInfo($raw, [qw(PreviewImage Orientation)], { Binary => 1 });
my ($rotation) = ( $exif->{Orientation} =~ /(\d+)/ );
my $img = Imager->new();
$img->read(data => ${$exif->{PreviewImage}})
or die $img->errstr;
$img
->scale(type=>'min', xpixels=>2048, ypixels=>2048)
->rotate(degrees => $rotation)
->write(file=>$new, type=>'jpeg')
;
return;
}
sub get_cores {
my $cpuinfo = read_file("/proc/cpuinfo");
my $max_threads;
# Walk through all the cores to figure out how many we have.
while ($cpuinfo =~ m{^processor\s*:\s*(?<cores>\d+)}msgi ) {
$max_threads = $+{cores}+1;
};
return $max_threads;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment