Solved

PHP GD Watermarking

Posted on 2008-11-02
11
612 Views
Last Modified: 2012-08-14
Hi,
I am trying to add a watermark for images in a gallery. Earlier I have used "imagecopymerge" successfully, but this time I am stuck. Relevant code is below (Original working version without watermark first)

The second part is with the manipulation I tried, I have marked where all the changes are.

With this I get a lot of error, the first one being "Warning: Wrong parameter count for imagestring() in C:\wamp\www\automarket3\admin\images\store\details.php on line 285"

And second one "Warning: imagejpeg(): supplied argument is not a valid Image resource in C:\wamp\www\automarket3\admin\images\store\details.php on line 354"

Thanks for any help.
Jay
#-#############################################

# desc: resizes image using GD library

# param: ($fullFilename) filename of full size image ($thumbFilename) filename to save thumbnail as ($size) max width or height to resize to

# returns: true if image created, false if failed

function ResizeImageUsingGD($fullFilename, $thumbFilename, $size) {

 

	list ($width,$height,$type) = GetImageSize($fullFilename);

 

	if($im = ReadImageFromFile($fullFilename,$type)){

		//if image is smaller than the $size, show the original

		if($height <= $size && $width <= $size){

			$newheight=$height;

			$newwidth=$width;

		}

		//if image height is larger, height=$size, then calc width

		else if($height > $width){

			$newheight=$size;

			$newwidth=round($width / ($height/$size));

		}

		//if image width is larger, width=$size, then calc height

		else{

			$newwidth=$size;

			$newheight=round($height / ($width/$size));

		}

 

		$im2=ImageCreateTrueColor($newwidth,$newheight);

		ImageCopyResampled($im2,$im,0,0,0,0,$newwidth,$newheight,$width,$height);

 

		return WriteImageToFile($im2,$thumbFilename,$type);

	}

 

	return false;

}#-#ResizeImageUsingGD()

 

 

 

-----------------------Edited Version ---------------------------------

 

 

#-#############################################

# desc: resizes image using GD library

# param: ($fullFilename) filename of full size image ($thumbFilename) filename to save thumbnail as ($size) max width or height to resize to

# returns: true if image created, false if failed

 

 

function ResizeImageUsingGD($fullFilename, $thumbFilename, $size) {

 

// Edited for adding watermark

// Set the margins for the stamp and get the height/width of the stamp image

 

$stamp = imagecreatefrompng('logo.png');

$marge_right = 0;

$marge_bottom = 0;

$sx = imagesx($stamp);

$sy = imagesy($stamp);

 

// End of watermark edit - part 1

 

	list ($width,$height,$type) = GetImageSize($fullFilename);

 

	if($im = ReadImageFromFile($fullFilename,$type)){

		//if image is smaller than the $size, show the original

		if($height <= $size && $width <= $size){

			$newheight=$height;

			$newwidth=$width;

		}

		//if image height is larger, height=$size, then calc width

		else if($height > $width){

			$newheight=$size;

			$newwidth=round($width / ($height/$size));

		}

		//if image width is larger, width=$size, then calc height

		else{

			$newwidth=$size;

			$newheight=round($height / ($width/$size));

		}

 

		// Added $dst_img for watermark - edit part2

		$dst_img = imagecreatetruecolor($newwidth, $newheight);			

    	imagecopyresampled($dst_img,$im,0,0,0,0,$newwidth,$newheight,$width,$height);

		

	

		$im2 = imagecopymerge($dst_img, $stamp, imagesx($dst_img) - $sx - $marge_right, imagesy($dst_img) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp), 10);

		imagestring ($im2, 2,10, $destHeight-20);

		

		

	

 

		return WriteImageToFile($im2,$thumbFilename,$type);

	}

 

	return false;

}#-#ResizeImageUsingGD()

Open in new window

0
Comment
Question by:jayseena
  • 6
  • 5
11 Comments
 
LVL 7

Expert Comment

by:Valleriani
ID: 22861309
Hey mate, try the coding below. Before that, you don't need imagestring for watermarks, thats more for text watermarks, not image watermarks.

I added the variable $stampt , which is stamp transparency, if you want the stamp to be more/less transparent on the image, change it higher/lower. 100 Being full and 0 being invisible.

Basicly, don't need to create a new variable for imagecopymerge, just use the current one, sort of like how imagecopyresampled is...

Hope this helps and this is what you wanted:


function ResizeImageUsingGD($fullFilename, $thumbFilename, $size) {
 

$stamp = imagecreatefrompng('test.png');

$stampt = 25; //Stamp transparency amount

$marge_right = 0;

$marge_bottom = 0;

$sx = imagesx($stamp);

$sy = imagesy($stamp);
 

        list ($width,$height,$type) = GetImageSize($fullFilename);
 

        if($im = ReadImageFromFile($fullFilename,$type)){

                //if image is smaller than the $size, show the original

                if($height <= $size && $width <= $size){

                        $newheight=$height;

                        $newwidth=$width;

                }

                //if image height is larger, height=$size, then calc width

                else if($height > $width){

                        $newheight=$size;

                        $newwidth=round($width / ($height/$size));

                }

                //if image width is larger, width=$size, then calc height

                else{

                        $newwidth=$size;

                        $newheight=round($height / ($width/$size));

                }
 

                $im2=ImageCreateTrueColor($newwidth,$newheight);

                ImageCopyResampled($im2,$im,0,0,0,0,$newwidth,$newheight,$width,$height);

				imagecopymerge($im2, $stamp, imagesx($im2) - $sx - $marge_right, imagesy($im2) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp), $stampt);
 

                return WriteImageToFile($im2,$thumbFilename,$type);

        }
 

        return false;

}#-#ResizeImageUsingGD()

Open in new window

0
 
LVL 7

Expert Comment

by:Valleriani
ID: 22861320
Oh, you'll want to change test.png to whatever your watermark is.

20 is a small size for a image though. would be hard to see.

As well http://se2.php.net/manual/en/function.imagestring.php for imagestring if you want to know about it.
0
 

Author Comment

by:jayseena
ID: 22861587
Valleriani, thanks for your help. The script is perfect and doesn't throw any errors. But I have messed up something else in between and am trying to figure out what and where. I will check this out and get back.
Once again, thanks.
0
 
LVL 7

Expert Comment

by:Valleriani
ID: 22861623
Ok no problem! Just let me know :)
0
 

Author Comment

by:jayseena
ID: 22865306
Hi,
Apparently it worked well. But I made a mistake in identifying the part of the script. The part I mentioned was for creating thumbnail. What I wanted was watermark on the enlarged image. I am using a gallery script which takes main images from a dynamic folder and creates thumbnails on the fly. So now I realise that there is no GD role for the main images. I use lightbox to show pop-up image. And the images are uploaded to a dynamic folder using ADDT multiple image upload server behavior.
Any thoughts on how can I achieve the result I am looking for!
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 7

Expert Comment

by:Valleriani
ID: 22865511
Ohh okay, so you want one thumbnail and one watermarked normal sized image. Let me check.
0
 
LVL 7

Expert Comment

by:Valleriani
ID: 22865678
How about this?

Just some notes:

This is now : ResizeImageUsingGD(Filetoget, Filetowritetoowithwatermark, thumbnail, sizeofthumbnail);
Extra field, "File to write too with watermark" will be the large version of the image WITH the watermark.
EX. ResizeImageUsingGD("test.jpg", "test-l.jpg", "test-t.jpg", 50);

There is an issue however, if you try to write to the same file you are opening, it will cause an error. This was solved by checking if the filename = writename, and chmodding the image to 777 to be able to change, guess it is picky. Note, the script must have chmod 777 as well (probably does anyways.) If you don't WANT to leave the image to 777, (doesn't really matter on images though), you can chmod the filename back down to whatever you want after writing the images.
EX. ResizeImageUsingGD("test.jpg", "test.jpg", "test-t.jpg", 50);


I hope this is what you ment, I didn't really understand to well.
function ResizeImageUsingGD($fullFilename, $fullWriteName, $thumbFilename, $size) {
 

$stamp = imagecreatefrompng('logo.png');

$trans = 30; //Stamp transparency amount

$marge_right = 0;

$marge_bottom = 0;

$sx = imagesx($stamp);

$sy = imagesy($stamp);

	if ($fullFilename == $fullWriteName) {

		chmod($fullFilename, 0777);

	}
 

        list ($width,$height,$type) = GetImageSize($fullFilename);
 

        if($im = ReadImageFromFile($fullFilename,$type)){

                //if image is smaller than the $size, show the original

                if($height <= $size && $width <= $size){

                        $newheight=$height;

                        $newwidth=$width;

                }

                //if image height is larger, height=$size, then calc width

                else if($height > $width){

                        $newheight=$size;

                        $newwidth=round($width / ($height/$size));

                }

                //if image width is larger, width=$size, then calc height

                else{

                        $newwidth=$size;

                        $newheight=round($height / ($width/$size));

                }
 

                $im2=ImageCreateTrueColor($newwidth,$newheight);

                ImageCopyResampled($im2,$im,0,0,0,0,$newwidth,$newheight,$width,$height);

                WriteImageToFile($im2,$thumbFilename,$type);
 

				imagecopymerge($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp), $trans);

                WriteImageToFile($im,$fullWriteName,$type);

        }
 

        return false;

}#-#ResizeImageUsingGD()

Open in new window

0
 

Author Comment

by:jayseena
ID: 22866172
Hi,
Most of the thing you said just passed over my head. I appreciate your help. I tried the above script but didn't see what I am looking for. But there is no error thrown except that simply it doesn't show the watermark on the main image.

I will explain a bit more.
At the user end: The images are uploaded to a folder (multiple image upload at once) with the folder name logged to a database.

At the browser end: The gallery pulls the images and the thumbnails are created on the fly and saved to a folder 'thumbnails' within the main folder.

Here is how the main folder pulled:
// folder where full size images are stored (include trailing slash)
$config['fulls'] = $_GET['car_id'];

And the thumbnails here
// folder where thumbnails are to be created (include trailing slash)
$config['thumbs'] = $row_Recordset1['car_T_id'];

I am attaching the code where it says about the images
In between how can I add a trailing slash at the end of $config['fulls'] = $_GET['car_id']; Currently I am doing this manually in the database. The 'fulls' path should show like  myimagefolder/
Hope it's clear now

// for the images on the page

	for($i=$config['start']; $i<$config['max']; $i++){

 

		$thumb_image = $config['thumbs'].$imagelist[$i];

		$thumb_exists = file_exists($thumb_image);

 

		// create thumb if not exist

		if(!$thumb_exists){

			set_time_limit(30);

			if(!($thumb_exists = ResizeImageUsingGD("$config[fulls]$imagelist[$i]", $thumb_image, $config['size']))){

				Oops("Creating Thumbnail image of <strong>$config[fulls]$imagelist[$i]</strong> failed. Possible directory write permission errors.");

			}

		}

 

		$imagelist[$i] = rawurlencode($imagelist[$i]);

 

 

	#########################################################

	# print out the image and link to the page 

	#########################################################

	

		echo '<td>';

			echo '<a href="'. $config['fulls'].$imagelist[$i] .'" title="'. $imagelist[$i] .'" rel="lightbox[]"">';

			echo '<img src="'. $config['thumbs'].$imagelist[$i] .'" alt="'. $imagelist[$i] .'"  border="0">';

			echo '</a>';

		echo '</td>'."\n";

	#########################################################

Open in new window

0
 
LVL 7

Assisted Solution

by:Valleriani
Valleriani earned 50 total points
ID: 22866507
Hmm odd, when I have a bit more time I can take a look at that too.

I have edited it a bit. You do need to CHMOD the script to be 0777. If you don't know what this means you can google it, its very simple to do, you do it in a ftp editor normally by right clicking the file and look for 'PROPERTIES' or 'CHMOD', and adjusting it to 0777 so the file can be rewritten too. Make sure to change the watermark png to whatever you have.

You also have to make sure to 'delete' the thumbnail + whereever thumbnails are stored, as if there is ALREADY a thumbnail with your script, it will not recreate it, thus will not add the watermark image as well. (Since they are both together.) So if there is already a thumbnail, it will not do the watermark script!

If you look here, I did it on one image with the script I will provide here:

http://stonefallstudios.com/test/woot.jpg

I will provide the full script I used for testing. It is a little different but you can try it out yourself too. Just take a image, and a PNG for the watermark.

But yeah, try this ResizeImageUsingGD, and what I stated above about CHmodding the file to 0777. If you need further help I will try my best with doing this :)

<?php
 

ResizeImageUsingGD("woot.jpg", "bcthumb.jpg", 100);
 

function ResizeImageUsingGD($fullFilename, $thumbFilename, $size) {
 

$stamp = imagecreatefrompng('test.png');

$trans = 30; //Stamp transparency amount

$marge_right = 0;

$marge_bottom = 0;

$sx = imagesx($stamp);

$sy = imagesy($stamp);
 

        list ($width,$height,$type) = GetImageSize($fullFilename);
 

        if($im = ReadImageFromFile($fullFilename,$type)){

                //if image is smaller than the $size, show the original

                if($height <= $size && $width <= $size){

                        $newheight=$height;

                        $newwidth=$width;

                }

                //if image height is larger, height=$size, then calc width

                else if($height > $width){

                        $newheight=$size;

                        $newwidth=round($width / ($height/$size));

                }

                //if image width is larger, width=$size, then calc height

                else{

                        $newwidth=$size;

                        $newheight=round($height / ($width/$size));

                }
 

                $im2=ImageCreateTrueColor($newwidth,$newheight);

                ImageCopyResampled($im2,$im,0,0,0,0,$newwidth,$newheight,$width,$height);

                WriteImageToFile($im2,$thumbFilename,$type);
 

				chmod($fullFilename, 0777);

				imagecopymerge($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp), $trans);

                WriteImageToFile($im,$fullFilename,$type);

        }
 

        return false;

}#-#ResizeImageUsingGD()
 

function ReadImageFromFile($filename, $type) {

	$imagetypes = ImageTypes();
 

	switch ($type) {

		case 1 :

			if ($imagetypes & IMG_GIF){

				return ImageCreateFromGIF($filename);

			}

			else{Oops("File type <b>.gif</b> not supported by GD version on server");}

		break;
 

		case 2 :

			if ($imagetypes & IMG_JPEG){

				return ImageCreateFromJPEG($filename);

			}

			else{Oops("File type <b>.jpg</b> not supported by GD version on server");}

		break;
 

		case 3 :

			if ($imagetypes & IMG_PNG){

				return ImageCreateFromPNG($filename);

			}

			else{Oops("File type <b>.png</b> not supported by GD version on server");}

		break;
 

		default:

			Oops("Unknown file type passed to ReadImageFromFile");

		return 0;

	}

}#-#ReadImageFromFile()
 
 

#-#############################################

# desc: creates the new thumbnail image depending on type

# param: ($im) image resource ($filename) filename of image to create ($type) int of type. 1=gif,2=jpeg,3=png

# returns: true if created, false if failed

function WriteImageToFile($im, $filename, $type) {

	global $config;
 

	switch ($type) {

		case 1 :

			return ImageGIF($im, $filename);

		case 2 :

			return ImageJpeg($im, $filename, 100);

		case 3 :

			return ImagePNG($im, $filename);

		default:

			return false;

	}

}#-#WriteImageToFile()
 
 

?>

Open in new window

0
 

Author Comment

by:jayseena
ID: 22866777
Hi,
Thanks. I will try this out.
0
 

Accepted Solution

by:
jayseena earned 0 total points
ID: 23034246
Dear Valleriani,
Thanks for all your support. This was hecking my brain for quiet long time and the client has forgotten the whole concept of water marking for the time being. I am also leaving the issue behind for the time being.
Thank you once again.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now