PHP Developers Network

A community of PHP developers offering assistance, advice, discussion, and friendship.
 
Loading
It is currently Sun Mar 26, 2017 7:47 pm

All times are UTC - 5 hours




Post new topic Reply to topic  [ 544 posts ]  Go to page 1, 2, 3, 4, 5 ... 37  Next
Author Message
PostPosted: Tue Mar 07, 2017 4:35 am 
Offline
DevNet Master

Joined: Wed Oct 08, 2008 3:39 pm
Posts: 4143
Location: United Kingdom
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:

Syntax: [ Download ] [ Hide ]
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.

_________________
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.


Top
 Profile  
 
PostPosted: Tue Mar 07, 2017 6:21 am 
Offline
Moderator
User avatar

Joined: Tue Nov 09, 2010 3:39 pm
Posts: 6192
Location: Montreal, Canada
Take a look at the Imagine library.

_________________
Supported PHP versions No longer supported versions


Top
 Profile  
 
PostPosted: Tue Mar 07, 2017 6:29 am 
Offline
DevNet Master

Joined: Wed Oct 08, 2008 3:39 pm
Posts: 4143
Location: United Kingdom
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.

_________________
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.


Top
 Profile  
 
PostPosted: Tue Mar 07, 2017 6:31 am 
Offline
Moderator
User avatar

Joined: Tue Nov 09, 2010 3:39 pm
Posts: 6192
Location: Montreal, Canada
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.

_________________
Supported PHP versions No longer supported versions


Top
 Profile  
 
PostPosted: Tue Mar 07, 2017 6:37 am 
Offline
DevNet Master

Joined: Wed Oct 08, 2008 3:39 pm
Posts: 4143
Location: United Kingdom
I am not familiar with Composer. I'm just familiar with adding scripts to a page.

_________________
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.


Top
 Profile  
 
PostPosted: Tue Mar 07, 2017 6:40 am 
Offline
Moderator
User avatar

Joined: Tue Nov 09, 2010 3:39 pm
Posts: 6192
Location: Montreal, Canada
You really ought to familiarise yourself with it. Fortunately, it's also quite easy to use. https://getcomposer.org/

_________________
Supported PHP versions No longer supported versions


Top
 Profile  
 
PostPosted: Tue Mar 07, 2017 7:25 am 
Offline
DevNet Master

Joined: Wed Oct 08, 2008 3:39 pm
Posts: 4143
Location: United Kingdom
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.
Syntax: [ Download ] [ Hide ]
   $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);
}}
}

_________________
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.


Top
 Profile  
 
PostPosted: Tue Mar 07, 2017 7:40 am 
Offline
Moderator
User avatar

Joined: Tue Nov 09, 2010 3:39 pm
Posts: 6192
Location: Montreal, Canada
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?

_________________
Supported PHP versions No longer supported versions


Top
 Profile  
 
PostPosted: Tue Mar 07, 2017 7:55 am 
Offline
DevNet Master

Joined: Wed Oct 08, 2008 3:39 pm
Posts: 4143
Location: United Kingdom
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.

_________________
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.


Top
 Profile  
 
PostPosted: Tue Mar 07, 2017 8:00 am 
Offline
Moderator
User avatar

Joined: Tue Nov 09, 2010 3:39 pm
Posts: 6192
Location: Montreal, Canada
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.

_________________
Supported PHP versions No longer supported versions


Top
 Profile  
 
PostPosted: Tue Mar 07, 2017 8:11 am 
Offline
DevNet Master

Joined: Wed Oct 08, 2008 3:39 pm
Posts: 4143
Location: United Kingdom
Yes. It needs a hidden field named resize. That will be for categories or products.
Plus of course the image itself.

_________________
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.


Top
 Profile  
 
PostPosted: Tue Mar 07, 2017 8:13 am 
Offline
Moderator
User avatar

Joined: Tue Nov 09, 2010 3:39 pm
Posts: 6192
Location: Montreal, Canada
You should probably add a fallback for when that's not provided, or some sort of early return rather than allowing errors.

_________________
Supported PHP versions No longer supported versions


Top
 Profile  
 
PostPosted: Tue Mar 07, 2017 8:21 am 
Offline
DevNet Master

Joined: Wed Oct 08, 2008 3:39 pm
Posts: 4143
Location: United Kingdom
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?

_________________
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.


Top
 Profile  
 
PostPosted: Tue Mar 07, 2017 8:35 am 
Offline
DevNet Master

Joined: Wed Oct 08, 2008 3:39 pm
Posts: 4143
Location: United Kingdom
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.

_________________
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.


Top
 Profile  
 
PostPosted: Tue Mar 07, 2017 8:39 am 
Offline
Moderator
User avatar

Joined: Tue Nov 09, 2010 3:39 pm
Posts: 6192
Location: Montreal, Canada
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.

Syntax: [ Download ] [ Hide ]
<?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>
 

_________________
Supported PHP versions No longer supported versions


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 544 posts ]  Go to page 1, 2, 3, 4, 5 ... 37  Next

All times are UTC - 5 hours


Who is online

Users browsing this forum: Bing [Bot], Exabot [Bot] and 5 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
Powered by phpBB® Forum Software © phpBB Group