Page 1 of 37

Image Resizing Script required - a better one...

Posted: Tue Mar 07, 2017 3:35 am
by simonmlewis
This is the image resize script I use. But I have used it for years, so I wonder if there is a better version (that will still run on 5.4 ... don't ask!).

I will need to resize images three times. So it would be good to find a script that doesn't have to be run over and over. Rather ... take the image, and resize it to the three sizes effectively.

Here is my current one:

Code: Select all

if(get_magic_quotes_gpc()) {
      $input = array(&$_GET, &$_POST, &$_COOKIE, &$_ENV, &$_SERVER);
     
      while(list($k, $v) = each($input)) {
        foreach($v as $key => $val) {
          if(!is_array($val)) {
            $input[$k][$key] = stripslashes($val);
            continue;
          }
          $input[] =& $input[$k][$key];
        }
      }
      unset($input);
    }
    
error_reporting(0);

$change="";
$abc="";

 define ("MAX_SIZE","400");
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }

 $errors=0;
  
 if($_SERVER["REQUEST_METHOD"] == "POST")
 {
 	$image =$_FILES["photo"]["name"];
	$uploadedfile = $_FILES['photo']['tmp_name'];    
 
 	if ($image) 
 	{
 	
 		$filename = stripslashes($_FILES['photo']['name']);
 	
  		$extension = getExtension($_FILES['photo']['name']);
 		$extension = strtolower($extension);
		
		
 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
 		{
		
 			$change='<div class="msgdiv">Unknown Image extension </div> ';
 			$errors=1;
 		}
 		else
 		{

 $sizechange=filesize($_FILES['photo']['tmp_name']);


if ($sizechange > MAX_*1024)
{
	$change='<div class="msgdiv">You have exceeded the size limit!</div> ';
	$errors=1;
}


if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['photo']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);

}
else if($extension=="png")
{
$uploadedfile = $_FILES['photo']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);

}
else 
{
$src = imagecreatefromgif($uploadedfile);
}

echo $scr;

list($width,$height)=getimagesize($uploadedfile);
$tmp=imagecreatetruecolor($width,$height);

$newwidth1=600;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);

imagecopyresampled($tmp,$src,0,0,0,0,$width,$height,$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
$pic=($_FILES['photo']['name']);
srand(time());
$random = (rand()%99999999);
$newname="$random"."$pic";
$filename = "images/productphotos/". $newname;
$filename1 = "images/productphotos/small/". $newname;
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}

}
These will not be in separate folders.
They will be resized, and (taken from my previous thread here splitting up filename and extension), will just need renaming for each size:

$newname475 = $filename . "-475" . $extension;
$newname768 = $filename . "-768" . $extension;
$newname1920 = $filename . "-1920" . $extension;

Hope someone can help. Thanks.

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

Posted: Tue Mar 07, 2017 5:21 am
by Celauran
Take a look at the Imagine library.

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

Posted: Tue Mar 07, 2017 5:29 am
by simonmlewis
Is that not a script I can just add to, or do I need to "install" something?
I'm looking for one that I can just run a script with.

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

Posted: Tue Mar 07, 2017 5:31 am
by Celauran
Easiest would be to pull it in with Composer, then just follow the instructions on their docs page. It's pretty simple to use. If you need to make some customizations, I'd recommend making a wrapper class for it.

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

Posted: Tue Mar 07, 2017 5:37 am
by simonmlewis
I am not familiar with Composer. I'm just familiar with adding scripts to a page.

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

Posted: Tue Mar 07, 2017 5:40 am
by Celauran
You really ought to familiarise yourself with it. Fortunately, it's also quite easy to use. https://getcomposer.org/

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

Posted: Tue Mar 07, 2017 6:25 am
by simonmlewis
I need to install it on my windows machine too.

These is where I am at with my older script, trying to enhance it.
Different banners will need to be different sizes, so the site is dependent on a variable value.

The three versions won't be in the database. They will be gathered "on the fly" in the code.

So I just need the one to be uploaded 'as is', and then the others to be resized and renamed "on upload".

Take a look at it so far. It will prob through a ton of errors, but you can maybe see where I am going with it.

Code: Select all

   $target = $_SERVER['DOCUMENT_ROOT']."/images/pages/";
    $random = (rand()%99999999);
    $pic=($_FILES['homeimage']['name']);
    $newname="$random"."$pic";
        
if(get_magic_quotes_gpc()) {
      $input = array(&$_GET, &$_POST, &$_COOKIE, &$_ENV, &$_SERVER);
     
      while(list($k, $v) = each($input)) {
        foreach($v as $key => $val) {
          if(!is_array($val)) {
            $input[$k][$key] = stripslashes($val);
            continue;
          }
          $input[] =& $input[$k][$key];
        }
      }
      unset($input);
    }
    
error_reporting(0);

$change="";
$abc="";

 define ("MAX_SIZE","400");
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }

 $errors=0;
  
 if($_SERVER["REQUEST_METHOD"] == "POST")
 {
 	$image =$_FILES["image"]["name"];
	$uploadedfile = $_FILES['image']['tmp_name'];    
 
 	if ($image) 
 	{
 	
 		$filename = stripslashes($_FILES['image']['name']);
  	$extension = getExtension($_FILES['image']['name']);
 		$extension = strtolower($extension);
		
		
 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
 		{
		
 			$change='<div class="msgdiv">Unknown Image extension </div> ';
 			$errors=1;
 		}
 		else
 		{

 $sizechange=filesize($_FILES['image']['tmp_name']);

if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['image']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);

}
else if($extension=="png")
{
$uploadedfile = $_FILES['image']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else 
{
$src = imagecreatefromgif($uploadedfile);
}

echo $scr;

list($width,$height)=getimagesize($uploadedfile);
$tmp=imagecreatetruecolor($width,$height);

if (isset($resize))
{
  if ($resize == "categories" || $resize == "products")
  {
  $resolution475 = "237";
  $resolution768 = "384";
  $resolution1920 = "451";
  }
}

$newwidth475=$resolution475;
$newheight475=($height/$width)*$newwidth475;
$tmp475=imagecreatetruecolor($newwidth475,$newheight475);
imagecopyresampled($tmp475,$src,0,0,0,0,$newwidth475,$newheight475,$width,$height);

$newwidth768=$resolution768;
$newheight768=($height/$width)*$newwidth768;
$tmp768=imagecreatetruecolor($newwidth768,$newheight768);
imagecopyresampled($tmp768,$src,0,0,0,0,$newwidth768,$newheight768,$width,$height);

$newwidth1920=$resolution1920;
$newheight1920=($height/$width)*$newwidth1920;
$tmp1920=imagecreatetruecolor($newwidth1920,$newheight1920);
imagecopyresampled($tmp1920,$src,0,0,0,0,$newwidth1920,$newheight1920,$width,$height);

imagecopyresampled($tmp,$src,0,0,0,0,$width,$height,$width,$height);

$pic=($_FILES['image']['name']);
srand(time());
$random = (rand()%99999999);
$newname="$random"."$pic";
    
$ext = pathinfo($newname, PATHINFO_EXTENSION);
$filename = pathinfo($newname, PATHINFO_FILENAME);

$newname475 = $filename . "-475" . $ext;
$newname768 = $filename . "-768" . $ext;
$newname1920 = $filename . "-1920" . $ext;
    
$filename475 = "images/pages/". $newname475;
$filename768 = "images/pages/". $newname768;
$filename1920 = "images/pages/". $newname1920;
imagejpeg($tmp475,$filename475,100);
imagejpeg($tmp768,$filename768,100);
imagejpeg($tmp1920,$filename1920,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp475);
imagedestroy($tmp768);
imagedestroy($tmp=1920);
}}
}

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

Posted: Tue Mar 07, 2017 6:40 am
by Celauran
Explain to me in words what you're trying to accomplish. I'm seeing a fair bit of duplication in that code you posted, you've got resolution variables that aren't always defined, etc. Looks like the short of it is you want to upload an image, give it a random name, and resize it to three specific sizes. Is that about right? Anything else? Any errors you're getting?

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

Posted: Tue Mar 07, 2017 6:55 am
by simonmlewis
Admin uploads image banner.jpg.
A random set of digits are added at the front to make it unique.
The original image remains the same as is uploaded to images/pages/.
That image is then resized based on the value of $resize. As some are two across (50/50) and some are four across.

But each are for a 475/768/1920 resolution screen.

As it is resized it is then renamed: banner-475.jpg. banner-768.jpg. banner-1920.jpg.
It is stored in the same place as the original.

Then on the consumer page it will use srcset and PHP to establish these filenames, from the original banner.jpg.

Not run this script yet, but thought I would show it here so you can see what I am trying to make happen, based on our original image resizing code.

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

Posted: Tue Mar 07, 2017 7:00 am
by Celauran
I just tried to run what you posted after adding a simple upload form to it. You've got undefined variables being passed into your resize functions which results in errors being thrown all over the place.

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

Posted: Tue Mar 07, 2017 7:11 am
by simonmlewis
Yes. It needs a hidden field named resize. That will be for categories or products.
Plus of course the image itself.

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

Posted: Tue Mar 07, 2017 7:13 am
by Celauran
You should probably add a fallback for when that's not provided, or some sort of early return rather than allowing errors.

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

Posted: Tue Mar 07, 2017 7:21 am
by simonmlewis
Its' used by admin only, so it will always have those elements passed over.
But do you see where I am going with it? Do I have the main part of it about right?

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

Posted: Tue Mar 07, 2017 7:35 am
by simonmlewis
It's just processing the image resizing at all. It uploads the original, but not the others.
I don't even get an error message, which is a bit strange.

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

Posted: Tue Mar 07, 2017 7:39 am
by Celauran
I threw this together fairly quickly, so it's a bit crude and may not be 100%, but it appears to accomplish what you're after.

Code: Select all

<?php

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['image']) && $_FILES['image']['error'] === 0) {
    $target_directory = __DIR__ . '/images/pages';
    $pathinfo = pathinfo($_FILES['image']['name']);
    $prefix = (rand() % 99999999);

    // Open the uploaded image with the Imagine library
    $image = $imagine->open($_FILES['image']['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 = "{$prefix}_{$pathinfo['filename']}{$key}.{$pathinfo['extension']}";
        $image->resize($scaled_box)->save($target_directory . '/' . $new_filename);
    }
}

?>

<!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="image">
            <button>Submit</button>
        </form>
    </body>
</html>