Skip to content

Instantly share code, notes, and snippets.

@Korko
Created October 9, 2012 12:54
Show Gist options
  • Save Korko/3858632 to your computer and use it in GitHub Desktop.
Save Korko/3858632 to your computer and use it in GitHub Desktop.
Resize an image from an url and return the new picture
<?php
ob_start("ob_gzhandler");
function loadImage ($file) {
$data = getimagesize($file);
die(var_export($data));
switch($data["mime"]){
case "image/jpeg":
$im = imagecreatefromjpeg($file);
break;
case "image/png":
$im = imagecreatefrompng($file);
break;
default:
throw new Exception('Img Type not managed');
}
return $im;
}
if (!isset($_GET['url']) || (!isset($_GET['w']) && !isset($_GET['h']))) {
die('USAGE: resize.php?url=&lt;imageURL&gt;[&w=&lt;maxwidth&gt;][&h=&lt;maxheight&gt;]');
}
$url = $_GET['url'];
try {
$image = loadImage($url);
} catch(Exception $e) {
die('Unable to load this image');
}
$w = imagesx($image);
$h = imagesy($image);
//calculate new image dimensions (preserve aspect)
if (isset($_GET['w']) && !isset($_GET['h'])) {
$new_w = intval($_GET['w']);
$new_h = $new_w * ($h/$w);
} else if (!isset($_GET['w']) && isset($_GET['h'])) {
$new_h = intval($_GET['h']);
$new_w = $new_h * ($w/$h);
} else {
$new_h = intval($_GET['h']);
$new_w = intval($_GET['w']);
if ($new_w * ($h/$w) > $new_h) {
$new_w = $new_h * ($w/$h);
} else if ($new_h * ($w/$h) > $new_w) {
$new_h = $new_w * ($h/w);
}
}
$im2 = ImageCreateTrueColor($new_w, $new_h);
imagecopyResampled ($im2, $image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
header('Content-type: image/png');
header("Content-Disposition: inline; filename=".basename($url).".png");
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($url)) . ' GMT');
header("Cache-Control: public");
header("Pragma: public");
imagepng($im2);
imagedestroy($im2);
imagedestroy($image);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment