PDA

View Full Version : PHP Image upload and resize.


tux
10-21-2009, 05:49 PM
Hi all,

I am working on a script to upload an image and resize it twice to create a main image, a thumbnail and a smaller thumbnail all from one upload.

The script is below and runs okay giving the success message but the files do not show up in the folders as you would expect.

I cant for the life of me see where I have gone wrong. Hope one of you can see why.

<?php
///////////////////////////////////////////
function getExtension($str) {

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

$errors=0;

if($_SERVER["REQUEST_METHOD"] == "POST")
{
$image = $_FILES["file"]["name"];
$uploadedfile = $_FILES['file']['tmp_name'];

if ($image)
{
$filename = stripslashes($_FILES['file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
echo ' Unknown Image extension! ';
$errors = 1;
}
else
{
$size=filesize($_FILES['file']['tmp_name']);

if ($size > MAX_SIZE*1024)
{
echo "You have exceeded the size limit";
$errors = 1;
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
//resize image and create thumbs and small thumbs
list($width,$height)=getimagesize($uploadedfile);

$newwidth=300;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);

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

$newwidth1=50;
$newheight2=($height/$width)*$newwidth2;
$tmp2=imagecreatetruecolor($newwidth2,$newheight2) ;

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$ne wheight,
$width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$ newheight1,
$width,$height);

imagecopyresampled($tmp2,$src,0,0,0,0,$newwidth2,$ newheight2,
$width,$height);
//declare destinations
$filename = "Images/Gallery/Test/". $_FILES['file']['name'];
$filename1 = "Images/Gallery/Test/Test_Thumbs". $_FILES['file']['name'];
$filename2 = "Images/Gallery/Test_Thumbs/Small/". $_FILES['file']['name'];
//write files to folders
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
imagejpeg($tmp2,$filename1,100);
//destroy temps to save memory
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
imagedestroy($tmp2);
}
}
}
//If no errors registered, print the success message
if(isset($_POST['Submit']) && !$errors)
{
echo "Image Uploaded Successfully!";
}
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<form name="upload" enctype="multipart/form-data" method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
<input type="file" name="image" id="image" >
<input type="submit" name="Submit" id="Submit" value="Upload Image">
</form>
</body>
</html>

Thanks, Paul

edbr
10-22-2009, 02:31 AM
is this intentional?
$newwidth1=100;
+$newwidth1=50; maybe should be$newwidth2=50;
as for the destination folders ??? can only say check paths but im sure you hve

tux
10-22-2009, 08:13 PM
Thanks for that edbr,

Sometimes you can look and look and not see the obvious. lol

For anyone that may be interested here is the corrected and updated code.

<?php
// function to get file extension
function getExtension($str) {

$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// define max file size, change to suit your own maximum file size
define ("MAX_SIZE","1000");
$errors=0;
//get the original file from form
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$image = $_FILES["file"]["name"];// from your upload form
$uploadedfile = $_FILES['file']['tmp_name'];// from your upload form
// check for correct file extension
if ($image)
{
$filename = stripslashes($_FILES['file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
echo ' Unknown Image extension! ';// build your own error handling here
$errors = 1;
}
// check for correct file size
else
{
$size=filesize($_FILES['file']['tmp_name']);

if ($size > MAX_SIZE*1024)
{
echo "You have exceeded the size limit";// build your own error handling here
$errors = 1;
}
// check which extension we have and create file
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
//resize image and create thumbs and small thumbs
list($width,$height)=getimagesize($uploadedfile);
//for main images, this keeps the width at 300px regardless of portrait or landscape
$newwidth=300;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
//for thumbnails, change the $newwidth variable to what ever size you need
if($width > $height){//landscape
$newwidth1=100;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1) ;
}elseif($width < $height){//portrait
$newheight1=100;
$newwidth1=($width/$height)*$newheight1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1) ;
}
//for smaller thumbnails, my site required this smaller thumb. Delete this section if you dont need it
if($width > $height){//landscape
$newwidth2=50;
$newheight2=($height/$width)*$newwidth2;
$tmp2=imagecreatetruecolor($newwidth2,$newheight2) ;
}elseif($width < $height){//portrait
$newheight2=50;
$newwidth2=($width/$height)*$newheight2;
$tmp2=imagecreatetruecolor($newwidth2,$newheight2) ;
}
// create new resized files
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$ne wheight,$width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$ newheight1,$width,$height);

imagecopyresampled($tmp2,$src,0,0,0,0,$newwidth2,$ newheight2,$width,$height);
//declare destinations
$filename = "Images/Gallery/Test/". $_FILES['file']['name']; //
$filename1 = "Images/Gallery/Test/Test_Thumbs/". $_FILES['file']['name']; // your destination paths here
$filename2 = "Images/Gallery/Test/Test_Thumbs/Small/". $_FILES['file']['name']; //
//write files to folders
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
imagejpeg($tmp2,$filename2,100);
//destroy temps to save memory
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
imagedestroy($tmp2);
}
}
}
//If no errors registered, print the success message
if(isset($_POST['Submit']) && !$errors)
{
echo "Image Uploaded Successfully!";
}
?>

..and the form.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Upload Image Files and Resize</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<form name="upload" enctype="multipart/form-data" method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
<input type="file" name="file" id="file" >
<input type="submit" name="Submit" id="Submit" value="Upload Image">
</form>
</body>
</html>

Hope this helps someone, regards,

Paul

edbr
10-23-2009, 01:55 AM
i hate to think of the time ive wasted because of missing semi colons etc , just fresh eyes mate

kasiarakos
09-08-2010, 09:31 AM
hello I took exactly the code step by step but when i paste this

//get the original file from form
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$image = $_FILES["file"]["name"];// from your upload form
$uploadedfile = $_FILES['file']['tmp_name'];// from your upload form

it seems like I have an error in first line of form what do you thin it's the problem?

davidj
09-08-2010, 09:35 AM
paste the whole script

kasiarakos
09-08-2010, 09:58 AM
sorry it works perfect my wrong.... do you know someone else tutorial to figure the images from the database to browser?

kasiarakos
09-08-2010, 11:55 AM
sorry it works perfect my wrong.... do you know someone else tutorial to figure the images from the database to browser?

how you can change the name of images wich are saved to the folder?

DougJoseph
10-12-2010, 06:06 PM
Paul (Tux):

That script is EXACTLY what I needed and it is working flawlessly. THANK YOU!

-Doug J.

tux
10-12-2010, 07:00 PM
You're welcome Doug and welcome to the forum.

DougJoseph
10-12-2010, 07:04 PM
You're welcome Doug and welcome to the forum.

You saved me a lot of time! I hope to pass it forward or return the favor sometime.

DougJoseph
10-13-2010, 04:07 AM
Paul,

The image upload is awesome!

I need to set up for uploading PDFs too.

Do you have any quick tips that could speed my search on the best way to get it done?

-Doug

edbr
10-13-2010, 04:29 AM
play around with this. define your folder

<form action="<?php print $PHP_SELF?>" enctype="multipart/form-data" method="post">
Last name:<br /> <input type="text" name="name" value="" /><br />
class notes:<br /> <input type="file" name="pdf" value="" /><br />
<input type="submit" name="submit" value="Submit Notes" />
</form>

<?php
define ("filesplace","./");

if (is_uploaded_file($_FILES['pdf']['tmp_name'])) {

if ($_FILES['pdf']['type'] != "application/pdf") {
echo "<p>Files must be uploaded in PDF format.</p>";
} else {
$name = $_POST['name'];
$result = move_uploaded_file($_FILES['pdf']['tmp_name'], filesplace."/$name.pdf");
if ($result == 1) echo "<p>Upload done .</p>";
else echo "<p>Sorry, errorwhile uploading . </p>";
} #endIF
} #endIF

DougJoseph
10-13-2010, 04:46 AM
Thanks! Will give it a go.

DougJoseph
10-16-2010, 08:59 AM
Thanks for the script! Saved me a lot of time! I hope to return the favor or help someone else in the future.

honda-mini
05-25-2013, 03:32 PM
hi there, i'm fairly new to this, but im looking to use this code to upload files and resize to build a thumbnail gallery... is there any way to add the url to a database automatically so i can reference it in a page to show the image.. or am i going about it all the wrong way lol

thanks in advance

edbr
05-27-2013, 03:17 AM
no it is normal; process to insert the image path into a database