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 »

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 »

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: 12159
Joined: 2010-01-23T23:01:33-07:00
Authentication code: 1151
Location: England, UK

Re: Expensive resizing to multiple output files

Post by snibgo »

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
100find
Posts: 2
Joined: 2018-02-06T02:42:38-07:00
Authentication code: 1152

Re: Expensive resizing to multiple output files

Post by 100find »

Several years ago, I met the same problem, and my solution is reading the image file into Mem and use Blob model to load the image from mem several times .
The Clone method is very smart.
Post Reply