class Water
{
protected $imgPath;
protected $waterPath;
protected $imgSource;
protected $waterSource;
protected $imgInfo = [];
protected $waterInfo = [];
private $error = '';
const IMG_OPACITY = '15';
/**
* Water constructor.
* @param $imgPath
* @param $waterPath
*/
public function __construct($imgPath, $waterPath)
{
$this->imgInfo = $this->getImageInfo($imgPath);
$this->waterInfo = $this->getImageInfo($waterPath);
if ($this->checkImg($imgPath) !== false || $this->checkImg($waterPath) !== false) {
$this->imgPath = $imgPath;
$this->waterPath = $waterPath;
}
}
public function init()
{
$this->imgSource = $this->getSource($this->imgPath);
$this->waterSource = $this->getSource($this->waterPath);
$waterImage = $this->createWaterImg();
$newImage = $this->makeImg($waterImage);
$this->show($newImage);
}
/**
* @param $img
* @return bool
* 图片检查
*/
public function checkImg($img)
{
$ext = strtolower($this->getExtension($img));
if (in_array($ext, array('gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'))) {
$imgInfo = $this->getImageInfo($img);
if (empty($imgInfo) || ($ext == 'gif' && empty($imgInfo['bits']))) {
$this->setError('非法图像文件');
} else {
return true;
}
}
}
/**
* @param $img
* @return mixed
* 获取图片后缀
*/
public function getExtension($img)
{
return pathinfo($img, PATHINFO_EXTENSION);
}
/***
* @param $img
* @return array
* 获取图片信息
*/
public function getImageInfo($img)
{
$imgInfo = getimagesize($img);
switch ($imgInfo[2]) {
case 1:
$imgType = "gif";
break;
case 2:
$imgType = "jpg";
break;
case 3:
$imgType = "png";
break;
}
$info = [
'width' => $imgInfo[0],
'height' => $imgInfo[1],
'type' => $imgType,
'bits' => $imgInfo['bits'],
];
return $info;
}
/***
* @return resource
*/
public function createWaterImg()
{
$cutImg = imagecreatetruecolor($this->waterInfo['width'], $this->waterInfo['height']);
$white = imagecolorallocatealpha($cutImg, 255, 255, 255, 0);
imagefill($cutImg, 0, 0, $white);
imagecopy($cutImg, $this->waterSource, 0, 0, 0, 0, $this->waterInfo['width'], $this->waterInfo['height']);
return $cutImg;
}
/**
* @param $cut
* @return mixed
*/
public function makeImg($cut)
{
$lengthx = $this->imgInfo['width'] - 10;
$lengthy = $this->imgInfo['height'] - 10;
for ($x = 0; $x < $lengthx; $x) {
for ($y = 0; $y < $lengthy; $y) {
imagecopymerge($this->imgSource, $cut, $x, $y, 0, 0, $this->waterInfo['width'], $this->waterInfo['height'], water::IMG_OPACITY);
$y += $this->waterInfo['height'];
}
$x += $this->waterInfo['width'];
}
return $this->imgSource;
}
public function show($newImage)
{
header('content-type:' . $this->imgInfo['type']);
echo imagejpeg($newImage);
exit;
}
/***
* @param $img
* @return resource
* 获取图片源
*/
public function getSource($img)
{
return imagecreatefromstring(file_get_contents($img));
}
private function setError($msg)
{
$this->error = $msg;
}
public function getError()
{
return $this->error;
}
public function __destruct()
{
imagedestroy($this->imgSource);
}
}
$water = new Water('img.jpg', 'water.jpg');
$water->init();
近期评论