0

I found Ian Atkin's solution here - Resize image in PHP - and am trying to modify it to accommodate png and gif, and to save the resized image. Jpg works, but I'm getting black images (of correct size) for png and gif. I can't figure out what am I doing wrong. Here's the code:

function resize_image($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
    if ($width > $height) {
        $width = ceil($width-($width*abs($r-$w/$h)));
    } else {
        $height = ceil($height-($height*abs($r-$w/$h)));
    }
    $newwidth = $w;
    $newheight = $h;
} else {
    if ($w/$h > $r) {
        $newwidth = $h*$r;
        $newheight = $h;
    } else {
        $newheight = $w/$r;
        $newwidth = $w;
    }
}

if($extension=="gif") {
    $src = imagecreatefromgif($file);
} elseif($extension=="png") {
    $src = imagecreatefrompng($file);
} else {
    $src = imagecreatefromjpeg($file);
}

$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

if($extension=="gif") {
    imagegif($dst, $file);
} elseif($extension=="png") {
    imagepng($dst, $file);
} else {
    imagejpeg($dst, $file);
}
return $dst;

}

Thank you very much!

Manya
  • 23
  • 4
  • You should use some sensible formatting when you write your code. Proper indention and avoid having multiple commands on single lines. It currently looks very messy and is quite hard to read. – M. Eriksson Sep 12 '20 at 13:03
  • Sorry, edited it. – Manya Sep 12 '20 at 13:23
  • `if($extension=="gif")` - The variable `$extension` is never defined so this should throw a "undefined variable" warning and then always go to the `else` part of the if-statements (using jpeg) – M. Eriksson Sep 12 '20 at 13:25
  • Oh, I'm sorry, the $extension was set earlier, outside of this function, I should have mentioned it, sorry. I do get png and gif files recognized, saved as png/gif, and their dimensions/proportions are correct. But they are black. – Manya Sep 12 '20 at 13:42
  • Even if it's set outside of the function, it will still be undefined inside the function. [Here's the manual about variable scope](https://www.php.net/manual/en/language.variables.scope.php). – M. Eriksson Sep 12 '20 at 14:19
  • Thank you so much! That was the issue, all working well now. Thank you! – Manya Sep 12 '20 at 14:27

0 Answers0