0

I have a php code (upload.php) which lets users upload an image from index.html, resizes it, puts an watermark and displays it on the same index.html page. An user can then download the image by 'Save image as...' option. The resized image is saved in the images/ folder. The filename remains same as the uploaded file.

Is there any way put a Download button in the index.html page which prompts user to download the watermarked image? What modifications do I need to make this possible?

index.html

<html>
    <head>
        <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
        <title>Process image</title>
        <link type="text/css" rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"/>
        <link href="css/jquery.inputfile.css" rel="stylesheet" type="text/css" />

        <script src="js/jquery.min.js"></script>
        <script src="js/jquery.inputfile.js"></script>
        <script src="js/bootstrap.min.js"></script>
        <style type="text/css">

            input[type=file], input[type=submit] {
                cursor:pointer
            }

        </style>
        <script type="text/javascript">
            $(document).ready(function (e) {
                $("#uploadForm").on('submit', (function (e) {
                    $("#uploadForm").find('.progress-bar').removeClass('progress-bar-success')
                            .removeClass('progress-bar-danger');
                    e.preventDefault();
                    $.ajax({
                        url: "upload.php",
                        type: "POST",
                        data: new FormData(this),
                        contentType: false,
                        cache: false,
                        processData: false,
                        success: function (data)
                        {
                            $("#profileImage").html(data);
                        },
                        error: function ()
                        {
                        },
                        xhr: function () {
                            var xhr = new window.XMLHttpRequest();
                            //Upload progress
                            xhr.upload.addEventListener("progress", function (e) {
                                if (e.lengthComputable) {
                                    var percentComplete = (e.loaded || e.position) * 100 / e.total;
                                    //Do something with upload progress
                                    console.log(percentComplete);
                                    $("#uploadForm").find('.progress-bar').width(percentComplete + '%').html(percentComplete + '%');
                                }
                            }, false);
                            xhr.addEventListener('load', function (e) {
                                $("#uploadForm").find('.progress-bar').addClass('progress-bar-success').html('Finished uploading.');
                            });
                            return xhr;
                        }

                    });
                }));
            });
        </script>
    </head>
    <body>
        <div class="bgColor">
            <form id="uploadForm" action="upload.php" method="post">
                <div class="row " align="center">
                    <div class="col-sm-6 col-sm-offset-2">
                        <div id="profileImage">  <img src="blank.gif" class="img-thumbnail " width="300" height="300"/></div>
                    </div>
                    <div class="col-sm-6 col-sm-offset-2">
                        <div id="uploadFormLayer">
                            <label>Upload Image File:</label><br/>
                            <input name="userImage" type="file" class="inputFile" /></br>
                            <input type="submit" value="Submit" class="btn btn-primary" />
                        </div>
                    </div>
                    <div class="col-sm-6 col-sm-offset-2" style="margin-top:20px">
                        <div class="progress progress-striped active">
                            <div class="progress-bar" style="width:0%"></div>
                        </div></div>
            </form>
        </div>
        <script>
            $('input[type="file"]').inputfile({
                uploadText: '<span class="glyphicon glyphicon-upload"></span> Select a file',
                removeText: '<span class="glyphicon glyphicon-trash"></span>',
                restoreText: '<span class="glyphicon glyphicon-remove"></span>',

                uploadButtonClass: 'btn btn-primary',
                removeButtonClass: 'btn btn-default'
            });
        </script>
        <p style="text-align: center;">
            <span style="color:#000000;">Once the image is processed, </span><span style="color:#800000;"><strong>save it to your device</strong></span><span style="color:#000000;">. After saving the image, click <a href="http://www.pronilhalder.com/p/photography.html">here</a> to go to </span><strong><span style="color:#ff0000;">Step 2</span></strong><span style="color:#000000;">.</span></p>
        <p style="text-align: center;">
            *Save it using &#39;<strong>Save image as</strong>&#39; option from the right click/long press context menu.</p>

    </body>    
</html> 

upload.php

<?php
if (is_array($_FILES)) {
    $target_dir = "images/";
    $image_formats = array("jpg", "jpeg", "png", "gif"); //Image Formats
    if (is_uploaded_file($_FILES['userImage']['tmp_name'])) {
        $sourcePath = $_FILES['userImage']['tmp_name'];
        $targetPath = $target_dir . $_FILES['userImage']['name'];

        $size = $_FILES['userImage']['size'];

        $ext = pathinfo($targetPath, PATHINFO_EXTENSION); // Get Image Extension

        if (in_array($ext, $image_formats)) {
            if ($size < (4096 * 4096)) { // Image size max 4 MB

                $newWidth = 300;
                $newHeight = 300;

                $target = compressAndWatermark($sourcePath, $newWidth, $newHeight, $targetPath, $ext);

                if ($target) {
                    ?>
                    <img src="<?php echo $target; ?>" class="img-thumbnail" width="300" height="300" />
                    <?php
                }
            } else {
                echo "Max. image size is 4 MB.";
            }
        } else {
            echo "Image must be a jpg, png or gif.";
        }
    }
}

//Function for resize, compress and watermark to the images

function compressAndWatermark($tempFile, $newwidth, $newheight, $target, $ext) {

    $uploadTempFile = $tempFile;
    $watermark_png_file = 'watermark.png';  // Path of the watermark image
    list( $width, $height, $uploadType ) = getimagesize($uploadTempFile);
    if ($ext == "jpg" || $ext == "jpeg" || $ext == "JPEG" || $ext == "JPG") {
        $srcImage = imagecreatefromjpeg($uploadTempFile);
        $targetImage = imagecreatetruecolor($newwidth, $newwidth);
        $k = 1;
    } else if (($ext == "png") || ($ext == "PNG")) {
        $srcImage = imagecreatefrompng($uploadTempFile);
        $targetImage = imagecreatetruecolor($newwidth, $newwidth);
        $white = imagecolorallocate($targetImage, 255, 255, 255);  // To make the png images background white.
        imagefilledrectangle($targetImage, 0, 0, $width, $height, $white); // Fill the background with white.
        $k = 2;
    } else if ($ext == "gif" || $ext == "GIF") {
        $srcImage = imagecreatefromgif($uploadTempFile);
        $targetImage = imagecreatetruecolor($newwidth, $newwidth);
        $white = imagecolorallocate($targetImage, 255, 255, 255);
        imagefilledrectangle($targetImage, 0, 0, $width, $height, $white);
        $k = 3;
    }
    imagecopyresampled($targetImage, $srcImage, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    //Calculte the centre position of the images to watemark it.
    $watermark_left = ($newwidth / 2) - (300 / 2); //watermark left
    $watermark_bottom = ($newheight / 2) - (40 / 2); //watermark bottom
    $watermark = imagecreatefrompng($watermark_png_file); //watermark image
    // Use imagecopy() to merge two     images
    imagecopy($targetImage, $watermark, $watermark_left, $watermark_bottom, 0, 0, 300, 40); //merge image

    if ($k = 1) {
        imagejpeg($targetImage, $target, 100);
    } else if ($k = 2) {
        imagepng($targetImage, $target, 9);
    } else if ($k = 3) {
        imagepng($targetImage, $target);
    }
    // Free up the memory
    imagedestroy($targetImage);
    return $target;
}
?> 

You may see the index.html page working here

UPDATE : I solved the issue by myself. I just created another php file called download.php

<?php
if(isset($_REQUEST["file"])){
    // Get parameters
    $file = urldecode($_REQUEST["file"]); // Decode URL-encoded string
    $filepath = "images/" . $file;

    // Process download
    if(file_exists($filepath)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filepath));
        flush(); // Flush system output buffer
        readfile($filepath);
        exit;
    }
}
?> 

Then added the following line in the update.html

$filename = $_FILES['userImage']['name'];
echo '<br><p><a href="download.php?file=' . urlencode($filename) . '">Save image</a></p>'; 

1 Answers1

0

See this answer to a similar question. That is, do a redirect to:

<a href="data:text/url,my_image.jpg" target="_blank">
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
N. Kern
  • 401
  • 2
  • 7