troubleshooting Question

smoothly upload a file, add a watermark and save a good quality version

Avatar of Neil Thompson
Neil ThompsonFlag for United Kingdom of Great Britain and Northern Ireland asked on
2 Comments1 Solution98 ViewsLast Modified:
hi all

I'm trying to upload a image file (only images) and then add a watermark to them before loading them into my MySQL database. I'm currently doing it by grabbing the file, saving it on the FileSystem, loading it again then adding the watermark, saving it again before finally liading it into the database and deleting the image.

Seems somewhat messy (although it works) and it degrades on quality the 2nd time around.

Can one of you guru's amend my code to work in 1 neat movement please?

I would obviously like to browse for the file, have it grabbed, the watermark added then saved for me to upload using send_long_data to MySQL (which works fine already so I haven't included that bit)


<?php // upload directory
    define('UPLOAD_DIR', 'uploads/');
	// watermark stamp
	$stamp = imagecreatefrompng('../../images/site/stamp.png');
	// grab the image
    $img = $_POST['image'];
    $img = str_replace('data:image/jpeg;base64,', '', $img);
    $img = str_replace(' ', '+', $img);	
    $data = base64_decode($img);
	// give the file a new name
    $file = UPLOAD_DIR . MD5(microtime()) . '.jpg';	
	// save the file
    $success = file_put_contents($file, $data);
    //print $success ? $file : 'Unable to save the file.';	
	// reload to add the watermark
	$preWMImage = imagecreatefromjpeg($file);

	// Set the margins for the stamp and get the height/width of the stamp image
	$marge_right = 10;
	$marge_bottom = 10;
	$sx = imagesx($stamp);
	$sy = imagesy($stamp);
	// add the watermark
		(imagesx($preWMImage) - $sx - $marge_right),
		(imagesy($preWMImage) - $sy - $marge_bottom),
	// resave
	imagejpeg($preWMImage, $file); ?>

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 2 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 2 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros