prunk has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I have a question using the Image::Resize GD graphics library. Following the code presented in the example off of CPAN, I would like to retain the name of the file "large.jpg" as the name of the file being sent to standard output after it has been resized. Instead of thumbnail.jpg it would be large.jpg. I have tried various ways of doing working at this and I cannot wrap my head around it. Does $image contain the contents of the large.jpg? Why not type this below? Thank you in advance.

#!/usr/bin/perl -w use strict; use GD::Image; use Image::Resize; my $image = Image::Resize->new('20191212_150024.jpg'); $image = $image->resize(197,262); open(FH, '>'.$image); print FH $image->jpeg(); close(FH); # Result of running this code: Died at /usr/local/share/perl/5.26.1/Im +age/Resize.pm line 25. #original code below and it works from CPAN $image = Image::Resize->new("large.jpg"); $gd = $image->resize(120, 120); open(FH, '>thumbnail.jpg'); print FH $gd->jpeg(); close(FH);

Replies are listed 'Best First'.
Re: Image::Resize Question
by GrandFather (Saint) on Jun 07, 2022 at 22:01 UTC

    Names are important. Avoid reusing variables for different jobs and give each variable a meaningful name. Your code could be better written:

    #!/usr/bin/perl -w use strict; use GD::Image; use Image::Resize; my $imagePath = '20191212_150024.jpg'; my $rawImage = Image::Resize->new($imagePath); my $smallImage = $rawImage->resize(197, 262); open my $outFH, '>', $imagePath or die "Can't create '$imagePath': $!" +; print $outFH $smallImage->jpeg(); close $outFH;

    Note also the use of a lexical file handle ($outFH) and three parameter open with error checking. Lexical file handles help reduce weird bugs due to global file handle lifetimes. Three parameter open is much more robust against strange file names and error checking can save several debug iterations when files are not called what you expect or are not where you expect.

    Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond
      Thank you to all for your advice! Appreciate it!
Re: Image::Resize Question
by hippo (Archbishop) on Jun 07, 2022 at 21:46 UTC
    open(FH, '>'.$image);

    At that point, $image is an Image::Resize object, not a filename. Store your filename in a separate variable if you want to (try to) read from it and then write over it.


    🦛