Solved

Image Upload using the gd library and PHP

Posted on 2008-06-09
5
2,131 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

734 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