Skip to content

Instantly share code, notes, and snippets.

@insipid
Created October 15, 2009 08:54
Show Gist options
  • Save insipid/210794 to your computer and use it in GitHub Desktop.
Save insipid/210794 to your computer and use it in GitHub Desktop.
<?php
$target = $_GET['target'];
$watermark = $_GET['watermark'];
if ((strlen($target) == 0) || (strlen($watermark) == 0)) {
exit;
}
if (!file_exists($target) || !file_exists($watermark)) {
exit;
}
// I don't understand why there isn't a GD utility function for this
function imagecreatefrom($filename) {
$ext = strrchr($filename, '.');
if (!$ext) {
$ext = '';
}
switch ($ext) {
case '.jpg':
case '.jpeg':
return imagecreatefromjpeg($filename);
case '.png':
return imagecreatefrompng($filename);
case '.gif':
return imagecreatefromgif($filename);
default:
// Might as well assume it's a jpeg
return imagecreatefromjpeg($filename);
}
}
// Get original file dimensions
list($t_width, $t_height) = getimagesize($target);
list($w_width, $w_height) = getimagesize($watermark);
// The two options for scaling depend on the relative aspect-ratios of the target and watermark (e.g., portrait vs. lanscape)
// In other words: if you scale the watermark image, which dimension hits first: width or height?
// If target image is "taller" than the watermark image, then we want the full width, and scale the height
if (($t_height / $t_width) > ($w_height / $w_width)) {
// We want the full width in the output
$out_width = $t_width;
// And scale the height accordingly
$out_height = intval(($t_width / $w_width) * $w_height);
// We also need to adjust the y-offset; which is (half-of-the-target - half-of-the-scaled-watermark)
$out_x = 0;
$out_y = intval(($t_height / 2) - ($out_height / 2));
} else {
// Otherwise we want full-height, and scale the width
$out_height = $t_height;
$out_width = intval(($t_height / $w_height) * $w_width);
// Similar to above, we need to offset the image horizontally
$out_y = 0;
$out_x = intval(($t_width / 2) - ($out_width / 2));
}
// The output image is always the same size as the target
$out_image = imagecreatetruecolor($t_width, $t_height);
$t_image = imagecreatefrom($target);
$w_image = imagecreatefrom($watermark);
// The target image is copied as-is
imagecopyresampled($out_image, $t_image, 0, 0, 0, 0, $t_width, $t_height, $t_width, $t_height);
// Then we overlay it with the appropriately-scaled watermark
imagecopyresampled($out_image, $w_image, $out_x, $out_y, 0, 0, $out_width, $out_height, $w_width, $w_height);
// Content type
header('Content-type: image/png');
// Output
imagepng($out_image, null, 9);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment