8 Replies - 228 Views - Last Post: 10 May 2019 - 07:17 AM Rate Topic: -----

#1 vipery2kx   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 03-May 19

Image Upload - Resize then Watermark (with text)

Posted 03 May 2019 - 09:39 AM

I've been building a file upload form step by step making sure it works. First I've done the basic move_uploaded_file(), no problems there. That means this is not a permissions problem.

Yesterday I adjusted my code that adds $my_watermark = 'Some string to be the watermark'; (which of course is not the actual string or the variable I am using) and exchanged move_uploaded_file() to imagejpeg() or imagepng() (depending on my if($ext = 'png') {} else {} and that worked.

But the issue I have now, and I'm certain my variables are misplaced is when I added code to resize the image, hoping to also keep the aspect ratio.

My current code, the issue lies only in here:
      // image validation up here

      list( $src_width, $src_height ) = getimagesize( $f_name );
      $src_ratio = $src_width / $src_height;

      //make sure the new picture width is ~100% wide on screens upto 575px wide (using Bootstrap 4)
      if ( $ratio > 1 ) {
        $resized_width = 500;
        $resized_height = 500 / $ratio;
      } else {
        $resized_width = 500 * $ratio;
        $resized_height = 500;
      }

      $fontsize = 5;
      $wm_text = ' friendswebsite.com';

      // ---- I would like to center the text (harder to crop out and steal the picture), but this math put most of the wm_text string off the pic
      //$xPosition = ( ( $width / 2 ) - ( ( imagefontwidth( $fontsize ) * strlen( $wm_text ) ) / 2 ) );
      //$yPosition = ( ( $height / 2 ) - ( imagefontheight( $fontsize ) / 2 ) );
      // ---- As a temporarily solution I just filled in "10, 10" in the imagestring() function to place the text in the upper left hand corner

      if ( $file_ext == 'png' ) {
        $newImg = imagecreatefrompng( $f_temp );
      } else {
        $newImg = imagecreatefromjpeg( $f_temp );
      }

      $resized_img = imagecreatetruecolor( $resized_width, $resized_height );

      $fontcolor = imagecolorallocate( $resized_img, 128, 0, 128 );
      imagecopyresampled( $resized_img, $newImg, 0, 0, 0, 0, $resized_width, $resized_height, $width, $height );

      imagestring( $resized_img, $fontsize, 10, 10, $wm_text, $fontcolor );

      $f_name = /* generate a unique filename in each iteration */;
      $uploaded_path = $upload_folder . $f_name . '.' . $file_ext;

      if ( !file_exists( $uploaded_path ) ) {
        if ( $file_ext == 'png' ) {
          imagepng( $newImg, $uploaded_path );
        } else {
          imagejpeg( $newImg, $uploaded_path );
        }
      } else {/* echo a error message */}

      imagedestroy( $newImg );
      imagedestroy( $resized_img);



PS. This is in a foreach() loop... which also functions, which is why I excluded it.

Is This A Good Question/Topic? 0
  • +

Replies To: Image Upload - Resize then Watermark (with text)

#2 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2290
  • View blog
  • Posts: 6,981
  • Joined: 15-January 14

Re: Image Upload - Resize then Watermark (with text)

Posted 03 May 2019 - 10:44 AM

What happens when you run that, what is the output? I'm not clear on what the actual problem is.
Was This Post Helpful? 0
  • +
  • -

#3 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2290
  • View blog
  • Posts: 6,981
  • Joined: 15-January 14

Re: Image Upload - Resize then Watermark (with text)

Posted 03 May 2019 - 10:50 AM

If the problem is working out the size to maintain the aspect ratio, here's a function I wrote to resize an image that will maintain aspect ratio and transparent background. Note that this will only resize images to be smaller, not larger.

function resize_image($opts)
{
    $src = isset($opts['source']) ? $opts['source'] : '';
    $dest = isset($opts['dest']) ? $opts['dest'] : '';
    $w = isset($opts['w']) ? intval($opts['w']) : 0;
    $h = isset($opts['h']) ? intval($opts['h']) : 0;

    if ($src == '') {
        return;
    }
    if ($w == 0 && $h == 0) {
        return;
    }

    if ($dest == '') {
        $dest = $src;
    } // resize in place

    // open the image
    $ext = strtolower(array_pop(explode('.', $src)));
    switch ($ext) {
        case 'jpg':
        case 'jpeg':
            $i = imagecreatefromjpeg($src);
            break;

        case 'gif':
            $i = imagecreatefromgif($src);
            break;

        case 'png':
            $i = imagecreatefrompng($src);
            break;

        default:
            return;
    }

    $new_w = imagesx($i);
    $new_h = imagesy($i);

    if (($w != 0 && $new_w <= $w && $h == 0) ||
        ($w == 0 && $h != 0 && $new_h <= $h) ||
        ($w != 0 && $new_w <= $w && $h != 0 && $new_h <= $h)) {
        // image is small enough
        if ($dest != $src) {
            copy($src, $dest);
        }
        return;
    }

    // determine new size
    if ($w != 0 && $new_w > $w) {
        $new_h = ($w / $new_w) * $new_h;
        $new_w = $w;
    }
    if ($h != 0 && $new_h > $h) {
        $new_w = ($h / $new_h) * $new_w;
        $new_h = $h;
    }

    // resize
    $new = imagecreatetruecolor($new_w, $new_h);

    if ($ext == 'png' || $ext == 'gif') {
        $trnprt_indx = imagecolortransparent($i);

        // If we have a specific transparent color
        if ($trnprt_indx >= 0) {
            // Get the original image's transparent color's RGB values
            $trnprt_color = imagecolorsforindex($i, $trnprt_indx);

            // Allocate the same color in the new image resource
            $trnprt_indx = imagecolorallocate($new, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);

            // Completely fill the background of the new image with allocated color.
            imagefill($new, 0, 0, $trnprt_indx);

            // Set the background color for new image to transparent
            imagecolortransparent($new, $trnprt_indx);
        } // Always make a transparent background color for PNGs that don't have one allocated already
        elseif ($ext == 'png') {
            // Turn off transparency blending (temporarily)
            imagealphablending($new, false);

            // Create a new transparent color for image
            $color = imagecolorallocatealpha($new, 0, 0, 0, 127);

            // Completely fill the background of the new image with allocated color.
            imagefill($new, 0, 0, $color);

            // Restore transparency blending
            imagesavealpha($new, true);
        }
    }

    imagecopyresampled($new, $i, 0, 0, 0, 0, $new_w, $new_h, imagesx($i), imagesy($i));
    imagedestroy($i);

    // save the image
    switch ($ext) {
        case 'jpg':
        case 'jpeg':
            imagejpeg($new, $dest);
            break;

        case 'gif':
            imagegif($new, $dest);
            break;

        case 'png':
            imagepng($new, $dest);
            break;
    }

    imagedestroy($new);
}

Was This Post Helpful? 1
  • +
  • -

#4 vipery2kx   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 03-May 19

Re: Image Upload - Resize then Watermark (with text)

Posted 03 May 2019 - 10:57 AM

I will try your function. What do I define in $opts?

When I added the code that would resize images, the uploading parameter of both imagejpeg() and imagepng() broke.
So if the watermarking code still worked (or broke like everything else), I have no way of knowing.
Was This Post Helpful? 0
  • +
  • -

#5 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2290
  • View blog
  • Posts: 6,981
  • Joined: 15-January 14

Re: Image Upload - Resize then Watermark (with text)

Posted 03 May 2019 - 01:13 PM

You're saving $newImg rather than $resized_img.

The code in my function to calculate the dimensions starts on line 52 if you want to just see how I did it. It figures out if either dimension is too large for what was requested, and figures out what it should be. If you specify max width of 300, and the width is 400, then it sets the width to 300 and calculates the appropriate height. The width and height are optional, if either one is left out it resizes according to the aspect ratio. If both are given it doesn't check the aspect ratio, it just resizes to that size. E.g.:

resize_image([
  'source' => 'uploaded.png',
  'dest' => 'resized.png',
  'w' => 300 // max width of 300px, resize h appropriately
]);

Was This Post Helpful? 0
  • +
  • -

#6 vipery2kx   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 03-May 19

Re: Image Upload - Resize then Watermark (with text)

Posted 03 May 2019 - 06:41 PM

Yeah, I realized that along with a couple of other typos. I didn't CMD+Z far enough before I copied my code and pasted it here.

Thank you ArtificialSoldier. That solved the aspect ratio problem and my images upload with the desired watermark string.
Now the final step, place the watermark dead center in the resized image.

$xPosition = ( ( $width / 2 ) - ( ( imagefontwidth( $fontsize ) * strlen( $wm_text ) ) / 2 ) );
$yPosition = ( ( $height / 2 ) - ( imagefontheight( $fontsize ) / 2 ) );



This math placed the watermark mostly off the image, I attached the output image.
Those purple-ish letters at the very top above the "About Me". In this image, the desired location would be right above the "Hello<br>".

View Postvipery2kx, on 03 May 2019 - 06:39 PM, said:

Yeah, I realized that along with a couple of other typos. I didn't CMD+Z far enough before I copied my code and pasted it here.

Thank you ArtificialSoldier. That solved the aspect ratio problem and my images upload with the desired watermark string.
Now the final step, place the watermark dead center in the resized image.

$xPosition = ( ( $width / 2 ) - ( ( imagefontwidth( $fontsize ) * strlen( $wm_text ) ) / 2 ) );
$yPosition = ( ( $height / 2 ) - ( imagefontheight( $fontsize ) / 2 ) );



This math placed the watermark mostly off the image, I attached the output image.
Those purple-ish letters at the very top above the "About Me". In this image, the desired location would be right above the "Hello<br>".


I thought attaching the file(s) was automatic.

Attached image(s)

  • Attached Image

Was This Post Helpful? 0
  • +
  • -

#7 vipery2kx   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 03-May 19

Re: Image Upload - Resize then Watermark (with text)

Posted 03 May 2019 - 09:45 PM

Turns out a few variables didn't match up (again). I fixed that.

I got the text vertically centered... but the first letter of my desired string starts in the center, it is not centered.

My code:
$xPosition = ( ( $newWidth / 2 ) - ( ( imagefontwidth( $fontsize ) + strlen( $wm_text ) ) / 2 ) );
$yPosition = ( ( $newHeight / 2 ) - ( imagefontheight( $fontsize ) / 2 ) );



My reference: Center a text on an image using imagestring()
Was This Post Helpful? 0
  • +
  • -

#8 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2290
  • View blog
  • Posts: 6,981
  • Joined: 15-January 14

Re: Image Upload - Resize then Watermark (with text)

Posted 06 May 2019 - 01:18 PM

If it starts in the center, then that second half of your width equation is 0. Make sure you have PHP set to report all errors, and set it up to use an error log so that error messages don't corrupt the image data. Check the error log for any errors from your code.

Your calculation is not the same one they're using on the other page, maybe that's the problem. That's only going to be a few pixels off-center because you're adding instead of multiplying.
Was This Post Helpful? 1
  • +
  • -

#9 vipery2kx   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 03-May 19

Re: Image Upload - Resize then Watermark (with text)

Posted 10 May 2019 - 07:17 AM

I knew something didn't look right. Thanks ArtificialSoldier.

*SOLVED & ClOSED* (somehow)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1