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); ?>
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.
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