Solved

Image Upload using the gd library and PHP

Posted on 2008-06-09
5
2,124 Views
Last Modified: 2013-12-13
Dear all,

An ever increasing headache has ended with a cry and a desperate need for help from you guy's!! I need help with an upload and resize feature within my site.

I have provided all the relevant code below. At the moment the code resizes an image on upload and places each image in a specified folder. however, at the moment only the thumbnail gets resized - can someone show me how to make the original image a different size too please???

This would be a great help, thank you!
require_once('Connections/connBookShop.php');
 

if (!function_exists("GetSQLValueString")) {

function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 

{

  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
 

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
 

  switch ($theType) {

    case "text":

      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";

      break;    

    case "long":

    case "int":

      $theValue = ($theValue != "") ? intval($theValue) : "NULL";

      break;

    case "double":

      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";

      break;

    case "date":

      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";

      break;

    case "defined":

      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;

      break;

  }

  return $theValue;

}

}
 

// Maximum file size

define ("max_size","500");
 

// Large image size

define ("width","245");

define ("height","300");
 

// Thumnail image size

define ("width_tn","96");

define ("height_tn","96");
 

// this is the function that will create the thumbnail image from the uploaded image

// the resize will be done considering the width and height defined, but without deforming the image

function make_thumb($img_name,$filename,$new_w,$new_h)

{

	//get image extension.

		$ext=getExtension($img_name);

	//creates the new image using the appropriate function from gd library

		if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))

			$src_img=imagecreatefromjpeg($img_name);

		if(!strcmp("png",$ext))

			$src_img=imagecreatefrompng($img_name);

	//gets the dimmensions

			$old_x=imageSX($src_img);

			$old_y=imageSY($src_img);

	// next we will calculate the new dimmensions for the thumbnail image

			$ratio1=$old_x/$new_w;

			$ratio2=$old_y/$new_h;

		if($ratio1>$ratio2) {

			$thumb_w=$new_w;

			$thumb_h=$old_y/$ratio1;

		}

		else {

			$thumb_h=$new_h;

			$thumb_w=$old_x/$ratio2;

}

// we create a new image with the new dimmensions

$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);

// resize the big image to the new created one

imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

// output the created image to the file. Now we will have the thumbnail into the file named by $filename

if(!strcmp("png",$ext))

imagepng($dst_img,$filename);

else

imagejpeg($dst_img,$filename);

//destroys source and destination images.

imagedestroy($dst_img);

imagedestroy($src_img);

}

// This function reads the extension of the file.

// It is used to determine if the file is an image by checking the extension.

function getExtension($str) {

$i = strrpos($str,".");

if (!$i) { return ""; }

$l = strlen($str) - $i;

$ext = substr($str,$i+1,$l);

return $ext;

}
 
 

//Here follows the php code to process post data.

//The code contains image extension and size verification as well as uploading and resizing image.

// This variable is used as a flag. The value is initialized with 0 (meaning no error found)

//and it will be changed to 1 if an error occures. If the error occures the file will not be uploaded.

$errors=0;
 

// checks if the form has been submitted

if(isset($_POST['Submit']))

{

//reads the name of the file the user submitted for uploading

$image=$_FILES['image']['name'];

// if it is not empty

if ($image)

{

// get the original name of the file from the clients machine

$filename = stripslashes($_FILES['image']['name']);

// get the extension of the file in a lower case format

$extension = getExtension($filename);

$extension = strtolower($extension);

// if it is not a known extension, we will suppose it is an error, print an error message

//and will not upload the file, otherwise we continue

if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png"))

{

echo '<h1>Unknown extension!</h1>';

$errors=1;

}

else

{

// get the size of the image in bytes

// $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which

//the uploaded file was stored on the server

$size=getimagesize($_FILES['image']['tmp_name']);

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

//compare the size with the maxim size we defined and print error if bigger

if ($sizekb > max_size*1024)

{

echo '<h1>You have exceeded the size limit!</h1>';

$errors=1;

}

//we will give an unique name, for example the time in unix time format

$image_name=time().'.'.$extension;

//the new name will be containing the full path where will be stored (images folder)

$newname="assets/images/book_cover/large/".$image_name;

$copied = copy($_FILES['image']['tmp_name'], $newname);

//we verify if the image has been uploaded, and print error instead

if (!$copied)

{

echo '<h1>Copy unsuccessfull!</h1>';

$errors=1;

}

else

{

// the new thumbnail image will be placed in images/thumbs/ folder

$thumb_name='assets/images/book_cover/'.$image_name;

// call the function that will create the thumbnail. The function will get as parameters

//the image name, the thumbnail name and the width and height desired for the thumbnail

$thumb=make_thumb($newname,$thumb_name,width_tn,height_tn);

}} }}

//If no errors registred, print the success message and show the thumbnail image created

if(isset($_POST['Submit']) && !$errors)

{

echo "<h1>Thumbnail created Successfully!</h1>";

echo '<img src="'.$thumb_name.'">';

}
 
 

// Insert into database

$editFormAction = $_SERVER['PHP_SELF'];

if (isset($_SERVER['QUERY_STRING'])) {

  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);

}
 

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "uploadForm")) {

 $insertSQL = sprintf("INSERT INTO items (ItemName, ItemLongDesc, ItemPrice, ItemThumb, ItemImage, ItemQnty) VALUES (%s, %s, %s, %s, %s, %s)",

                     GetSQLValueString($_POST['itemName'], "text"),

                     GetSQLValueString($_POST['itemDesc'], "text"),

                     GetSQLValueString($_POST['itemPrice'], "double"),

                     GetSQLValueString($image_name, "text"),

                     GetSQLValueString($image_name, "text"),

                     GetSQLValueString($_POST['itemQnty'], "int"));
 

  mysql_select_db($database_connBookShop, $connBookShop);

  $Result1 = mysql_query($insertSQL, $connBookShop) or die(mysql_error());

}

Open in new window

0
Comment
Question by:wilson1000
  • 3
  • 2
5 Comments
 
LVL 48

Expert Comment

by:hernst42
ID: 21746124
If you want to make a larger "thumbnail" for the original you can replace the line
            $copied = copy($_FILES['image']['tmp_name'], $newname);
with
     make_thumb($newname, $_FILES['image']['tmp_name'], width, height);
     $copied =true;
0
 
LVL 4

Author Comment

by:wilson1000
ID: 21746452
Thanks for your reply however, after implementing your suggestion I have been left with all these warnings and no upload :

Warning: imagecreatefromjpeg(assets/images/book_cover/large/1213043443.jpg) [function.imagecreatefromjpeg]: failed to open stream: No such file or directory in C:\Inetpub\BookShop_Antique\upload.php on line 52

Warning: imagesx(): supplied argument is not a valid Image resource in C:\Inetpub\BookShop_Antique\upload.php on line 56

Warning: imagesy(): supplied argument is not a valid Image resource in C:\Inetpub\BookShop_Antique\upload.php on line 57

Warning: Division by zero in C:\Inetpub\BookShop_Antique\upload.php on line 67

Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in C:\Inetpub\BookShop_Antique\upload.php on line 70

Warning: imagecopyresampled(): supplied argument is not a valid Image resource in C:\Inetpub\BookShop_Antique\upload.php on line 72

Warning: imagejpeg(): supplied argument is not a valid Image resource in C:\Inetpub\BookShop_Antique\upload.php on line 77

Warning: imagedestroy(): supplied argument is not a valid Image resource in C:\Inetpub\BookShop_Antique\upload.php on line 79

Warning: imagedestroy(): supplied argument is not a valid Image resource in C:\Inetpub\BookShop_Antique\upload.php on line 80

Warning: imagecreatefromjpeg(assets/images/book_cover/large/1213043443.jpg) [function.imagecreatefromjpeg]: failed to open stream: No such file or directory in C:\Inetpub\BookShop_Antique\upload.php on line 52

Warning: imagesx(): supplied argument is not a valid Image resource in C:\Inetpub\BookShop_Antique\upload.php on line 56

Warning: imagesy(): supplied argument is not a valid Image resource in C:\Inetpub\BookShop_Antique\upload.php on line 57

Warning: Division by zero in C:\Inetpub\BookShop_Antique\upload.php on line 67

Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in C:\Inetpub\BookShop_Antique\upload.php on line 70

Warning: imagecopyresampled(): supplied argument is not a valid Image resource in C:\Inetpub\BookShop_Antique\upload.php on line 72

Warning: imagejpeg(): supplied argument is not a valid Image resource in C:\Inetpub\BookShop_Antique\upload.php on line 77

Warning: imagedestroy(): supplied argument is not a valid Image resource in C:\Inetpub\BookShop_Antique\upload.php on line 79

Warning: imagedestroy(): supplied argument is not a valid Image resource in C:\Inetpub\BookShop_Antique\upload.php on line 80

<?php

require_once('Connections/connBookShop.php');
 

if (!function_exists("GetSQLValueString")) {

function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 

{

  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
 

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
 

  switch ($theType) {

    case "text":

      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";

      break;    

    case "long":

    case "int":

      $theValue = ($theValue != "") ? intval($theValue) : "NULL";

      break;

    case "double":

      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";

      break;

    case "date":

      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";

      break;

    case "defined":

      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;

      break;

  }

  return $theValue;

}

}
 

// Maximum file size

define ("max_size","500");
 

// Large image size

define ("width","245");

define ("height","300");
 

// Thumnail image size

define ("width_tn","96");

define ("height_tn","96");
 

// this is the function that will create the thumbnail image from the uploaded image

// the resize will be done considering the width and height defined, but without deforming the image

function make_thumb($img_name,$filename,$new_w,$new_h)

{

	//get image extension.

		$ext=getExtension($img_name);

	//creates the new image using the appropriate function from gd library

		if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))

			$src_img=imagecreatefromjpeg($img_name);

		if(!strcmp("png",$ext))

			$src_img=imagecreatefrompng($img_name);

	//gets the dimmensions

			$old_x=imageSX($src_img);

			$old_y=imageSY($src_img);

	// next we will calculate the new dimmensions for the thumbnail image

			$ratio1=$old_x/$new_w;

			$ratio2=$old_y/$new_h;

		if($ratio1>$ratio2) {

			$thumb_w=$new_w;

			$thumb_h=$old_y/$ratio1;

		}

		else {

			$thumb_h=$new_h;

			$thumb_w=$old_x/$ratio2;

}

// we create a new image with the new dimmensions

$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);

// resize the big image to the new created one

imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

// output the created image to the file. Now we will have the thumbnail into the file named by $filename

if(!strcmp("png",$ext))

imagepng($dst_img,$filename);

else

imagejpeg($dst_img,$filename);

//destroys source and destination images.

imagedestroy($dst_img);

imagedestroy($src_img);

}

// This function reads the extension of the file.

// It is used to determine if the file is an image by checking the extension.

function getExtension($str) {

$i = strrpos($str,".");

if (!$i) { return ""; }

$l = strlen($str) - $i;

$ext = substr($str,$i+1,$l);

return $ext;

}
 
 

//Here follows the php code to process post data.

//The code contains image extension and size verification as well as uploading and resizing image.

// This variable is used as a flag. The value is initialized with 0 (meaning no error found)

//and it will be changed to 1 if an error occures. If the error occures the file will not be uploaded.

$errors=0;
 

// checks if the form has been submitted

if(isset($_POST['Submit']))

{

//reads the name of the file the user submitted for uploading

$image=$_FILES['image']['name'];

// if it is not empty

if ($image)

{

// get the original name of the file from the clients machine

$filename = stripslashes($_FILES['image']['name']);

// get the extension of the file in a lower case format

$extension = getExtension($filename);

$extension = strtolower($extension);

// if it is not a known extension, we will suppose it is an error, print an error message

//and will not upload the file, otherwise we continue

if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png"))

{

echo '<h1>Unknown extension!</h1>';

$errors=1;

}

else

{

// get the size of the image in bytes

// $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which

//the uploaded file was stored on the server

$size=getimagesize($_FILES['image']['tmp_name']);

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

//compare the size with the maxim size we defined and print error if bigger

if ($sizekb > max_size*1024)

{

echo '<h1>You have exceeded the size limit!</h1>';

$errors=1;

}

//we will give an unique name, for example the time in unix time format

$image_name=time().'.'.$extension;

//the new name will be containing the full path where will be stored (images folder)

$newname="assets/images/book_cover/large/".$image_name;

make_thumb($newname, $_FILES['image']['tmp_name'], width, height);

$copied = true;

//we verify if the image has been uploaded, and print error instead

if (!$copied)

{

echo '<h1>Copy unsuccessfull!</h1>';

$errors=1;

}

else

{

// the new thumbnail image will be placed in images/thumbs/ folder

$thumb_name='assets/images/book_cover/'.$image_name;

// call the function that will create the thumbnail. The function will get as parameters

//the image name, the thumbnail name and the width and height desired for the thumbnail

$thumb=make_thumb($newname,$thumb_name,width_tn,height_tn);

}} }}

//If no errors registred, print the success message and show the thumbnail image created

if(isset($_POST['Submit']) && !$errors)

{

echo "<h1>Thumbnail created Successfully!</h1>";

echo '<img src="'.$thumb_name.'">';

}
 
 

// Insert into database

$editFormAction = $_SERVER['PHP_SELF'];

if (isset($_SERVER['QUERY_STRING'])) {

  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);

}
 

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "uploadForm")) {

 $insertSQL = sprintf("INSERT INTO items (ItemName, ItemLongDesc, ItemPrice, ItemThumb, ItemImage, ItemQnty) VALUES (%s, %s, %s, %s, %s, %s)",

                     GetSQLValueString($_POST['itemName'], "text"),

                     GetSQLValueString($_POST['itemDesc'], "text"),

                     GetSQLValueString($_POST['itemPrice'], "double"),

                     GetSQLValueString($image_name, "text"),

                     GetSQLValueString($image_name, "text"),

                     GetSQLValueString($_POST['itemQnty'], "int"));
 

  mysql_select_db($database_connBookShop, $connBookShop);

  $Result1 = mysql_query($insertSQL, $connBookShop) or die(mysql_error());

}

?>

Open in new window

0
 
LVL 48

Expert Comment

by:hernst42
ID: 21746534
maybe parameter must be change to
make_thumb($_FILES['image']['tmp_name'], $newname, width, height);
instead
make_thumb($newname, $_FILES['image']['tmp_name'], width, height);
The naming of the parameters is very confusing.
0
 
LVL 4

Author Comment

by:wilson1000
ID: 21746880
This still returns the same result - do you have anymore suggestions?
0
 
LVL 4

Accepted Solution

by:
wilson1000 earned 0 total points
ID: 21747132
I have achieved it...

The reason the warnings were generated was because the thumbnail didn't have an image on the server to work with because the copy action was taken away, i.e. copy=true

After reading through the code i added two more lines at position 147, basically creating a new image to overwrite the original image source.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Php Array Diff 3 26
windows 10 bash shell 4 33
Time difference 10 35
php documentation 4 19
Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now