-
Notifications
You must be signed in to change notification settings - Fork 6
/
Image.php
68 lines (60 loc) · 2.54 KB
/
Image.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
<?php
class Image
{
public static $type = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
public static function compress($src, $quality = 90)
{
list ($width, $height, $type) = @getimagesize($src);
if (!is_numeric($type)) {
return false;
}
$imagecreatefromFunction = 'imagecreatefrom' . self::$type[$type];
$imageFunction = 'image' . self::$type[$type];
$quality = $type !== 2 && $quality > 9 ? 9 : $quality;
if (($img = @$imagecreatefromFunction($src)) && imagecopyresampled($img, $img, 0, 0, 0, 0, $width, $height, $width, $height) && $imageFunction($img, $src, $quality)) {
return imagedestroy($img);
}
is_resource($img) && imagedestroy($img);
return false;
}
public static function watermarkToJpg($fromPath, $watermarkPath, $toPath = '', $xAlign = 'left', $yAlign = 'bottom', $quality = 90)
{
$xOffset = $yOffset = $xPos = $yPos = 10; // 偏移10像素
if (!($img = @imagecreatefromjpeg($fromPath)) || !(list($waterWidth, $waterHeight, $waterType) = @getimagesize($watermarkPath))){
return false;
}
$imagecreatefromFunction = 'imagecreatefrom' . self::$type[$waterType];
if (!($imgWater = @$imagecreatefromFunction($watermarkPath))){
return false;
}
list ($imgWidth, $imgHeight) = @getimagesize($fromPath);
if ($xAlign == 'middle') {
$xPos = $imgWidth / 2 - $waterWidth / 2 + $xOffset;
}
if ($xAlign == 'left') {
$xPos = 0 + $xOffset;
}
if ($xAlign == 'right') {
$xPos = $imgWidth - $waterWidth - $xOffset;
}
if ($yAlign == 'middle') {
$yPos = $imgHeight / 2 - $waterHeight / 2 + $yOffset;
}
if ($yAlign == 'top') {
$yPos = 0 + $yOffset;
}
if ($yAlign == 'bottom') {
$yPos = $imgHeight - $waterHeight - $yOffset;
}
$cut = imagecreatetruecolor($waterWidth, $waterHeight);
imagecopy($cut, $img, 0, 0, $xPos, $yPos, $waterWidth, $waterHeight);
imagecopy($cut, $imgWater, 0, 0, 0, 0, $waterWidth, $waterHeight);
imagecopymerge($img, $cut, $xPos, $yPos, 0, 0, $waterWidth, $waterHeight, $quality);
if (imagejpeg($img, ($toPath ? $toPath : $fromPath), $quality)) {
return imagedestroy($cut) && imagedestroy($img);
}
is_resource($cut) && imagedestroy($cut);
is_resource($img) && imagedestroy($img);
return false;
}
}