Expensive resizing to multiple output files

PerlMagick is an object-oriented Perl interface to ImageMagick. Use this forum to discuss, make suggestions about, or report bugs concerning PerlMagick.
Post Reply
yosh
Posts: 2
Joined: 2017-06-08T07:37:36-07:00
Authentication code: 1151

Expensive resizing to multiple output files

Post by yosh » 2017-06-08T07:57:00-07:00

Hello, I'm looking for less expensive way to resize one image to multiple output files.

Let's say I have one input JPEG image (i.e. 3500 x 2500 px, around 3MB). Is there a way to read this file once and resize it to multiple output formats, without reading the source file again? Currently I'm doing something like this:

Code: Select all

my $img = Image::Magick->new;
foreach my $outputfile(@outfiles) {
  $img->Read($inputfile);
  $img->Scale(geometry => "${scale}x${scale}");
  $img->Write($outputfile);
  @$img = ();
}
undef $img;
The problem is with Read() which takes around 0.5 second (which is fast, but with 10 output formats reading alone takes 5 seconds).

If I put Read() outside loop then I do operations on the same picture. It's fast, but each scaling is using already scaled image. It causes problems when 1 format is very small and the next one is larger. I believe there has to be a way to always reach for source image without using the expensive Read() every time.

Thanks in advance for any hints or suggestions.

Yosh

yosh
Posts: 2
Joined: 2017-06-08T07:37:36-07:00
Authentication code: 1151

Re: Expensive resizing to multiple output files

Post by yosh » 2017-06-08T08:10:19-07:00

Ok, actually just after I wrote this I've found the Clone() method and changed the scaling to:

Code: Select all

my $img = Image::Magick->new;
$img->Read($inputfile);
foreach my $outputfile(@outfiles) {
  my $temp = $img->Clone();
  $temp->Scale(geometry => "${scale}x${scale}");
  $temp->Write($outputfile);
  undef $temp;
}
undef $img;
I'll leave this here in case it helps someone. Perhaps there is a better way?

snibgo
Posts: 9249
Joined: 2010-01-23T23:01:33-07:00
Authentication code: 1151
Location: England, UK

Re: Expensive resizing to multiple output files

Post by snibgo » 2017-06-08T08:12:10-07:00

You found the answer before I had time to post it. It is the obvious solution.

======

The answer is to read once, before the loop. Inside the loop, clone the image and operate on that.

For cloning in perl, see http://www.imagemagick.org/script/perl- ... cellaneous
snibgo's IM pages: im.snibgo.com

Post Reply