phpimage-scaling

what is the right way to scale down an image in php


why is scaling image in php so complicated ? A lot of confusin about

I simply want to scale down an image - if it's width is over 960px

something like this:

$path = "sbar/01.jpg";
$w = getimagesize($path)[0];    
if($w > 960){scale($path, 960, auto);}

what is the simplest way to do this ? Here is my try:

$max = 960;
$h = getimagesize($path)[1];
$ratio = $w/$h;
$new_height = $w/$ratio;
$img = imagecreatetruecolor($max, $new_height);
$image = imagecreatefromjpeg($path); 

And what now? There is still no desired image (960 x auto) in $path


Solution

  • There is no "best" way to do it. There are just different ways to do it. If you have an image that is already stored and you want to scale it and then save the scaled version you can simply do this:

    $image = imagecreatefromjpeg('test.jpg');
    $newImage = imagescale($image, 960, -1);
    imagejpeg($newImage, 'scaled_image.jpg');
    

    You first load the image from a given path. Then you scale it (while the image stays in memory). At the end, you save it under the provided path. Done.

    The -1 (or if you omit the value altogether) means to only scale the other dimension and keep the aspect ratio.