package Acme::Task::ImageCrop;
use Mojo::Base 'Mojolicious::Plugin';
use XML::FeedPP;
use Mojo::UserAgent;
use Imager;
use File::Fetch;
use File::Temp qw/ tempdir tempfile /;
sub register {
my ($self, $app) = @_;
$app->minion->add_task(image_crop => \&image_crop);
}
sub image_crop {
eval{
_image_crop(@_);
};
if($@){
$_[0]->app->log->debug("Error: " . $@);
}
}
sub _image_crop {
my $job = shift;
my $url = shift;
my $id = shift;
$job->app->log->debug("cropping " . $url . " , id: " . $id);
# download url to a temporary folder
my $dir = tempdir(CLEANUP => 1);
$job->app->log->debug( "temp dir : " . $dir);
my $where = File::Fetch
->new( uri => $url )
->fetch( to => $dir );
# create 2 crops - original size (to strip metadata) and a thumbnail
my $src_image = Imager->new(file => $where) or die Imager->errstr;
my $thumbnail = $src_image->scale( xpixels => 160 );
my $original = $src_image->copy();
my ($t_fh, $thumbnail_file) = tempfile( DIR => $dir, SUFFIX => ".png", CLEANUP => 1 );
my ($o_fh, $original_file) = tempfile( DIR => $dir, SUFFIX => ".png", CLEANUP => 1 ) ;
$thumbnail->write( file => $thumbnail_file ) or die $thumbnail->errstr;
$original->write( file => $original_file ) or die $original->errstr;
# store them in S3
my $bucket_name = "files";
my $bucket = $job->app->s3->bucket($bucket_name) or
die $job->app->s3->err . ": " . $job->app->s3->errstr;
$bucket->add_key_filename($id . '/orig.png', $original_file,
{content_type => 'image/png'})
or die $job->app->s3->err . ": " . $job->app->s3->errstr;
$bucket->add_key_filename($id . '/thumbnail.png', $thumbnail_file,
{content_type => 'image/png'})
or die $job->app->s3->err . ": " . $job->app->s3->errstr;
$job->app->log->debug("Finished cropping and uploading image");
File::Temp::cleanup();
}
1;