Skip to content

Instantly share code, notes, and snippets.

@freshdevelop
Created November 23, 2012 11:12
Show Gist options
  • Select an option

  • Save freshdevelop/4135171 to your computer and use it in GitHub Desktop.

Select an option

Save freshdevelop/4135171 to your computer and use it in GitHub Desktop.
PHP image resizer
<?php
/*
This works like a callable url to embed in img tag that returns a jpeg image
resized proportionally and/or cropped accordingly to "width" and "height" parameters
Usage: resize.php?image=images/my-kitten-image.jpg&width=200&height=100
*/
$filename = $_GET['image'];
$new_w = $_GET['width'];
$new_h = $_GET['height'];
list($image_w, $image_h) = getimagesize($filename);
if (empty($new_w) && empty($new_h)) { $new_w = $image_w; $new_h = $image_h; }
$image_ratio = $image_w / $image_h;
if (empty($new_w)) { $new_w = $new_h * $image_ratio; }
if (empty($new_h)) { $new_h = $new_w / $image_ratio; }
$new_ratio = $new_w / $new_h;
$margin_x = $margin_y = 0;
$cropped_w = $image_w;
$cropped_h = $image_h;
if ($new_ratio >= $image_ratio) {
// l'immagine richiesta è più larga
$cropped_h = $image_w / $new_ratio;
$margin_y = $image_h - $cropped_h;
} else {
// l'immagine richiesta è più alta
$cropped_w = $image_h * $new_ratio;
$margin_x = $image_w - $cropped_w;
}
$image_p = imagecreatetruecolor($new_w, $new_h);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, $margin_x / 2, $margin_y / 2, $new_w, $new_h, $cropped_w, $cropped_h);
Header ("Content-type: image/jpeg");
imagejpeg($image_p, null, 80);
?>
@freshdevelop
Copy link
Author

This works like a callable url to embed in img tag that returns a jpeg image resized proportionally and/or cropped accordingly to "width" and "height" parameters.

Usage: resize.php?image=images/my-kitten-image.jpg&width=200&height=100

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment