Skip to content

Instantly share code, notes, and snippets.

@listenrightmeow
Created March 26, 2013 18:40
Show Gist options
  • Save listenrightmeow/5247970 to your computer and use it in GitHub Desktop.
Save listenrightmeow/5247970 to your computer and use it in GitHub Desktop.
Crop and letterbox PHP GD image
<?php
$url = $_REQUEST['image'];
$max_width = 500;
$max_height = 500;
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
$data = curl_exec($ch);
$http_returned_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
@$im = imagecreatefromstring($data);
curl_close($ch);
if(!$im || $http_returned_code == 404 || $http_returned_code == 307 || $http_returned_code == 403 || $http_returned_code == 500 || $http_returned_code == 0 || $http_returned_code == 400) {
$url = $_SERVER["SERVER_NAME"] . '/images/default_logos/default_icon_whitebg.jpg';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
$data = curl_exec($ch);
$im = imagecreatefromstring($data);
curl_close($ch);
}
$width = imagesx($im);
$height = imagesy($im);
if ($height > $width) {
$ratio = $max_height / $height;
$x = $width * $ratio;
$y = $max_height;
$pos_x = round(($max_height - $x) / 2);
$pos_y = 0;
} else {
$ratio = $max_width / $width;
$x = $max_width;
$y = $height * $ratio;
$pos_x = 0;
$pos_y = round(($max_width - $y) / 2);
}
header("Content-Type: image/png");
$im_resize = imagecreate($max_width, $max_height);
imagecolorallocate($im, 255, 255, 255);
imagecopyresized($im_resize, $im, $pos_x, $pos_y, 0, 0, $x, $y, $width, $height);
imagedestroy($im);
imagepng($im_resize);
imagedestroy($im_resize);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment