insipid (owner)

Revisions

gist: 210794 Download_button fork
public
Public Clone URL: git://gist.github.com/210794.git
Embed All Files: show embed
water.php #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?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);
 
?>