PHP 7 Script to Add Watermark Logo to Uploaded Local Image File in Browser Full Project For Beginners

  • Post author:
  • Post category:PHP
  • Post comments:0 Comments


Welcome folks today in this blog post we will be adding watermark logo to uploaded local image file in browser using php . All the full source code of the application is shown below.




Get Started




In order to get started you need to make an index.php file and copy paste the following code








<form action="upload.php" method="post" enctype="multipart/form-data">
    Select Image File to Upload:
    <input type="file" name="file">
    <input type="submit" name="submit" value="Upload">

// Path configuration 
$targetDir = "uploads/"; 
$watermarkImagePath = 'codexworld-logo.png'; 
$statusMsg = ''; 
        // File upload path 
        $fileName = basename($_FILES["file"]["name"]); 
        $targetFilePath = $targetDir . $fileName; 
        $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); 
        // Allow certain file formats 
        $allowTypes = array('jpg','png','jpeg'); 
        if(in_array($fileType, $allowTypes)){ 
            // Upload file to the server 
            if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){ 
                // Load the stamp and the photo to apply the watermark to 
                $watermarkImg = imagecreatefrompng($watermarkImagePath); 
                    case 'jpg': 
                        $im = imagecreatefromjpeg($targetFilePath); 
                    case 'jpeg': 
                        $im = imagecreatefromjpeg($targetFilePath); 
                    case 'png': 
                        $im = imagecreatefrompng($targetFilePath); 
                        $im = imagecreatefromjpeg($targetFilePath); 
                // Set the margins for the watermark 
                $marge_right = 10; 
                $marge_bottom = 10; 
                // Get the height/width of the watermark image 
                $sx = imagesx($watermarkImg); 
                $sy = imagesy($watermarkImg); 
                // Copy the watermark image onto our photo using the margin offsets and  
                // the photo width to calculate the positioning of the watermark. 
                imagecopy($im, $watermarkImg, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($watermarkImg), imagesy($watermarkImg)); 
                // Save image and free memory 
                imagepng($im, $targetFilePath); 
                    $statusMsg = "The image with watermark has been uploaded successfully."; 
                    $statusMsg = "Image upload failed, please try again."; 
                $statusMsg = "Sorry, there was an error uploading your file."; 
            $statusMsg = 'Sorry, only JPG, JPEG, and PNG files are allowed to upload.'; 
        $statusMsg = 'Please select a file to upload.'; 
// Display status message 
echo $statusMsg;

Leave a Reply