3

I am trying to watermark images on upload.

I have a multi upload script in place which works fine, see below:

           $gallery=$_GET["gallery"];
                    $album=$_GET["album"];
if(isset($_FILES['files'])){
    $errors= array();
    foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
        $file_name = $key.$_FILES['files']['name'][$key];
        $file_size =$_FILES['files']['size'][$key];
        $file_tmp =$_FILES['files']['tmp_name'][$key];
        $file_type=$_FILES['files']['type'][$key];  
        if($file_size > 2097152){
            $errors[]='File size must be less than 2 MB';
        }       
        $query="INSERT into commerce_images (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`, `added_by`, `gallery_id`, `sub_gallery_id`) 
        VALUES('$user','$file_name','$file_size','$file_type', '$Fname $Sname', '$gallery', '$album'); ";
        $desired_dir="uploads";
        if(empty($errors)==true){
            if(is_dir($desired_dir)==false){
                mkdir("$desired_dir", 0700);        // Create directory if it does not exist
            }
            if(is_dir("$desired_dir/".$file_name)==false){
                move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
            }else{                                  // rename the file if another one exist
                $new_dir="$desired_dir/".$file_name.time();
                 rename($file_tmp,$new_dir) ;               
            }
         mysql_query($query);           
        }else{
                print_r($errors);
        }
    }
    if(empty($error)){
?>

<script>location.assign("commerce-images.php?state=new");</script>
                                        <?php
    }
}
?>

Is it possible to watermark all images uploaded using my script?

Boaz
  • 19,892
  • 8
  • 62
  • 70
Shaun
  • 153
  • 8

2 Answers2

2

Off topic, but requested, hopefully it helps someone get from mysql_* to PDO out there. PDO Manual Page for bindParam, to point you someplace at least.

Schema

create table commerce_images 
(   `id` int auto_increment primary key,
    `USER_ID` int not null,
    `FILE_NAME` varchar(123) not null,
    `FILE_SIZE` int not null,
    `FILE_TYPE` int not null, 
    `added_by` varchar(100), 
    `gallery_id` int not null, 
    `sub_gallery_id` int not null
);

php

<?php
    // Begin Vault (this is in a vault, not actually hard-coded)
    $host="localhost";
    $username="GuySmiley";
    $password="anchovies_¿^?fish╔&®";
    $dbname="so_gibberish";
    // End Vault

    try {

        $dbh = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $user=456;
        $file_name="/path";
        $file_size=29832;
        $file_type=3;
        $Fname="Kim";
        $Sname="Billings";
        $gallery=35;
        $album=9;

        $FullName="$Fname $Sname";

        // prepared statement with named placeholders for sanity of not using index values of placeholders
        $stmt = $dbh->prepare("INSERT into commerce_images (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`, `added_by`, `gallery_id`, `sub_gallery_id`) 
        VALUES(:user,:file_name,:file_size,:file_type,:FullName,:gallery,:album)");
        $stmt->bindParam(':user', $user, PDO::PARAM_INT);   // correct this datatype
        $stmt->bindParam(':file_name', $file_name, PDO::PARAM_STR,123); // size it
        $stmt->bindParam(':file_size', $file_size, PDO::PARAM_INT);
        $stmt->bindParam(':file_type', $file_type, PDO::PARAM_INT); // correct this datatype
        $stmt->bindParam(':FullName', $FullName, PDO::PARAM_STR,123);   // size it
        $stmt->bindParam(':gallery', $gallery, PDO::PARAM_INT); // correct this datatype
        $stmt->bindParam(':album', $album, PDO::PARAM_INT); // correct this datatype
        $stmt->execute();

        $stmt = null;
        // PDO closes connection at end of script

    } catch (PDOException $e) {
        echo 'PDO Exception: ' . $e->getMessage();
        exit();
    }
?>

Results

select * from commerce_images;
+----+---------+-----------+-----------+-----------+--------------+------------+----------------+
| id | USER_ID | FILE_NAME | FILE_SIZE | FILE_TYPE | added_by     | gallery_id | sub_gallery_id |
+----+---------+-----------+-----------+-----------+--------------+------------+----------------+
|  1 |     456 | /path     |     29832 |         3 | Kim Billings |         35 |              9 |
+----+---------+-----------+-----------+-----------+--------------+------------+----------------+
Drew
  • 24,851
  • 10
  • 43
  • 78
  • Thanks, does this also do the watermar? – Shaun Sep 12 '15 at 16:40
  • No, this code is responsible for one thing only (as it should be), handling the persistence to database. – kayess Sep 12 '15 at 16:41
  • no sir, as seen in earlier comments, as I was saying I would show PDO while the smart PHP people helped with watermarks. – Drew Sep 12 '15 at 16:41
1

While OP's question wasnt crystal clear on the exact method of watermarking, im showing here text and image watermarking capabilities using the GD library.


Adding text as watermark (using TTF font): Gist

function add_text_watermark($kep,$Text,$WatermarkNeeded = 1) {
    list($img_type, $Image) = getImage($kep);

$sx = imagesx($Image) ;
$sy = imagesy($Image) ;

if ($WatermarkNeeded)
    { 
    /* Set the font */
    $Font="_arial.ttf";
    $FontColor = ImageColorAllocate ($Image,204,204,204) ;
    $FontShadow = ImageColorAllocate ($Image,100,100,100) ;
    $Rotation = 0 ;
    /* Make a copy image */
    $OriginalImage = ImageCreateTrueColor($sx,$sy) ;
    ImageCopy ($OriginalImage,$Image,0,0,0,0,$sx,$sy) ;

    /* Iterate to get the size up */
    $FontSize=1 ;
    do
        {
        $FontSize *= 1.1 ;
        $Box = @ImageTTFBBox($FontSize,0,$Font,$Text);
        $TextWidth = abs($Box[4] - $Box[0]) ;
        $TextHeight = abs($Box[5] - $Box[1]) ;
        }
    while ($TextWidth < $sx*0.9 && $FontSize < 30) ;
    /*  Awkward maths to get the origin of the text in the right place */
    $x = $sx/2 - cos(deg2rad($Rotation))*$TextWidth/2 ;
    $y = $sy/2 + sin(deg2rad($Rotation))*$TextWidth/2 + cos(deg2rad($Rotation))*$TextHeight/2 ;
    /* Make shadow text first followed by solid text */

    ImageTTFText ($Image,$FontSize,$Rotation,$x+1,$y+1,$FontShadow,$Font,$Text);
    ImageTTFText ($Image,$FontSize,$Rotation,$x,$y,$FontColor,$Font,$Text);

    /* merge original image into version with text to show image through text */
    ImageCopyMerge ($Image,$OriginalImage,0,0,0,0,$sx,$sy,50) ;
    imagejpeg($Image, $kep, 100);
    }
}

function getImage($res) {
    $img = "";
    $type = "";

    if (intval(@imagesx($res)) > 0) {
        $img = $res;
    } else {
        $imginfo = getimagesize($res);

        switch($imginfo[2]) { // Determine type
            case 1:
                $type = "GIF";
                if (function_exists("imagecreatefromgif")) {
                    $img = imagecreatefromgif($res);
                } else {
                    die("Unsupported image type: $type");
                }
                break;
            case 2:
                $type = "JPG";
                if (function_exists("imagecreatefromjpeg")) {
                    $img = imagecreatefromjpeg($res);
                } else {
                    die("Unsupported image type: $type");
                }
                break;
            case 3:
                $type = "PNG";
                if (function_exists("imagecreatefrompng")) {
                    $img = imagecreatefrompng($res);
                } else {
                    die("Unsupported image type: $type");
                }
                break;
        }
    }

    return array($type, $img);
}

EDIT: make sure the ttf font file you are trying to add as watermark text are in sight of the path!


Adding Image as watermark: Gist

function generate_watermarked_image($originalFileContents, $originalWidth, $originalHeight, $paddingFromBottomRight = 0, $watermarkFileLocation = 'logo.png') {
$watermarkImage = imagecreatefrompng($watermarkFileLocation);
$watermarkWidth = imagesx($watermarkImage);  
$watermarkHeight = imagesy($watermarkImage);

$originalImage = imagecreatefromstring($originalFileContents);

$destX = $originalWidth - $watermarkWidth - $paddingFromBottomRight;  
$destY = $originalHeight - $watermarkHeight - $paddingFromBottomRight;

// creating a cut resource
$cut = imagecreatetruecolor($watermarkWidth, $watermarkHeight);

// copying that section of the background to the cut
imagecopy($cut, $originalImage, 0, 0, $destX, $destY, $watermarkWidth, $watermarkHeight);

// placing the watermark now
imagecopy($cut, $watermarkImage, 0, 0, 0, 0, $watermarkWidth, $watermarkHeight);

// merging both of the images
imagecopymerge($originalImage, $cut, $destX, $destY, 0, 0, $watermarkWidth, $watermarkHeight, 100);

return $originalImage;
}

You can call it as:

$Image = "$desired_dir/".$file_name;

imagejpeg(generate_watermarked_image(file_get_contents($Image), imagesx($Image), imagesy($Image), 10), $Image."-watermarked.jpg", 100);

EDIT: make sure the logo.png or whatever file you are trying to add as watermark are in sight of the path!

kayess
  • 3,384
  • 9
  • 28
  • 45
  • Thanks where in my code does this go / what does it replace? – Shaun Sep 12 '15 at 15:54
  • @Shaun IMHO right at the place where you are storing the file at its final place. Eg. after your file system operations copy/move/rename. – kayess Sep 12 '15 at 15:56
  • ermm, new to this and have no idea? sorry!? – Shaun Sep 12 '15 at 15:59
  • @Shaun before or after where you have the line with `mysql_query($query);`. Which i meant as the file is stored on its final place at. – kayess Sep 12 '15 at 16:03
  • @kayees sorry to be a pest, but could you show me the new code (mine above) edited with yours? – Shaun Sep 12 '15 at 16:05
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/89466/discussion-between-shaun-and-kayess). – Shaun Sep 12 '15 at 16:14