Avatar of Neil Thompson
Neil Thompson
Flag for United Kingdom of Great Britain and Northern Ireland asked on

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

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)

Thanks
Neil

<?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
	imagecopy(
		$preWMImage, 
		$stamp, 
		(imagesx($preWMImage) - $sx - $marge_right),
		(imagesy($preWMImage) - $sy - $marge_bottom),
		0, 
		0, 
		imagesx($stamp), 
		imagesy($stamp)
	);
	
	// resave
	imagejpeg($preWMImage, $file); ?>

Open in new window

PHP

Avatar of undefined
Last Comment
Neil Thompson

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
gr8gonzo

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Neil Thompson

ASKER
Many thanks for your detailed thoughts. I've done some working out and it would have used the 1GB of space I had really quickly so thanks for that.

I've also amended my scripts to use PNG and as you said it's perfect. It's also allowed me to cull 1/2 my scrips and implement both client side resizing and compression.

Thanks for taking the time :)

Neil
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck