Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's code from my personal grab bag of image resizing code. First, data you need:</p> <pre><code>list($originalWidth, $originalHeight) = getimagesize($imageFile); $ratio = $originalWidth / $originalHeight; </code></pre> <p>Then, this algorithm fits the image into the target size as best it can, keeping the original aspect ratio, not stretching the image larger than the original:</p> <pre><code>$targetWidth = $targetHeight = min($size, max($originalWidth, $originalHeight)); if ($ratio &lt; 1) { $targetWidth = $targetHeight * $ratio; } else { $targetHeight = $targetWidth / $ratio; } $srcWidth = $originalWidth; $srcHeight = $originalHeight; $srcX = $srcY = 0; </code></pre> <p>This crops the image to fill the target size completely, not stretching it:</p> <pre><code>$targetWidth = $targetHeight = min($originalWidth, $originalHeight, $size); if ($ratio &lt; 1) { $srcX = 0; $srcY = ($originalHeight / 2) - ($originalWidth / 2); $srcWidth = $srcHeight = $originalWidth; } else { $srcY = 0; $srcX = ($originalWidth / 2) - ($originalHeight / 2); $srcWidth = $srcHeight = $originalHeight; } </code></pre> <p>And this does the actual resizing:</p> <pre><code>$targetImage = imagecreatetruecolor($targetWidth, $targetHeight); imagecopyresampled($targetImage, $originalImage, 0, 0, $srcX, $srcY, $targetWidth, $targetHeight, $srcWidth, $srcHeight); </code></pre> <p>In this case the <code>$size</code> is just one number for both width and height (square target size). I'm sure you can modify it to use non-square targets. It should also give you an inspiration on what other resizing algorithms you can use.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload