Jump to content

Adding Image Resize To My Current Upload Script


sintax63

Recommended Posts

Hello PHP Freaks -

 

I have a PHP Image Upload script that I got working, but I really could use a feature or two added to it. I have been messing with it all day but have yet to make any progress. The desired features are:

 

1. Resize the uploaded photo to X amount (say 600px width)

2. Create a thumbnail of the photo and store it in a separate directory ("/photos/thumbs" for example)

 

I am will post the code below in case anyone cares to take a look at it and wouldn't mind helping out.

 

Thanks in advance,

Abraham

 

<?php

if ($_POST['process'] == 1) {

// ------------------------------------------------
// Counts The Table Rows And Adds One
// $next = mysql_insert_id();
// ------------------------------------------------

include("../admin/database.php");

$query = mysql_query("SELECT * FROM lodges"); 
$total = mysql_num_rows($query); 
$next  = $total + 1;

// ------------------------------------------------
// Separates The File Name From The Extension
// ------------------------------------------------

function findexts ($filename) 
{ 
$filename = strtolower($filename) ; 
$exts = split("[/\\.]", $filename) ; 
$n = count($exts)-1; 
$exts = $exts[$n]; 
return $exts; 
} 

// ------------------------------------------------
// Applies The Function To The File
// ------------------------------------------------
$ext = findexts ($_FILES['imgfile']['name']) ;

// ------------------------------------------------
// Renames The File To Match The Entry ID
// ------------------------------------------------
$pic = $next.".";

// ------------------------------------------------
// Define The Photo Upload Directory
// ------------------------------------------------
$target = "../photos/lodges/";

// ------------------------------------------------
// Creates The Directory/Name.Extenstion
// ------------------------------------------------
$target = $target . $pic.$ext;

if(move_uploaded_file($_FILES['imgfile']['tmp_name'], $target)) { 
echo "Photo Uploaded As ".$pic.$ext;
} else {
echo "Something Went Wrong..."; }

}

?>

Link to comment
Share on other sites

I did do a search and a whole lot of reading on that site. I guess I'm just stuck as where to put the resize / thumbnail code into my current script. I would guess at the end, since I want to wait until after I rename the file... but everything I tried yielded unsatisfactory results.  :(

Link to comment
Share on other sites

Here's a script that stores images in mysql doing something similar to what your looking for. You'll need a table with the following fields...

 

CREATE TABLE `images` (

`id` int(11) NOT NULL auto_increment,

`name` varchar(32) NOT NULL,

`description` varchar(300) NOT NULL,

`size` int(6) NOT NULL,

`date` timestamp NOT NULL default CURRENT_TIMESTAMP,

`image` mediumblob NOT NULL,

`thumb` mediumblob NOT NULL,

PRIMARY KEY (`id`),

KEY `date` (`date`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;

 

This code will resize the image (currently keeping it under 150 kb's) and create a thumbnail image. It doesn't have many frills and you will still be chewing up bandwidth unless you shrink the files on a localhost server on your own machine. It's currently setup strictly for jpegs.

 

<?php



if(isset($_REQUEST['upload'])) {



ini_set('memory_limit', '200m');

$filesize = $_FILES['userfile']['size'];
$filename = $_FILES['userfile']['name'];
$filetype = $_FILES['userfile']['type'];
$tmpname = $_FILES['userfile']['tmp_name'];
$desc = $_REQUEST['description'];
$desc = htmlspecialchars($desc);

if($filetype == 'image/pjpeg') {

	$orig_image = imagecreatefromjpeg($tmpname);

	list($width, $height) = getimagesize($tmpname);

	if($filesize > 157286) { // Resize image if it's over 150 kb's.

		//When I wrote this I was mainly concerned with keeping the image file equal
		//to 150 kb's it could easily be converted to adjust to certain dimensions.

		$percent = 157286 / $filesize;

		$newwidth = $width * $percent;
		$newheight = $height * $percent;

		$new_image = imagecreatetruecolor($newwidth, $newheight);

		imagecopyresampled($new_image, $orig_image, 0, 0, 0, 0,$newwidth, $newheight, $width, $height);

	}

	// Generate thumbnail images.

	$thumbw = 50;

	$thumbh = $thumbw / $width * $height;

	$thumb = imagecreatetruecolor($thumbw, $thumbh);

	imagecopyresampled($thumb, $orig_image, 0, 0, 0, 0, $thumbw, $thumbh, $width, $height);

	ob_start(); // Start capturing stdout.		

	imagejpeg($thumb); // As though output to browser.

	$binarythumb = ob_get_clean(); // the raw jpeg image data.

	ob_start();

	imagejpeg($new_image);

	$binaryimage = ob_get_clean();

	$thumb = addslashes($binarythumb);

	$image = addslashes($binaryimage);

	$filesize = $filesize * $percent;

	// create mysql query.

	include("mysql_connect.php");

	$query = "INSERT INTO images (name, description, size, image, thumb)
		  VALUES ('$filename','$desc','$filesize','$image','$thumb')";



	$result = mysql_query($query) or die(mysql_error());



	if($result) {

		echo "
<pre>
Filename: $filename
Filesize: ".$filesize * $percent."
Filetype: $filetype
Filestatus: Your file uploaded successfully!
</pre>";

	}else{

		echo "File failed to upload.";

	}

}else{

	echo "This program only supports the upload of jpeg files <br />
	      your image is a $filetype file.";

}



}

?>

<html>

<head>

</head>

<body>

<fieldset><legend>Upload Images</legend>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<label id='label'>Select image:</label><input id='input' name="userfile[]" type="file" id="userfile"><br /> 
<label id='label'>Description:</label><br />
<textarea name='description' cols='30' rows='7'></textarea><br />
<input id='submit' name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>
</fieldset>

</body>

</html>

 

 

Link to comment
Share on other sites

pish posh Vbulletin has no problems with storing images in mysql. I have heard the same thing, but have never really investigated why. (I'm a good listner if some one would care to share.)

You could use the same code to resize for directory storage the variables binarythumb and binaryimage can be stored anywhere your little heart desires. The addslashes is for database storage so the variables thumb and image would probably give you invalid images.

Link to comment
Share on other sites

Well I've already got part of the upload script working with directory storage so I guess I will stay the course on that front.

 

Thanks to everyone for the links. I am usually pretty good about hacking my way through things to get them to function as I desire, but this GD library stuff just isn't clicking as quickly as I need it too.  :(

Link to comment
Share on other sites

I use a rather complicated resize function, but I've simplified it here, this might help you with creating a file instead of storing in DB:

It will save it as a jpg always, but I bet you can figure out how to change that.

<?php
if(isset($_FILES['file'])){
$ext = explode('.', $_FILES[$this->id]['name']);
$ext = $ext[count($ext)-1];
$newName  = 'my file new name.'.$ext;
$newLoc = 'new/file/location';
$targetPath = $newLoc.$newName;
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
$this->savedFileLoc = $f;
	if($ext == 'jpg'){
		$ext = 'jpeg';
	}
	$func = 'imagecreatefrom'.$ext;
	$photo = $newLoc.$newName;
	list($width_orig, $height_orig) = getimagesize($photo);
	$ratio_orig = $width_orig/$height_orig;

	$maxW = 200;
	$maxH = 150;
	if($maxW/$maxH > $ratio_orig){
		$newW = $maxW*$ratio_orig;
		$newH = $maxH;
	}else{
		$newH = $maxH/$ratio_orig;
		$newW = $maxW;
	}

	if($newH <= $height_orig && $newW <= $width_orig){
		$image_p = imagecreatetruecolor($newW, $newH);
		$image = $func($photo);
		imagecopyresampled($image_p, $image, 0, 0, 0, 0, $newW, $newH, $width_orig, $height_orig);
		if(imagejpeg($image_p, $path.$newName.'.jpg', 100)){
			$file = $newName.'.jpg';
		}
	}
}
}
?>

 

(I didn't check it for errors, sorry)

Link to comment
Share on other sites

Should be imagecreatefromjpeg()

 

Here is what's going on now. The file gets renamed as desired and uploaded to the proper directory, but there is no extension on it (it is "6" instead of "6.jpg" for example). Also, there is no resizing going on whatsoever...

 

<?php

if(isset($_REQUEST['upload'])) {

// ------------------------------------------------
// Counts The Table Rows And Adds One
// $next = mysql_insert_id();
// ------------------------------------------------

include("database.php");

$query = mysql_query("SELECT * FROM lodges"); 
$total = mysql_num_rows($query); 
$next  = $total + 1;

// ------------------------------------------------
// Checks For A Valid File Type (JPG, GIF, PNG)
// ------------------------------------------------
if (!($file_type =="image/pjpeg" OR $file_type =="image/jpeg" OR $file_type=="image/gif" OR $file_type=="image/png" OR $file_type=="image/x-png")) {  
        die ("You can only upload photos in .jpg .gif and .png format!");  
    }  

if(isset($_FILES['file'])) {

$ext = explode('.', $_FILES[$this->id]['name']);
$ext = $ext[count($ext)-1];

$newName  = $next.$ext;
$newLoc = '../photos/lodges/';

$targetPath = $newLoc.$newName;
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
$this->savedFileLoc = $f;
	if($ext == 'jpg'){
		$ext = 'jpeg';
	}
	$func = 'imagecreatefromjpeg'.$ext;
	$photo = $newLoc.$newName;
	list($width_orig, $height_orig) = getimagesize($photo);
	$ratio_orig = $width_orig/$height_orig;

	$maxW = 600;
	$maxH = 600;
	if($maxW/$maxH > $ratio_orig) {
		$newW = $maxW*$ratio_orig;
		$newH = $maxH;
	} else {
		$newH = $maxH/$ratio_orig;
		$newW = $maxW;
	}

	if($newH <= $height_orig && $newW <= $width_orig){
		$image_p = imagecreatetruecolor($newW, $newH);
		$image = $func($photo);
		imagecopyresampled($image_p, $image, 0, 0, 0, 0, $newW, $newH, $width_orig, $height_orig);
		if(imagejpeg($image_p, $path.$newName.'.jpg', 100)){
			$file = $newName.'.jpg';
		}
	}
}
}

}

?>

 

 

Link to comment
Share on other sites

I'm SO close to getting this working now. I have given up on the image resize upon upload because I could never get it to work. But I do have a couple issues which seem to be easy fixes.

 

1. How do I detect if the upload field has a file in it? I want to detect this so I can kick back an error if the file isn't a JPG.

 

2. I am getting an error upon successful submission that reads:

Warning: Cannot modify header information - headers already sent by (output started at /add/index.php:163) in /add/index.php on line 174

 

You will see I fudged this with a hidden form field called "uploader" and set the status to "1". This of course requires a photo to be uploaded every time.  :-[

 

I can't believe I have spent so many days on one page within my web site. If anyone can help me straighten out this errors I would be most grateful. My current code follows:

 

<?php

$thisPage = "Add A Lodge";

session_start(); 

// The Default Variable For The Empty Form

    $date	= date("Y-m-d");
    $name   = "";
    $number	= "";
    $type   	= "";
    $address= "";
    $city   	= "";
    $state   	= "";
    $zip   	= "";
    $area	= "";
    $phone	= "";
    $email	= "";
    $url	= "";
    $meeting= "";
    $time	= "";
    $chartered = "";
    $members = "";
    $grand	= "";
    $notes	= "";

    $exampleclass1  = "example";
    $exampleclass2  = "example";
    $exampleclass3  = "example";
    $exampleclass4  = "example";
    $exampleclass5  = "example";
    $exampleclass6  = "example";
    $exampleclass7  = "example";
    $exampleclass8  = "example";
    $exampleclass9  = "example";
    $exampleclass10 = "example";
    $exampleclass11 = "example";
    $exampleclass12 = "example";
    $exampleclass13 = "example";
    $exampleclass14 = "example";
    $exampleclass15 = "example";
    $exampleclass16 = "example";

// Field Validation Checks After Submit Button Is Pressed

    if(isset($_REQUEST['submit'])) {

// ------------------------------------------------
// Checks For A Valid File Type (JPG)
// ------------------------------------------------
if (!($userfile_type =="image/pjpeg" OR $userfile_type =="image/jpeg")) {  
die ("You can only upload photos in .jpg .gif and .png format!");  } 

    $name 	= $_REQUEST['name'] ;
    $number	= $_REQUEST['number'] ;
    $type 	= $_REQUEST['type'] ;
    $address= $_REQUEST['address'] ;
    $city 	= $_REQUEST['city'] ;
    $state 	= $_REQUEST['state'] ;
    $zip 	= $_REQUEST['zip'] ;
    $area 	= $_REQUEST['area'] ;
    $phone 	= $_REQUEST['phone'] ;
    $email 	= $_REQUEST['email'] ;
    $url 	= $_REQUEST['url'] ;
    $meeting 	= $_REQUEST['meeting'] ;
    $time 	= $_REQUEST['time'] ;
    $chartered 	= $_REQUEST['chartered'] ;
    $members 	= $_REQUEST['members'] ;
    $grand 	= $_REQUEST['grand'] ;
    $notes 	= $_REQUEST['notes'] ;

    if (!isset($_REQUEST['name'])) {
    header( "Location: index.php" );
    }

  	elseif (empty($name)) {
  	$exampleclass1 = "example-error";
  	$message = "Norton Moses Lodge";
  	}

elseif (empty($number)) {
  	$exampleclass2 = "example-error";
  	$message = "336";
  	}

  	elseif (empty($type)) {
  	$exampleclass3 = "example-error";
  	$message = "AF&AM";
  	}
  
elseif (empty($address)) {
  	$exampleclass4 = "example-error";
  	$message = "201 Sonny Drive";
  	}
  
elseif (empty($city)) {
  	$exampleclass5 = "example-error";
  	$message = "Austin";
  	}

elseif (empty($state)) {
  	$exampleclass6 = "example-error";
  	$message = "TX";
  	}

elseif (empty($zip)) {
  	$exampleclass7 = "example-error";
  	$message = "78767";
  	}

  else {

// Database Insertion Upon Successful Form Submission

include("../admin/database.php"); 

$query="INSERT INTO lodges VALUES ('','$date','$name','$number','$type','$address','$city','$state','$zip','$area','$phone','$email','$url','$meeting','$time','$chartered','$members','$grand','$notes','0','0')";
mysql_query($query);

if ($uploader == "1") {

// ------------------------------------------------
// Gets The Table ID Of This Entry
// ------------------------------------------------

$next = mysql_insert_id();

// ------------------------------------------------
// Separates The File Name From The Extension
// ------------------------------------------------

function findexts ($filename) { 
$filename = strtolower($filename) ; 
$exts = split("[/\\.]", $filename) ; 
$n = count($exts)-1; 
$exts = $exts[$n]; 
return $exts; }

// ------------------------------------------------
// Applies The Function To The File
// ------------------------------------------------

$ext = findexts ($_FILES['userfile']['name']) ;

// ------------------------------------------------
// Renames The File To Match The Entry ID
// ------------------------------------------------

$pic = $next.".";

// ------------------------------------------------
// Define The Photo Upload Directory
// ------------------------------------------------

$target = "../photos/lodges/";

// ------------------------------------------------
// Creates The Directory/Name.Extenstion
// ------------------------------------------------

$target = $target . $pic.$ext;

if(move_uploaded_file($_FILES['userfile']['tmp_name'], $target)) { 
echo "Photo Uploaded As ".$pic.$ext. "<br />";

} else {

echo "Something Went Wrong... <br />"; }

}

$_SESSION["submitted"] = '1';
$_SESSION["recordID"]  = $id;

header( "Location: ../success/" );

mysql_close();

  }
  }

?>


<?php include("../modules/header.php"); ?>

<h1>Add A New Lodge</h1>

<p>Use this form to submit a new lodge to the database. To ensure a successful listing, please provide as much information as possible. Please note that all submissions are subject to approval.</p>

<div id="add">

<form enctype="multipart/form-data" action="" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input type="hidden" name="uploader" value="1">

<table cellpadding="0" cellspacing="0" border="0">
   <tr>
<th scope="col" abbr="Name" class="nobg">Lodge Name</th>
<th scope="col" abbr="Number">Number</th>
<th scope="col" abbr="Type">Affiliation</th>
   </tr>

   <tr>
<td style="border-left: 1px solid #535353"><div id="<?print $exampleclass1; ?>">Norton Moses Lodge</div>
<input type="text" name="name" style="width:220px" value="<? print $name; ?>" maxlength="50"></td>

<td><div id="<?print $exampleclass2; ?>">336</div>
<input type="text" name="number" style="width:50px" value="<? print $number; ?>" maxlength="5"></td>

<td><div id="<?print $exampleclass3; ?>">AF&AM</div>
   	   <select name="type" style="width:75px">
	<option value="<? print $type; ?>"><? print $type; ?></option>
	<option value="AF&AM">AF&AM</option>
	<option value="F&AM">F&AM</option>
	<option value="PH">Prince Hall</option>
   	   </select>
</td>

   </tr>
</table>

<table cellpadding="0" cellspacing="0" border="0">
   <tr>
<th scope="col" abbr="Address" class="nobg">Address</th>
<th scope="col" abbr="City">City</th>
<th scope="col" abbr="State">State</th>
<th scope="col" abbr="Zip">Zip Code</th>
   </tr>

   <tr>
<td style="border-left: 1px solid #535353"><div id="<?print $exampleclass4; ?>">201 Sonny Drive</div>
<input type="text" name="address" style="width:150px" value="<? print $address; ?>" maxlength="50"></td>

<td><div id="<?print $exampleclass5; ?>">Austin</div>
<input type="text" name="city" style="width:75px" value="<? print $city; ?>" maxlength="25"></td>

<td><div id="<?print $exampleclass6; ?>">TX</div>
   <select name="state" style="width:50px">
	<option value="<? print $state; ?>"><? print $state; ?></option>
	<option value="TX">TX</option>
   	   </select>
</td>

<td><div id="<?print $exampleclass7; ?>">78767</div>
<input type="text" name="zip" style="width:50px" value="<? print $zip; ?>" maxlength="5"></td>

   </tr>
</table>

<table cellpadding="0" cellspacing="0" border="0">
   <tr>
<th scope="col" abbr="Phone" class="nobg">Phone Number</th>
<th scope="col" abbr="Email">Lodge Email</th>
<th scope="col" abbr="URL">Lodge Web Site</th>
   </tr>

   <tr>
<td style="border-left: 1px solid #535353"><div id="<?print $exampleclass8; ?>">512     123-4567</div>
<input type="text" name="area" style="width:30px" value="<? print $area; ?>" maxlength="3">
<input type="text" name="phone" style="width:65px" value="<? print $phone; ?>" maxlength="8"></td>

<td><div id="<?print $exampleclass9; ?>">name@domain.com</div>
<input type="text" name="email" style="width:130px" value="<? print $email; ?>" maxlength="50"></td>

<td><div id="<?print $exampleclass10; ?>">http://www.domain.com</div>
<input type="text" name="url" style="width:130px" value="<? print $url; ?>" maxlength="100"></td>

   </tr>
</table>

<table cellpadding="0" cellspacing="0" border="0">
   <tr>
<th scope="col" abbr="Meeting" class="nobg">Meeting Day</th>
<th scope="col" abbr="Day">Time</th>
<th scope="col" abbr="Membership">Membership</th>
   </tr>

   <tr>
<td style="border-left: 1px solid #535353"><div id="<?print $exampleclass11; ?>">Third Monday</div>
<input type="text" name="meeting" style="width:150px" value="<? print $meeting; ?>" maxlength="50">

<td><div id="<?print $exampleclass12; ?>">6:00 pm</div>
   <select name="time" style="width:85px">
	<option value="<? print $time; ?>"><? print $time; ?></option>
	<option value="16:00:00">04:00 pm</option>
	<option value="16:30:00">04:30 pm</option>
	<option value="17:00:00">05:00 pm</option>
	<option value="17:30:00">05:30 pm</option>
	<option value="18:00:00">06:00 pm</option>
	<option value="18:30:00">06:30 pm</option>
	<option value="19:00:00">07:00 pm</option>
	<option value="19:30:00">07:30 pm</option>
	<option value="20:00:00">08:00 pm</option>
	<option value="20:30:00">08:30 pm</option>
	<option value="21:00:00">09:00 pm</option>
	<option value="21:30:00">09:30 pm</option>
	<option value="22:00:00">10:00 pm</option>
   </select>
</td>

<td><div id="<?print $exampleclass13; ?>">162</div>
<input type="text" name="members" style="width:30px" value="<? print $members; ?>" maxlength="3"></td>

   </tr>
</table>

<table cellpadding="0" cellspacing="0" border="0">
   <tr>
<th scope="col" abbr="Chartered" class="nobg">Charter Date</th>
<th scope="col" abbr="Grand">Grand Lodge</th>
   </tr>

   <tr>
<td style="border-left: 1px solid #535353"><div id="<?print $exampleclass14; ?>">YYYY-MM-DD</div>
<input type="text" name="chartered" style="width:100px" value="<? print $chartered; ?>" maxlength="10"></td>

<td><div id="<?print $exampleclass15; ?>">Grand Lodge Of Texas</div>
<input type="text" name="grand" style="width:160px" value="<? print $grand; ?>" maxlength="50"></td>

   </tr>
</table>

<table cellpadding="0" cellspacing="0" border="0">
   <tr>
<th scope="col" abbr="notes" class="nobg">Additional Lodge Information</th>
   </tr>

   <tr>
<td style="border-left: 1px solid #535353">
<div id="<?print $exampleclass16; ?>">HTML Tip: <p>Separate Paragraphs Using These Tags</p></div>
<textarea name="notes" style="width:98%; height:100px"><? print $notes; ?></textarea></td>
   </tr>
</table>

<p><input name="userfile" type="file" /></p>

<input type="submit" name="submit" value="Submit Lodge" />

</form>

</div>

<div id="splash-footer"></div>

<?php include("../modules/footer.php"); ?>

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.