Question

I need to resize upload image to resolutions bellow the resolution of uploaded image.

Like this:

  • If i upload image of 1920x1200 resolution
  • Script should resize uploaded image to resolutions: 1680x1050, 1440x900 and 1280x800

However:

  • If i upload image of 1680x1050 resolution
  • Script should resize uploaded image to resolutions: 1440x900 and 1280x800

I know how to detect resolution, how to resize and save image on server, but i dont know how to build logic for problem above. Need help there.

Was it helpful?

Solution

Something like this should do:

// All resolutions that you want to generate
$resolutions = [[1920,1200],[1680,1050],[1440,900],[1280,800]];

// Current image dimensions
list($width, $height) = getimagesize('path/to/image.jpg');

foreach ($resolutions as $res) {
  if ($width <= $res[0] || $height <= $res[1]) continue;
  // logic to generate images at different resolutions
}

The idea is to loop and skip until the dimensions fall within the specified range, then generate the different images based on the remaining resolutions.

This works better if the aspect ratio is the same for all images, so you might need to adjust it or maybe just check the width.

Edit: You could also reverse the array and loop from low res to high res and use break with the inverse condition.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top