Skip to content

Instantly share code, notes, and snippets.

@efarem
Created September 25, 2013 18:30
Show Gist options
  • Save efarem/6703932 to your computer and use it in GitHub Desktop.
Save efarem/6703932 to your computer and use it in GitHub Desktop.
Quick and dirty was to resize an image canvas, center original and fill white space
<?php
function processImage($imgname)
{
// Load original image
$original = @imagecreatefromjpeg($imgname);
if (!$original)
die('Bad Image: ' . $imgname);
// Get size of original image
$size = getimagesize($imgname);
// Extract width and height
$w = $size[0];
$h = $size[1];
// Set equal width and height along with an offset if one was different
if ($w > $h)
{
$width = $w;
$height = $w;
$pos_x = 0;
$pos_y = ($width - $h) / 2;
$pos_y = $pos_y - ($pos_y * 2);
}
else if ($h > $w)
{
$width = $h;
$height = $h;
$pos_x = ($height - $w) / 2;
$pos_x = $pos_x - ($pos_x * 2);
$pos_y = 0;
}
else
{
$width = $w;
$height = $h;
$pos_x = 0;
$pos_y = 0;
}
// Create a new image with white background
$canvas = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($canvas, 255, 255, 255);
imagefilledrectangle($canvas, 0, 0, $width, $height, $white);
// Copy original image into new image at offsets set above
imagecopy($canvas, $original, 0, 0, $pos_x, $pos_y, $width, $height);
return $canvas;
}
// Array of images to be processed, could use readdir to open all files in a directory
$images = array('image.jpg');
foreach ($images as $image)
{
$img = processImage($image);
// Save image over original
imagejpeg($img, $image);
imagedestroy($img);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment