Skip to content

Instantly share code, notes, and snippets.

@vishnu1991
Last active January 24, 2017 09:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vishnu1991/024ae1f838098c887f8b7a2bf5b6364b to your computer and use it in GitHub Desktop.
Save vishnu1991/024ae1f838098c887f8b7a2bf5b6364b to your computer and use it in GitHub Desktop.
Add watermark to jpg images php
<?php
$bg_img='bg.jpg'; //path to background (JPG ext)
$logo_img='logo.png'; // path to logo (PNG ext.)
list($width_of_bg, $height_of_bg) = getimagesize($bg_img); // to calculate background image width and height
list($width_of_logo, $height_of_logo) = getimagesize($logo_img); //to calculate logo image width and height
//for bottom right
$logo_loc_width=$width_of_bg-$width_of_logo;
$logo_loc_height=$height_of_bg-$height_of_logo;
// for different logo placement options see below comment
$bottom_image = imagecreatefromjpeg($bg_img);
$top_image = imagecreatefrompng($logo_img);
imagesavealpha($top_image, true);
imagealphablending($top_image, true);
imagecopy($bottom_image, $top_image, $logo_loc_width, $logo_loc_height, 0, 0, $width_of_logo, $height_of_logo);
header('Content-type: image/png');
imagepng($bottom_image); // for outputting image to browser
//imagepng($bottom_image, 'outputfile.png'); //to save file to server (uncomment this line for saving file to server)
imagedestroy($bottom_image);
imagedestroy($top_image);
?>
@vishnu1991
Copy link
Author

vishnu1991 commented Jan 24, 2017

[Advance Options ]:

Option 1: Different Logo placement options
Replace Line 8-10 with following code
(Ex: if you want your logo to be placed on TOP RIGHT then replace the line 8-10 of above code(watermark.php) with
$logo_loc_width=$width_of_bg-$width_of_logo; $logo_loc_height=0; )

//for BOTTOM LEFT
$logo_loc_height=$height_of_bg-$height_of_logo;
//for CENTER
$logo_loc_width=$width_of_logo;
$logo_loc_height=$height_of_logo;
//for TOP LEFT
$logo_loc_width=0;
$logo_loc_height=0;
//for TOP RIGHT
$logo_loc_width=$width_of_bg-$width_of_logo;
$logo_loc_height=0;

@vishnu1991
Copy link
Author

vishnu1991 commented Jan 24, 2017

**Todos / Areas of improvement **

  • place png over png

If you have any problem/suggestion/bug/issue then pls comment to let us know!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment