Image Resizing Script required - a better one...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Image Resizing Script required - a better one...

Post by Celauran »

So what is it doing? Is there anything in your error log? I can't run this file, so I need you to explain how and where it's failing.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Image Resizing Script required - a better one...

Post by simonmlewis »

Errors tend to show on screen.
The error log in camp is I think error_log.php. It's big. So I need to empty and rerun.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Image Resizing Script required - a better one...

Post by simonmlewis »

Ok I see what is going on.
PArt of the script renames it, the other part doesn't.
So when I am checking for the new filename it finds only one.

The renaming bit is at fault.......... somewhere.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Image Resizing Script required - a better one...

Post by Celauran »

You've got $random and $prefix doing the same thing but in different places, which means they're going to have different values. Looks like you've got slightly different formatting here:

Code: Select all

    $target_directory = $_SERVER['DOCUMENT_ROOT']."/images/pages/";
    $random = (rand()%99999999);
    $pic=($_FILES['homeimage']['name']);
    $newname="$random"."$pic";
    $target = $target_directory . $newname;
and here:

Code: Select all

        $new_filename = "{$prefix}_{$pathinfo['filename']}{$key}.{$pathinfo['extension']}";
        $image->resize($scaled_box)->save($target_directory . '/' . $new_filename);
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Image Resizing Script required - a better one...

Post by simonmlewis »

Exactly.
But this also fails. In fact, on the original image it doesn't rename it at all, but on your bit, it does.. but only obviously the new ones.

Code: Select all

// ADD ALL BANNERS (SQUARE AND DOUBLE)
if ($update == "addbanner")
{
  if (isset($layertype))
  {
    $result = mysql_query ("SELECT id FROM products WHERE romancode = '$searchurl'");
    $num_result = mysql_num_rows($result);
    if ($num_result > 1)
    {
    $disableupload = "yes";
    echo "<script>
  window.location.replace('/a_home&status=duplicatecode')
  </script>";
    }
  }
 
  if (!isset($disableupload))
  {
    if ($stockbanner == "yes")
    {
      if ($searchurl != "")
      {
      mysql_query("INSERT INTO homepage (url, section, freetext, priority, content, homepromocolor, homepromotextcolor, stockbanner) VALUES ('$searchurl', '$section', '$freetext', '$priority', '$content', '$homepromocolor', '$homepromotextcolor', '$stockbanner')");
      }
      elseif ($searchurl == "")
      {
      mysql_query("INSERT INTO homepage (url, section, freetext, priority, content, homepromocolor, homepromotextcolor, stockbanner) VALUES ('$url', '$section', '$freetext', '$priority', '$content', '$homepromocolor', '$homepromotextcolor', '$stockbanner')");
      }
      echo "<script>
  window.location.replace('/a_home')
  </script>";
    }
    else
    {
    $target_directory = $_SERVER['DOCUMENT_ROOT']."/images/pages/";
    $random = (rand()%99999999);
    $pic=($_FILES['homeimage']['name']);
    $newname="$random_"."$pic";
    $target = $target_directory . $newname;
    if ($searchurl != "")
  {
  mysql_query("INSERT INTO homepage(url, image, section, freetext, priority, content, homepromocolor, homepromotextcolor, stockbanner) VALUES ('$searchurl', '$newname', '$section', '$freetext', '$priority', '$content', '$homepromocolor', '$homepromotextcolor', '$stockbanner')");
  }
  elseif ($searchurl == "")
  {
  mysql_query("INSERT INTO homepage(url, image, section, freetext, priority, content, homepromocolor, homepromotextcolor, stockbanner) VALUES ('$url', '$newname', '$section', '$freetext', '$priority', '$content', '$homepromocolor', '$homepromotextcolor', '$stockbanner')");
  }
 
require_once dirname(__DIR__) . '/vendor/autoload.php';
$imagine = new Imagine\Gd\Imagine();
// An array of widths, keyed by target screen size
$widths = [
    '475' => 237,
    '768' => 384,
    '1920' => 451,
];

// If we have an uploaded image without errors
if (!empty($_FILES) && isset($_FILES['homeimage'])) {
    $pathinfo = pathinfo($_FILES['homeimage']['name']);

    // Open the uploaded image with the Imagine library
    $image = $imagine->open($_FILES['homeimage']['tmp_name']);

    // Save the original
    $image->save($target_directory . '/' . $pathinfo['basename']);

    // Get image size
    $box = $image->getSize();

    // Resize
    foreach ($widths as $key => $width) {
        $ratio = $width / $box->getWidth();
        $scaled_box = $box->scale($ratio);
        $new_filename = "{$random}_{$pathinfo['filename']}{$key}.{$pathinfo['extension']}";
        $image->resize($scaled_box)->save($target_directory . '/' . $new_filename);
    }
}
  //Writes the photo to the server
  if(move_uploaded_file($_FILES['homeimage']['tmp_name'], $target))
    {
echo "<script>
  window.location.replace('/a_home')
  </script>";
    }
  }
}}
}
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Image Resizing Script required - a better one...

Post by simonmlewis »

That's it - I cracked it.

Code: Select all

// ADD ALL BANNERS (SQUARE AND DOUBLE)
if ($update == "addbanner")
{
  if (isset($layertype))
  {
    $result = mysql_query ("SELECT id FROM products WHERE romancode = '$searchurl'");
    $num_result = mysql_num_rows($result);
    if ($num_result > 1)
    {
    $disableupload = "yes";
    echo "<script>
  window.location.replace('/a_home&status=duplicatecode')
  </script>";
    }
  }
 
  if (!isset($disableupload))
  {
    if ($stockbanner == "yes")
    {
      if ($searchurl != "")
      {
      mysql_query("INSERT INTO homepageairsoft (url, section, freetext, priority, content, homepromocolor, homepromotextcolor, stockbanner) VALUES ('$searchurl', '$section', '$freetext', '$priority', '$content', '$homepromocolor', '$homepromotextcolor', '$stockbanner')");
      }
      elseif ($searchurl == "")
      {
      mysql_query("INSERT INTO homepageairsoft (url, section, freetext, priority, content, homepromocolor, homepromotextcolor, stockbanner) VALUES ('$url', '$section', '$freetext', '$priority', '$content', '$homepromocolor', '$homepromotextcolor', '$stockbanner')");
      }
      echo "<script>
  window.location.replace('/a_home')
  </script>";
    }
    else
    {
    $target_directory = $_SERVER['DOCUMENT_ROOT']."/images/pages/";
    $random = (rand()%99999999);
    $pic=($_FILES['homeimage']['name']);
    $newname= $random . "_". $pic;
    $target = $target_directory . $newname;
    if ($searchurl != "")
  {
  mysql_query("INSERT INTO homepageairsoft(url, image, section, freetext, priority, content, homepromocolor, homepromotextcolor, stockbanner) VALUES ('$searchurl', '$newname', '$section', '$freetext', '$priority', '$content', '$homepromocolor', '$homepromotextcolor', '$stockbanner')");
  }
  elseif ($searchurl == "")
  {
  mysql_query("INSERT INTO homepageairsoft(url, image, section, freetext, priority, content, homepromocolor, homepromotextcolor, stockbanner) VALUES ('$url', '$newname', '$section', '$freetext', '$priority', '$content', '$homepromocolor', '$homepromotextcolor', '$stockbanner')");
  }
 
require_once dirname(__DIR__) . '/vendor/autoload.php';
$imagine = new Imagine\Gd\Imagine();
// An array of widths, keyed by target screen size
$widths = [
    '475' => 237,
    '768' => 384,
    '1920' => 451,
];

// If we have an uploaded image without errors
if (!empty($_FILES) && isset($_FILES['homeimage'])) {
    $pathinfo = pathinfo($_FILES['homeimage']['name']);

    // Open the uploaded image with the Imagine library
    $image = $imagine->open($_FILES['homeimage']['tmp_name']);

    // Save the original
    $image->save($target_directory . '/' . $pathinfo['basename']);

    // Get image size
    $box = $image->getSize();

    // Resize
    foreach ($widths as $key => $width) {
        $ratio = $width / $box->getWidth();
        $scaled_box = $box->scale($ratio);
        $new_filename = "{$random}_{$pathinfo['filename']}_{$key}.{$pathinfo['extension']}";
        $image->resize($scaled_box)->save($target_directory . '/' . $new_filename);
    }
}
  //Writes the photo to the server
  if(move_uploaded_file($_FILES['homeimage']['tmp_name'], $target))
    {
echo "<script>
  window.location.replace('/a_homeairsoft')
  </script>";
    }
  }
}}
}
I tweaked my original renaming script. Thinking the _ would be playing havoc with the variable $random.
I've also adjusted the tail end of your part, so there is an _ there too, to separate out the numbers.

My next job is to dynamically delete all three images, as well as the main one.
In theory, this is just a simple delete script, with a few extra processes for the three others.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Image Resizing Script required - a better one...

Post by Celauran »

I noticed the $random_, which was causing problems. Good idea to wrap variables in braces when interpolating them. I was also just looking at this and arrived at something similar, though I wrapped the main image renaming block inside a check for $_FILES and added back the hyphen before the suffix.

Code: Select all

<?php

// Had to initialize these to get things working at all
$update = 'addbanner';
$stockbanner = '';

// ADD ALL BANNERS (SQUARE AND DOUBLE)
if ($update == "addbanner") {
    if (isset($layertype)) {
        $result = mysql_query ("SELECT id FROM products WHERE romancode = '$searchurl'");
        $num_result = mysql_num_rows($result);
        if ($num_result > 1) {
            $disableupload = "yes";
            echo "<script>window.location.replace('/a_home&status=duplicatecode')</script>";
        }
    }

    if (!isset($disableupload)) {
        if ($stockbanner == "yes") {
            if ($searchurl != "") {
                mysql_query("INSERT INTO homepage (url, section, freetext, priority, content, homepromocolor, homepromotextcolor, stockbanner) VALUES ('$searchurl', '$section', '$freetext', '$priority', '$content', '$homepromocolor', '$homepromotextcolor', '$stockbanner')");
            } elseif ($searchurl == "") {
                mysql_query("INSERT INTO homepage (url, section, freetext, priority, content, homepromocolor, homepromotextcolor, stockbanner) VALUES ('$url', '$section', '$freetext', '$priority', '$content', '$homepromocolor', '$homepromotextcolor', '$stockbanner')");
            }
            echo "<script>window.location.replace('/a_home')</script>";
        } else {
            // If we have an uploaded image without errors
            if (!empty($_FILES) && isset($_FILES['homeimage']) && $_FILES['homeimage']['error'] === 0) {
                $target_directory = $_SERVER['DOCUMENT_ROOT']."/images/pages/";
                $random = rand() % 99999999;
                $pic = $_FILES['homeimage']['name'];
                $newname = "{$random}_{$pic}";
                $target = $target_directory . $newname;

                /* Commented out since I've no database attached
                if ($searchurl != "") {
                    mysql_query("INSERT INTO homepage(url, image, section, freetext, priority, content, homepromocolor, homepromotextcolor, stockbanner) VALUES ('$searchurl', '$newname', '$section', '$freetext', '$priority', '$content', '$homepromocolor', '$homepromotextcolor', '$stockbanner')");
                } elseif ($searchurl == "") {
                    mysql_query("INSERT INTO homepage(url, image, section, freetext, priority, content, homepromocolor, homepromotextcolor, stockbanner) VALUES ('$url', '$newname', '$section', '$freetext', '$priority', '$content', '$homepromocolor', '$homepromotextcolor', '$stockbanner')");
                }
                 */

                require_once dirname(__DIR__) . '/vendor/autoload.php';
                $imagine = new Imagine\Gd\Imagine();

                // An array of widths, keyed by target screen size
                $widths = [
                    '475' => 237,
                    '768' => 384,
                    '1920' => 451,
                ];

                $pathinfo = pathinfo($_FILES['homeimage']['name']);

                // Open the uploaded image with the Imagine library
                $image = $imagine->open($_FILES['homeimage']['tmp_name']);

                // Save the original
                // You probably don't want this as it does not prepend $random
                // $image->save($target_directory . '/' . $pathinfo['basename']);

                // Get image size
                $box = $image->getSize();

                // Resize
                foreach ($widths as $key => $width) {
                    $ratio = $width / $box->getWidth();
                    $scaled_box = $box->scale($ratio);
                    $new_filename = "{$random}_{$pathinfo['filename']}-{$key}.{$pathinfo['extension']}";
                    $image->resize($scaled_box)->save($target_directory . '/' . $new_filename);
                }

                //Writes the photo to the server
                if (move_uploaded_file($_FILES['homeimage']['tmp_name'], $target)) {
                    echo "<script>window.location.replace('/a_home')</script>";
                }
            }
        }
    }
}

?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Image Resizing</title>
    </head>
    <body>
        <form method="POST" enctype="multipart/form-data">
            <input type="file" name="homeimage">
            <button>Submit</button>
        </form>
    </body>
</html>
Note this is not meant to be copy/pasted into your own file (which is where so many problems are introduced) but simply for demonstration.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Image Resizing Script required - a better one...

Post by Celauran »

simonmlewis wrote:My next job is to dynamically delete all three images, as well as the main one.
In theory, this is just a simple delete script, with a few extra processes for the three others.
glob and unlink and you're done.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Image Resizing Script required - a better one...

Post by simonmlewis »

Glob and unlink...????
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Image Resizing Script required - a better one...

Post by Celauran »

Additionally, I'm also noticing a fair bit of duplication in this file. Could easily extract some functions to make maintenance easier. Just a thought.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Image Resizing Script required - a better one...

Post by simonmlewis »

Mmmmm. I've used unlink. Not heard of glob.
Not quite sure how that would be better than a similar target_directory kind of thing, to tell it where they are, and delete.
Obviously need to state and break up the files, so it does it for 475, 768 and 1920.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Image Resizing Script required - a better one...

Post by Celauran »

simonmlewis wrote:Obviously need to state and break up the files, so it does it for 475, 768 and 1920.
That's where glob comes in. Give it a pattern and it will return all the files matching that pattern. You can then loop over the results and delete each file with unlink.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Image Resizing Script required - a better one...

Post by simonmlewis »

pattern? i.e. the original filename??
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Image Resizing Script required - a better one...

Post by simonmlewis »

I've found this today:

Code: Select all

<?php
   $mask = "*.jpg"
   array_map( "unlink", glob( $mask ) );
?>
So is it somehow smart enough if I make $mask be:
$mask = $row->image;

And then it finds all those where the files are like: 34456_354556shirt.jpg?
So 34456_354556shirt-475.jpg would also get deleted??
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
Post Reply