Search code examples
perlgd

Not recognizing png files for image processing


I'm trying to add png resolution to our image processing code. I'm getting the following error which i do not know how to resolve.

[Tue Aug 27 15:32:03.968126 2019] [cgi:error] [pid 3206] [client] AH01215: Can't call method "getBounds" on an undefined value

Here's my code.

my $file = "$datapath/$rs->{'path'}";
my ($ext) = $file =~ /(\.[^.]+)$/;
if ($ext eq "jpg"){
 my $src=GD::Image->newFromJpeg("$datapath/$rs->{'path'}",1);
} else {
 my $src=GD::Image->newFromPng("$datapath/$rs->{'path'}",1);
}
my ($w,$h)=$src->getBounds();

When I have this code, which is just jpg, it works:

my $file = "$datapath/$rs->{'path'}";
my ($ext) = $file =~ /(\.[^.]+)$/;
my $src=GD::Image->newFromJpeg("$datapath/$rs->{'path'}",1);
my ($w,$h)=$src->getBounds();

UPDATE

Now jpegs arent displaying.

my $file = "$datapath/$rs->{'path'}";
my ($ext) = $file =~ /(\.[^.]+)$/;
my $src;
if ($ext eq "jpg"){
   $src=GD::Image->newFromJpeg("$datapath/$rs->{'path'}",1);
} else {
   $src=GD::Image->newFromPng("$datapath/$rs->{'path'}",1);
}
my $img=GD::Image->new($ow,$oh,1);
$img->copyResampled($src,$x,$y,0,0,$nw,$nh,$w,$h);
$img->edgeImageSharpen(9);
$img->edgeBrightnessContrast(8,1.1);
if($ext eq "jpg"){
  my $jpg=$img->jpeg(90);
  print "Content-Type: image/jpeg\n";
  print "Content-Length: ".length($jpg)."\n\n";
  print $jpg;
} else {
  my $png=$img->png;
  print "Content-Type: image/png\n";
  print "Content-Length: ".length($png)."\n\n";
  print $png;
}

Solution

  • Check what value is being returned to $ext.

    Based on your code:

    my $file = "image_file.jpg";
    my ($ext) = $file =~ /(\.[^.]+)$/;
    say $ext; 
    

    This will print ".jpg" which is why the code without the conditional works as the condtion will fail as it is for "jpg" and not ".jpg"