PHP Function Watermark AND Compress Uploaded Image
Simplest, Easiest to Understand PHP Function Code to take an Uploaded Image ie $_FILES['uploaded-image']['tmp_name'], and BOTH Watermark AND Compress the Uploaded Image
Home
Short:
/* ----------------------------------------------------------------- function to both watermark and compress image [$compression] intensity of compression 0 - 100; 0 = worst quality, smallest filesize 100 = best quality, largest filesize [$watermarkOpacity] how transparent watermark [$watermarkImg] is 0 = invisible 100 = no transparency at all ------------------------------------------------------------------ */ function watermarkCompress($src_img_tmp_name, $watermarkPath, $compression = 75, $watermarkOpacity = 35) { // Load the image that will be the watermark $watermarkImg = imagecreatefrompng($watermarkPath); // create an image that php GD library can work with $im = imagecreatefromjpeg($src_img_tmp_name); // store width an height of the image we are applying watermark to $sourceImgWidth = imagesx($im); $sourceImgHeight = imagesy($im); // store width and height of watermark image $watermarkImgWidth = imagesx($watermarkImg); $watermarkImgHeight = imagesy($watermarkImg); // the x and y point of where we are putting the watermark image on the source image $watermarkX = (($sourceImgWidth * .5) - ($watermarkImgWidth * .5)); // middle of source image, horizontally $watermarkY = 20; // 20px from the top, vertically // "paste" the watermark on the source image, convert vars to int to prevent implicit float to int conversion error imagecopymerge($im, $watermarkImg, (int)$watermarkX, (int)$watermarkY, 0, 0, (int)$watermarkImgWidth, (int)$watermarkImgHeight, (int)$watermarkOpacity); // compress the image (if you dont wish to compress the image, remove 3rd optional parameter [$compression]) imagejpeg($im, $src_img_tmp_name, $compression); // free memory imagedestroy($im); } // example usage if (isset($_FILES["uploaded-image"]) && $_FILES["uploaded-image"]["error"] == UPLOAD_ERR_OK) { watermarkCompress($_FILES["uploaded-image"]["tmp_name"], "watermark-image-path.png"); }
source code home