search
HomeBackend DevelopmentPHP TutorialSimple example of adding watermark to php images

  1. /**
  2. * Add watermark to picture (applicable to png/jpg/gif format)
  3. *
  4. * @author flynetcn
  5. *
  6. * @param $srcImg original picture
  7. * @param $waterImg watermarked picture
  8. * @param $savepath save path
  9. * @param $savename Save name
  10. * @param $positon Watermark position
  11. * 1: Top left, 2: Top right, 3: Center, 4: Bottom left, 5: Bottom right
  12. * @param $alpha Transparency - - 0: Completely transparent, 100: Completely opaque
  13. *
  14. * @return Success -- the new image address after watermarking
  15. * Failure -- -1: The original file does not exist, -2: The watermark image does not exist, -3: The original file image object failed to be created
  16. *-4: The watermark file image object failed to be created-5: The new image after watermarking failed to be saved
  17. */
  18. function img_water_mark($srcImg, $waterImg, $savepath=null, $savename=null, $positon=5, $alpha=30)
  19. {
  20. $temp = pathinfo($srcImg);
  21. $name = $temp['basename'];
  22. $path = $temp['dirname'];
  23. $exte = $temp['extension'];
  24. $savename = $savename ? $savename : $name;
  25. $savepath = $savepath ? $savepath : $path;
  26. $savefile = $savepath .'/'. $savename;
  27. $srcinfo = @getimagesize($srcImg);
  28. if ( !$srcinfo) {
  29. return -1; //The original file does not exist
  30. }
  31. $waterinfo = @getimagesize($waterImg);
  32. if (!$waterinfo) {
  33. return -2; //The watermark image does not exist
  34. }
  35. $srcImgObj = image_create_from_ext($srcImg);
  36. if (!$srcImgObj) {
  37. return -3; //The creation of the original file image object failed
  38. }
  39. $waterImgObj = image_create_from_ext($waterImg);
  40. if (!$waterImgObj) {
  41. return -4; //Failed to create watermark file image object
  42. }
  43. switch ($positon) {
  44. //1 Top to the left
  45. case 1: $x=$y=0; break;
  46. //2 Top to the right
  47. case 2: $x = $srcinfo[0]-$waterinfo[0]; $y = 0; break;
  48. //3 centered
  49. case 3: $x = ($srcinfo[0]-$waterinfo[0] )/2; $y = ($srcinfo[1]-$waterinfo[1])/2; break;
  50. //4 bottom is on the left
  51. case 4: $x = 0; $y = $srcinfo[1]-$ waterinfo[1]; break;
  52. //5 bottom right
  53. case 5: $x = $srcinfo[0]-$waterinfo[0]; $y = $srcinfo[1]-$waterinfo[1]; break;
  54. default: $x=$y=0;
  55. }
  56. imagecopymerge($srcImgObj, $waterImgObj, $x, $y, 0, 0, $waterinfo[0], $waterinfo[1], $alpha);
  57. switch ($srcinfo[2]) {
  58. case 1: imagegif($srcImgObj, $savefile); break;
  59. case 2: imagejpeg($srcImgObj, $savefile); break;
  60. case 3: imagepng($srcImgObj, $savefile) ; break;
  61. default: return -5; //Save failed
  62. }
  63. imagedestroy($srcImgObj);
  64. imagedestroy($waterImgObj);
  65. return $savefile;
  66. }
  67. function image_create_from_ext($imgfile)
  68. {
  69. $info = getimagesize($imgfile);
  70. $im = null;
  71. switch ($info[2]) {
  72. case 1: $im=imagecreatefromgif($imgfile); break;
  73. case 2: $im=imagecreatefromjpeg($imgfile); break;
  74. case 3: $im=imagecreatefrompng($imgfile); break;
  75. }
  76. return $im;
  77. }
Copy code


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.