Resize and Watermark a JPG with a PNG using PHP GD2
Posted: Sat Jul 27, 2013 11:26 pm
Allowing people to see images and save them with a dynamic watermark without having to add them to thousands of images.
TUTORIAL FILES HERE http://www.supercala.net/tuts/gd2-png_jpg_watermark.zip
show.php
generate.php
TUTORIAL FILES HERE http://www.supercala.net/tuts/gd2-png_jpg_watermark.zip
show.php
Code: Select all
<?php
$imgF="test.jpg";
$imgWM="logo.png";
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="show.css" />
</head>
<body>
<h3>image</h3>
<img src="<?php echo $imgF;?>" width="64px" />
<h3>watermark</h3>
<img src="<?php echo $imgWM;?>" width="64px" />
<h3>resampled image</h3>
<img src="generate.php" />
</body>
</html>
generate.php
Code: Select all
<?php
/*
generate.php v1.0 by Kristoffe Brodeur. ©2013 All Rights Reserved.
07-27-2013
*/
$imgOrig="test.jpg";
$imgWM="logo.png";
$quality=100;
//new image
$maxW=200;
$maxH=200;
list($imgW,$imgH)=getimagesize($imgOrig);
//proportion check
if($imgW>$maxW)
{
$propW=$maxW/$imgW;
$newH1=$imgH*$propW;
//a crop needs to be made, it does not fit the 240:160 proportion
if($newH1>$maxH)
{
$median=($newH1-$maxH)/2;
$srcY=$median/$propW;
}
}
else
{
$srcY=0;
}
$srcH=$maxH*($imgW/$maxW);
$imgCanvas=imagecreatetruecolor($maxW,$maxH);
//imagealphablending($imgCanvas,false);
$imgSrc=imagecreatefromjpeg($imgOrig);
imagecopyresampled($imgCanvas,$imgSrc,0,0,0,$srcY,$maxW,$maxH,$imgW,$srcH);
//watermark
list($wmW,$wmH)=getimagesize($imgWM);
$wm_temp=imagecreatefrompng($imgWM);
imagecopy($imgCanvas,$wm_temp,0,0,0,0,$wmW,$wmH);
header('Content-type:image/jpg');
imagejpeg($imgCanvas,NULL,$quality);//NULL could have the finished filename instead
?>