php implements image watermark function
- 2020-12-22 17:35:45
- OfStack
<?php
/**
* Image with watermark (applicable to png/jpg/gif Format)
*
* @author flynetcn
*
* @param $srcImg The original image
* @param $waterImg The watermark image
* @param $savepath Save the path
* @param $savename Save the name
* @param $positon The watermark position
* 1: The top left , 2: At the top right , 3: In the middle , 4: Bureau at the bottom of the left , 5: At the bottom right
* @param $alpha transparency -- 0: Completely transparent , 100: Complete opacity
*
* @return successful -- Watermark after the new image address
* failure -- -1: The original file does not exist , -2: The watermark image does not exist , -3: The original file image object creation failed
* -4: Watermark file image object creation failed -5: The watermark after the new image save failure
*/
function img_water_mark($srcImg, $waterImg, $savepath=null, $savename=null, $positon=5, $alpha=30)
{
$temp = pathinfo($srcImg);
$name = $temp['basename'];
$path = $temp['dirname'];
$exte = $temp['extension'];
$savename = $savename ? $savename : $name;
$savepath = $savepath ? $savepath : $path;
$savefile = $savepath .'/'. $savename;
$srcinfo = @getimagesize($srcImg);
if (!$srcinfo) {
return -1; // The original file does not exist
}
$waterinfo = @getimagesize($waterImg);
if (!$waterinfo) {
return -2; // The watermark image does not exist
}
$srcImgObj = image_create_from_ext($srcImg);
if (!$srcImgObj) {
return -3; // The original file image object creation failed
}
$waterImgObj = image_create_from_ext($waterImg);
if (!$waterImgObj) {
return -4; // Watermark file image object creation failed
}
switch ($positon) {
//1 The top left
case 1: $x=$y=0; break;
//2 At the top right
case 2: $x = $srcinfo[0]-$waterinfo[0]; $y = 0; break;
//3 In the middle
case 3: $x = ($srcinfo[0]-$waterinfo[0])/2; $y = ($srcinfo[1]-$waterinfo[1])/2; break;
//4 At the bottom of the left
case 4: $x = 0; $y = $srcinfo[1]-$waterinfo[1]; break;
//5 At the bottom right
case 5: $x = $srcinfo[0]-$waterinfo[0]; $y = $srcinfo[1]-$waterinfo[1]; break;
default: $x=$y=0;
}
imagecopymerge($srcImgObj, $waterImgObj, $x, $y, 0, 0, $waterinfo[0], $waterinfo[1], $alpha);
switch ($srcinfo[2]) {
case 1: imagegif($srcImgObj, $savefile); break;
case 2: imagejpeg($srcImgObj, $savefile); break;
case 3: imagepng($srcImgObj, $savefile); break;
default: return -5; // Save failed
}
imagedestroy($srcImgObj);
imagedestroy($waterImgObj);
return $savefile;
}
function image_create_from_ext($imgfile)
{
$info = getimagesize($imgfile);
$im = null;
switch ($info[2]) {
case 1: $im=imagecreatefromgif($imgfile); break;
case 2: $im=imagecreatefromjpeg($imgfile); break;
case 3: $im=imagecreatefrompng($imgfile); break;
}
return $im;
}