Resize image

Hi:

I have this php script to upload the images and the data to MySQL database and display the images and data.  The problem I am having is when a large image is uploaded then the webpage looks ugly.  Is there a way to resize any image to a fixed size during display?  

Also, can we restrict the maximum size of image file uploaded?
<!-- Form to upload image -->
<form enctype="multipart/form-data" action="add.php" method="POST"> 
Name: <input type="text" name="name"><br> 
Description: <input type="text" name="description"><br> 
ISBN: <input type="text" name="isbn"><br> 
Photo: <input type="file" name="photo"><br> 
<input type="submit" value="Add"></form><hr>



<?php
// add.php
// Connects to your Database 
$dbh=mysql_connect("mysql.server.com", "dbuser", "dbpass") or die(mysql_error()) ; 
mysql_select_db("books") or die(mysql_error()) ; 

if($_POST) {
  //This is the directory where images will be saved 
  $target = "images/";
  $target = $target . basename( $_FILES['photo']['name']); 
 
  //This gets all the other information from the form 
  $name=$_POST['name']; 
  $description=$_POST['description']; 
  $isbn=$_POST['isbn']; 
  $pic=$_FILES['photo']['name']; 
 
  //Writes the information to the database 
  mysql_query("INSERT INTO booklist (id,name,description,isbn,image)  VALUES ('$id', '$name', '$description', '$isbn', '$pic')") ; 
 
  //Writes the photo to the server 
  if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) { 
    //Tells you if its all ok 
    //echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory<br><br>"; 
    header("location:list.php");
    exit();
  } else { 
    //Gives and error if its not 
    echo "Sorry, there was a problem uploading your file.<br><br>"; 
  } 
}



// close the database connection
mysql_close($dbh)
?>

//Display the image and the data
<?php
// list.php

// Connects to your Database 
$dbh=mysql_connect("mysql.server.com", "dbuser", "dbpass") or die(mysql_error()) ; 
mysql_select_db("books") or die(mysql_error()) ; 

//Retrieves data from MySQL 
$data = mysql_query("SELECT * FROM booklist") or die(mysql_error());  //Puts it into an array 
while($info = mysql_fetch_array( $data )) { 
  //Outputs the image and other data
  echo "<img src=images/". $info['image'] ."> <br>"; 
  echo "<b>Name:</b> ". $info['name'] ."<br>"; 
  echo "<b>Description:</b> ". $info['description']. " <br>";
  echo "<b>ISBN:</b> ". $info['isbn']. " <br><br>";
}

// close the database connection
mysql_close($dbh)

?> 

Toggle HighlightingOpen in New WindowSelect All

Open in new window

LVL 1
adamssapAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

adamssapAuthor Commented:

Thanks, I will take a look are the link provide. But, I am not an expert in php as you are.  I need some finger holding with my code.
0
GreggCommented:
ha! I too am not an expert, i've done the same in VB but not in php. I was hoping that was exactly what you needed. I believe it looks like it checks for correct things:

it validates file type (jpg, png, etc)
it checks for file size limit
it resizes as you specify

0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

adamssapAuthor Commented:
If I can make it work on my website, I would appreciate your help.
0
DerokorianCommented:
change:

  echo "<img src=images/". $info['image'] ."> <br>";

to

  echo "<img src=images/". $info['image'] ." style="max-width:500px;max-height:200px"> <br>";

The max-width/max-height are the key, however I don't know what max sizes you need, so I just stuck 500px and 200px, respectively, in there.
0
adamssapAuthor Commented:
Hi Derokorian:

I got this error:

Parse error: syntax error, unexpected T_STRING, expecting ',' or ';'
0
DerokorianCommented:
Oh ha, my bad I didn't look at what I wrote closely enough and forgot to escape the quotes, try this instead:

  echo "<img src=images/". $info['image'] ." style=\"max-width:500px;max-height:200px\"> <br>";
0
adamssapAuthor Commented:
That works like a charm, Derokorian.

Can we display a fixed width and height for the image during display? If the image is small, the size is increased and vice versa.
0
GreggCommented:
im so glad Derokorian helped you get it working. I should not have posted since php isnt in my limited skill set. Sorry!
0
adamssapAuthor Commented:
No problem greegg_s
0
DerokorianCommented:
To get images to display the same size (whether larger than original or small) and maintain aspect ratio will require some logic, however you could set just width (instead of max-width) to a fixed value and it will scale everything to have the same width. However this may look bad if some pictures are portrait and some are landscape. If you aren't worried about maintaining the aspect ratio you can set both the width and height to fixed values.

Can you please tell me a little more about what you are looking for in response to this information and I will try to help you if needed.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
adamssapAuthor Commented:
Thanks, Derokorian.  I will always have portrait images, so if I use width and height instaed of max-width or height that may work for me.  Can can you please help me in restricting the size of the image file being uploaded in the upload form code?
0
Lukasz ChmielewskiCommented:
<?php
// add.php
// Connects to your Database 
$dbh=mysql_connect("", "", "") or die(mysql_error()) ; 
mysql_select_db("books") or die(mysql_error()) ; 

$maxsize = 50000;

if($_POST) {
  //This is the directory where images will be saved 
  $target = "images/";
  $target = $target . basename( $_FILES['photo']['name']); 

  $photosize = $_FILES['photo']['size']; 
  if($photosize > $maxsize){
    echo "Sorry, file size exceeds the limit.<br><br>"; 
    exit();
  }
 
  //This gets all the other information from the form 
  $name=$_POST['name']; 
  $description=$_POST['description']; 
  $isbn=$_POST['isbn']; 
  $pic=$_FILES['photo']['name']; 
 
  //Writes the information to the database 
  mysql_query("INSERT INTO booklist (name,description,isbn,image)  VALUES ('$name', '$description', '$isbn', '$pic')") ; 
 
  //Writes the photo to the server 
  if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) { 
    //Tells you if its all ok 
    //echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory<br><br>"; 
    header("location:list.php");
    exit();
  } else { 
    //Gives and error if its not 
    echo "Sorry, there was a problem uploading your file.<br><br>"; 
  } 
}



// close the database connection
mysql_close($dbh)
?>

Open in new window



this is add.php - fill your connection data.
0
Lukasz ChmielewskiCommented:
The $maxsize variable sets the limit to 50 kB.
0
Ray PaseurCommented:
Image uploads and resizing are really two different things, even if we think of them together.  This script is rather old, and the tests about GD2 may not be needed anymore (everyone has it by now) so you may want to consider removing that part.  You might also want to remove the explicit slash characters and substitute the PHP constant DIRECTORY_SEPARATOR.

You can install this on your server and run it to see the moving parts.  

Best regards, ~Ray
<?php // RAY_upload_and_resize_image.php
date_default_timezone_set('America/Chicago');


// UPLOAD AN IMAGE AND RESIZE IT TO FIT A PREDEFINED SIZE


// A FUNCTION TO DETERMINE IF GD IS AT LEVEL 2 OR MORE
function get_gd_info($display=FALSE)
{

    // IS GD INSTALLED AT ALL?
    if (!function_exists("gd_info"))
    {
        if ($display) echo "<br/>GD NOT INSTALLED\n";
        return FALSE;
    }

    // IF GD IS INSTALLED GET DETAILS
    $gd = gd_info();

    // IF DISPLAY IS REQUESTED, PRINT DETAILS
    if ($display)
    {
        echo "<br/>GD DETAILS:\n";
        foreach ($gd as $key => $value)
        {
            if ($value === TRUE)  $value = 'YES';
            if ($value === FALSE) $value = 'NO';
            echo "<br/>$key = $value \n";
        }
    }

    // RETURN THE VERSION NUMBER
    $gd_version = preg_replace('/[^0-9\.]/', '', $gd["GD Version"]);
    return $gd_version;
}


// A FUNCTION TO MAKE AN IMAGE INTO THE RIGHT WIDTH FOR PAGE DISPLAY
// WILL WORK IF GD2 NOT INSTALLED, BUT WILL MAKE BETTER IMAGES WITH GD2
// INPUT IS THE IMAGE FILE NAME, OUTPUT IS AN IMAGE RESOURCE, OR FALSE IF NO RESIZE NEEDED
function create_right_size_image($image, $width=720)
{
    // IS GD HERE?
    $gdv = get_gd_info();
    if (!$gdv) return FALSE;

    // GET AN IMAGE THING
    $source = imagecreatefromjpeg("$image");

    // GET THE X AND Y DIMENSIONS
    $imageX = imagesx($source);
    $imageY = imagesy($source);

    // IF NO RESIZING IS NEEDED
    if ($imageX <= $width)
    {
        return FALSE;
    }

    // THE WIDTH IS TOO GREAT - MUST RESIZE
    $tnailX = $width;
    $tnailY = (int) (($tnailX * $imageY) / $imageX );

    // WHICH FUNCTIONS CAN RESIZE / RESAMPLE THE IMAGE?
    if ($gdv >= 2)
    {
        // IF GD IS AT LEVEL 2 OR ABOVE
        $target = imagecreatetruecolor($tnailX, $tnailY);
        imagecopyresampled ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
    } else
    {
        // IF GD IS AT A LOWER REVISION LEVEL
       $target = imagecreate($tnailX, $tnailY);
       imagecopyresized   ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
    }
    return $target ;
}
/* ********************************************************************************************* */


// ESTABLISH THE NAME OF THE PHOTOS DIRECTORY
$photos    = 'RAY_junk';

// ESTABLISH THE LARGEST FILE WE WILL UPLOAD
$max_file_size = '5000000'; // A BIT MORE THAN 4MB

// THIS IS A LIST OF THE POSSIBLE ERRORS THAT CAN BE REPORTED in $_FILES[]["error"]
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;

// IF THERE IS NOTHING USEFUL IN $_POST, PUT UP THE FORM FOR INPUT
if ( (empty($_POST['p'])) && (empty($_POST['MAX_FILE_SIZE'])) ) {
    ?>
    <h2>Upload Photos</h2>

    <!-- NOTE THE USE OF ENCTYPE -->
    <form name="UploadForm" enctype="multipart/form-data" action="<?=$_SERVER["REQUEST_URI"]?>" method="POST">
    <input type="hidden" name="p" value="1" />
    <!-- MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD -->
    <input type="hidden" name="MAX_FILE_SIZE" value="<?=$max_file_size?>" />
    <!-- INPUT NAME= IN TYPE=FILE DETERMINES THE NAME FOR ACTION SCRIPT TO USE IN $_FILES ARRAY -->
    <p>
    Find the photo you want to upload and click the "Upload" button below.
    </p>

    <table cellpadding="1" cellspacing="1" border="0">
    <tr><td align="right"><span class="required">Photo: </span></td> <td><input name="userfile" type="file" size="80" /></td></tr>
    <tr><td> </td><td><input type="submit" name="_submit" value="Upload" />
    &nbsp; &nbsp; Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> an existing photo.</td></tr>
    </table>
    </form>

    <?php die();

}

// THERE IS POST DATA - PROCESS IT
else
{
    echo "<h2>Results: Upload Photos</h2>\n";
    echo "<p>\n";

    // SYNTHESIZE THE NEW FILE NAME
    $f_type  = trim(strtolower(end    (explode( '.', basename($_FILES['userfile']['name'] )))));
    $f_name  = trim(strtolower(current(explode( '.', basename($_FILES['userfile']['name'] )))));
    $my_new  = getcwd() . '/' . $photos . '/' . $f_name . '.' . $f_type;
    $my_file = $photos  . '/' . $f_name . '.' . $f_type;

    // TEST FOR ALLOWABLE EXTENSIONS (ADD OTHERS AS NEEDED)
    if ($f_type != 'jpg')
    {
        die('Sorry, only JPG files allowed');
    }

    // IF THERE ARE ERRORS
    $error_code    = $_FILES["userfile"]["error"];
    if ($error_code != 0)
    {
        $error_message = $errors[$error_code];
        echo "<p class=\"required\">Upload Error Code: $error_code: $error_message</p>\n";
        die('Sorry');
    }

    // MOVE THE FILE INTO THE DIRECTORY
    $overwrite    = $_POST['overwrite'];
    $file_size    = number_format($_FILES["userfile"]["size"]);

    // IF THE FILE IS NEW
    if (!file_exists($my_new))
    {
        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_new))
        {
            $upload_success = 1;
        }
        else
        {
            $upload_success = -1;
        }
    }
    // IF THE FILE ALREADY EXISTS
    else
    {
        echo "<b><i>$my_file</i></b> already exists.\n";

        // SHOULD WE OVERWRITE THE FILE? IF NOT
        if (empty($overwrite))
        {
            $upload_success = 0;
        }
        // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
        else
        {
            $now    = date('Y-m-d');
            $my_bak = $my_new . '.' . $now . '.bak';
            if (!copy($my_new, $my_bak))
            {
                echo "<b>Attempted Backup Failed!</b>\n";
            }
            if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_new))
            {
                $upload_success = 2;
            }
            else
            {
                $upload_success = -1;
            }
        }
    }

    // REPORT OUR SUCCESS OR FAILURE
    if ($upload_success == 2) { echo "It has been overwritten.\n"; }
    if ($upload_success == 1) { echo "<b><i>$my_file</i></b> has been saved.\n"; }
    if ($upload_success == 0) { echo "<b>It was NOT overwritten.</b>\n"; }

    if ($upload_success > 0)
    {
        echo "$file_size bytes uploaded.\n";
        chmod ($my_new, 0755);
    }

    echo "</p>\n";

    // RESIZE THE FILE TO FIT DESIGNATED WIDTH, IF NECESSARY
    if ($upload_success > 0)
    {
        if ($imageblob = create_right_size_image($my_new))
        {
            imagejpeg($imageblob, $my_new);
        }
    }

    echo "<p><a href=\"$my_file\">See the file</a></p>\n";
}

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.