Skip to content

Instantly share code, notes, and snippets.

@lean8086
Created July 16, 2013 21:19
Show Gist options
  • Save lean8086/6015246 to your computer and use it in GitHub Desktop.
Save lean8086/6015246 to your computer and use it in GitHub Desktop.
Image proxy made for Weat in 2010.
<?php
// Requires "file", "size" and "default" parameters
if (!isset($_REQUEST["file"]) || !isset($_REQUEST["size"]) || !isset($_REQUEST["default"])) {
die("Expected to find \"file\", \"size\" and \"default\" parameters.");
}
// URL of file
$url = $_REQUEST["file"];
// TODO: If image isn't readable, print a default image in $_REQUEST["default"]
// Split URL to get extension
$extension = array_reverse(explode(".", $url));
// Create a new image from extension
switch ($extension[0]) {
default:
case "jpg":
case "jpeg":
$image = @imagecreatefromjpeg($url);
break;
case "png":
$image = @imagecreatefrompng($url);
break;
case "gif":
$image = @imagecreatefromgif($url);
break;
};
// Square size of result image
$size = $_REQUEST["size"];
// Grab the image size
list($width, $height) = getimagesize($url);
// Grab the ratio of image
$ratio = $width / $height;
// Horizontal image
if ($ratio > 1) {
// Same horizontal size
$sizeX = $size;
// Relative vertical size
$sizeY = $size / $ratio;
// Default left position
$x = 0;
// Centered top position
$y = ($size - $sizeY) / 2;
// Vertical
} else {
// Relative horizontal size
$sizeX = $size * $ratio;
// Same vertical size
$sizeY = $size;
// Centered left position
$x = ($size - $sizeX) / 2;
// Default top position
$y = 0;
}
// Create an empty image to generate definitive result
$result = @imagecreatetruecolor($size, $size) or die("Cannot Initialize new GD image stream.");
// Create a white background
$background = imagecolorallocate($result, 255, 255, 255);
// Set white background to empty image
imagefill($result, 0, 0, $background);
// Save into empty image the original image with calculations
imagecopyresampled($result, $image, $x, $y, 0, 0, $sizeX, $sizeY, $width, $height);
// Print image header
header("Content-Type: image/png");
// Print image
imagepng($result, null, 0, PNG_NO_FILTER);
// Destroy original image
imagedestroy($image);
// Destroy generated image
imagedestroy($result);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment