Need help in improving "add watermark" script

Discussion in 'PHP' started by 11alex11, Mar 30, 2010.

  1. #1
    This is the code:

    function setWatermark($WaterMark, $SourceFile, $DestinationFile){
    	
    	$photo = imagecreatefromjpeg($SourceFile);
    	$watermark = imagecreatefrompng($WaterMark);
    	imagealphablending($photo, true);
    	$offset = 10;
    	imagecopy($photo, $watermark, imagesx($photo) - imagesx($watermark) - $offset,  $offset, 0, 0, imagesx($watermark), imagesy($watermark));
    
    	if ($DestinationFile<>'') {
    		imagejpeg ($photo, $DestinationFile, 100);
    	} else {
    		// Output to the browser
    		header('Content-Type: image/jpeg');
    		imagejpeg($photo, null, 100);
    	};	
    	imagedestroy($photo);
    } 
    PHP:
    *this puts the watermark in the top right corner of the image.

    The problem is when I add this watermark to a small image (300 x 360) it takes a big part of the image. How can I resize the watermark without saving it (replacing the original)?
    Or maybe you have other idea that solves this problem?

    thanks :)
     
    11alex11, Mar 30, 2010 IP
  2. Nyu

    Nyu Peon

    Messages:
    79
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You can read the dimension of your photo with the function imagesx and imagesy. Then depending on the size of that image you can resize your watermark in php and add it to your photo like you do already do. For some resizing examples check the PHP Doc for the function imagecopyresampled -> Link ;)
     
    Nyu, Mar 31, 2010 IP
  3. 11alex11

    11alex11 Peon

    Messages:
    113
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    It works great but I'm using *.png watermark and when I'm using imagecopyresampled I get black background. How can I fix it? (the actual background is empty transparent)
     
    11alex11, Mar 31, 2010 IP
  4. Nyu

    Nyu Peon

    Messages:
    79
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #4
    You can try to use the imagecopyresized function instead or try the following to preserve transperancy with imagecopyresampled (not tested, just found that on the php site in a comment). Add this before the imagecopyresampled:

    
    imagealphablending($watermark, false);
    $color = imagecolortransparent($watermark, imagecolorallocatealpha($watermark, 0, 0, 0, 127));
    imagefill($watermark, 0, 0, $color);
    imagesavealpha($watermark, true);
    
    PHP:
     
    Nyu, Mar 31, 2010 IP
  5. 11alex11

    11alex11 Peon

    Messages:
    113
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    thanks :) problem solved
     
    11alex11, Mar 31, 2010 IP