繁体   English   中英

我的php水印功能不适用于png图像

[英]My php Watermark function is not working for png image

我正在使用PHP函数将徽标添加为在我网站上上传的图像上的水印。 但是我不知道为什么我的水印功能不能用于png文件。 但是,它完美地适用于jpeg文件。 这是我的PHP函数。

function watermark($img) {
   global $wm_file, $wm_right, $wm_bottom;

   // image values pulled from config.inc.php
   $logo = './images/' . $wm_file; // path to the watermark.png
   $sp = $wm_right; // spacing from right side
   $sq = $wm_bottom; // spacing from bottom

   $size = getImageSize($img);
   $sizel = getImageSize($logo);
   $imgA = imageCreateFromJpeg($img);
   imageAlphaBlending($imgA, TRUE);
   if($sizel[0] > $size[0] || $sizel[1] > $size[1]) 
   {
      // logo size > img size
      $sizelo[0] = $sizel[0];
      $sizelo[1] = $sizel[1];
      $sizel[0] = ($sizel[0]/2);
      $sizel[1] = ($sizel[1]/2);
   } 
   else 
   {
      $sizelo[0] = $sizel[0];
      $sizelo[1] = $sizel[1];
   }
   $imgBa = imageCreateFromPng($logo);
   $imgB = imageCreateTrueColor($sizel[0], $sizel[1]);
   imageAlphaBlending($imgB, TRUE);
   imageCopyResampled($imgB, $imgBa, 0, 0, 0, 0, $sizel[0], $sizel[1], $sizelo[0], $sizelo[1]);
   imageColorTransparent($imgB, ImageColorAllocate($imgB, 0, 0, 0));
   $perc = 100; 
   imageCopymerge($imgA, $imgB, ($size[0]-$sizel[0]-$sp), ($size[1]-$sizel[1]-$sq), 0, 0, $sizel[0], $sizel[1], $perc);
   unlink($img);
   if(imageJpeg($imgA, $img, 100)) 
   {
      imageDestroy($imgB);
      imageDestroy($imgA);
      return true;
   }
   chmod($img, 0777);
}

我看到的问题是,您正在使用imageCreateFromJpeg()作为为传递给函数的$img生成资源的方式。

如果通过该函数传递jpeg,它将起作用。 如果您传递png,则不会。

我建议使用imagecreatefromstring()创建所有资源,因为它不依赖于文件类型。 像这样:

$source = imagecreatefromstring(file_get_contents($filePath));

这样做的另一个好处是,如果函数无法从您提供的文件路径创建资源,则返回false,这意味着该文件不是图像文件。

现在,您已经有资源可用于其余的代码, imageJpeg()会将资源以jpeg格式保存回文件路径。

希望能有所帮助。

另一注。 如果打算使用bmp图像,则GD库没有bmp的内置函数。 但是在PHP.net上,有人确实编写了一个效果很好的createimagefromBMP() 我还认为,在最新版本的PHP上,GD库实际上确实具有createimagefromBMP()函数。

我还看到您正在使用unlink()从目录中删除图像。 出于两个原因,这是不必要的。 imageJpeg()只会覆盖原始图像。 另外,如果由于某种原因您的脚本失败,它可能会过早地删除该图像,并且您将丢失该图像而无需编写新的图像。

使用chmod()时请小心,请务必在完成chmod()权限设置回原始权限。

chmod($img, 777);  //Give broad permissions.

//Do something.

chmod($img, 600(or whatever they were)); //Reset permission back to where they were before you changed them.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM