Question

PHP -- HOw to Resize a JPG Image proportionately on upload function..

Asked by: sam928

Hello,
I have PHP script that resizes a JPG image (from an upload function)

However, the script that I have DOES NOT resize the image PROPORTIONANTLEY,  (sorry for spelling ;) )

The script i have attached resizes the image to a height of 100 pixels.  and it changes the width to 500.. (for some reason, but i do not see the variable in the PHP script,, i only see the HEIGHT of 100 variable)

What is needed to be changed to create a proportionate resize of 400 x 300.?

Anybody have an idea?

Cheers

<?php
// include the Database classes
require_once('classes/database_php4.php');
 
// escape quotes and apostrophes if magic_quotes_gpc off
if (!get_magic_quotes_gpc()) {
  foreach($_POST as $key=>$value) {
    $temp = addslashes($value);
    $_POST[$key] = $temp;
    }
  }
 
$db = new Database('db704.perfora.net','dbo277201649','Ycd2sZaR','db277201649');
$numrows = 1;
// if more than 3 send error message //
if ($numrows > 2) {
  $maxwishes = 'Personal Upload Limit Reached for Today... Sorry';
  echo 'duplicate=y&message='.urlencode($maxwishes);
  }
else {
		function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth ) 
{
  // open the directory
  $dir = opendir( $pathToImages );
 
  // loop through it, looking for any/all JPG files:
  while (false !== ($fname = readdir( $dir ))) {
    // parse path for the extension
    $info = pathinfo($pathToImages . $fname);
    // continue only if this is a JPEG image
    if ( strtolower($info['extension']) == 'jpg' ) 
    {
      echo "Creating thumbnail for {$fname} <br />";
 
      // load image and get image size
      $img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
      $width = imagesx( $img );
      $height = imagesy( $img );
 
      // calculate thumbnail size
      $new_width = $thumbWidth;
      $new_height = floor( $height * ( $thumbWidth / $width ) );
      $new_height = 100;
 
      // create a new temporary image
      $tmp_img = imagecreatetruecolor( $new_width, $new_height );
      srand(time());
      $random = (rand()%999);
      $random2 = (rand()%999);
 
      // copy and resize old image into new image 
      imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
      $newname = 'cmsnewsv2'.$random.$random2.'.jpg';
      $_POST['new_name'] = $newname;
 
      // save thumbnail into a file
      imagejpeg( $tmp_img, "{$pathToThumbs}{$newname}" );
      unlink($tmp_img, "{$pathToimages}{$fname}");
      $tmp_img = "";
      $img = "";
      $info = "";
      $fname = "";
    }
  }
  // close the directory
  closedir( $dir );
}
createThumbs("files/","files/thumbs/",500);
  $sql = 'INSERT INTO cmsnewsv2 (story_title,story_body,story_date,story_postedby,story_photo,story_link,story_price)
          VALUES ("'.$_POST['ttitle'].'","'.$_POST['story'].'","'.$_POST['date'].'","'.$_POST['author'].'","'.$_POST['new_name'].'","'.$_POST['uurl'].'","'.$_POST['pprice'].'")';
 
	$result = $db->query($sql);
  if ($result) {
    $created = 'Thankyou!';
    echo 'duplicate=n&message='.urlencode($created);
}
}
?>

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-07-05 at 09:40:54ID24544972
Tags

PHP

,

jpg

,

JPG

,

resizing an image

Topics

PHP Scripting Language

,

Images & Photo Software

Participating Experts
2
Points
500
Comments
8

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Resize/Save JPG
    With 'Paint Shop Pro' I can resize a JPG-picture while maintaining its aspect ratio. I want to do the same in a Delphi-program. After that I want to be able to save the altered JPG-picture. I'm using the component TPMultiImage form ImageLib. When I save a JPG-picture (using...
  2. GIF -> JPG then Scale
    Hi, I need to know how I can find out the type of the image (from filename) then if its a gif or bmp, convert it to jpg. Then scale it, keeping the proportions. I do not have telnet or root. The ISP will not install any modules. Must use modules that can simply be put in the ...
  3. parsing .jpg as php and returning a jpg?
    I want to use random images on my site, but I'd like to have them displayed by using jpg as the php extention. First of all, the server needs to be able to read a jpg as a php file -- I'm thinking this can be accomplished with htaccess. Second, this .jpg file (essentially a ...
  4. PHP to convert PNG to JPG
    Does anyone know how to convert a .png to a .jpg on the fly with a .php script?
  5. To convert .tif to .jpg --> PHP
    How I can convert image format .tif to jpg(or gif or png) through PHP script ?, do you know some script???

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Ray_PaseurPosted on 2009-07-05 at 09:46:03ID: 24780486

Here is an example of how to do it.  Please read it over and post back here if you have any questions.  Best regards, ~Ray

<?php // RAY_upload.php 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 = ereg_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	= 'photos';
 
// 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=>"<font color=green>Success!</font>",
	1=>"<font color=gold>The uploaded file exceeds the upload_max_filesize directive in php.ini</font>",
	2=>"<font color=gold>The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form</font>",
	3=>"<font color=gold>The uploaded file was only partially uploaded</font>",
	4=>"<font color=gold>No file was uploaded</font>",
	6=>"<font color=gold>Missing a temporary folder</font>",
	7=>"<font color=gold>Cannot write file to disk</font>"
);
 
// 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>
 
	<!-- 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();
 
} else {
 
// THERE IS POST DATA - PROCESS IT
	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
	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 PAGE 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";
 
 
	die('Done');
}
?>
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:

Select allOpen in new window

 

by: ErburethPosted on 2009-07-05 at 09:47:59ID: 24780492

Commenting out line 43 should do the trick ($new_height = 100;)

on line 42 you already have correct formula to calculate new height, but you overwrite it afterwards, which is bad.

 

by: Ray_PaseurPosted on 2009-07-05 at 10:11:25ID: 24780576

@Erbureth: Good catch.  After I saw the references to PHP4, I never bothered to read or test the script!

Best to all, ~Ray

 

by: sam928Posted on 2009-07-05 at 10:35:05ID: 24780646

Hello, Thank you for the lightning fast responses!!

@Erbureth, i have commented that line out,, and i have checked the result;  

I uploaded a 80 x 60 image... and it converted it to 500 x 375.

---------------------------
soo, somewhere it is resizing the width to 500.  i do not know where,  (is that what  'thumbWidth' is referring to? )   --- line 41 and 42.

i'm confused!


 

by: sam928Posted on 2009-07-05 at 10:41:45ID: 24780677

... Line 21 also... refers to 'thumbWidth'


 

by: Ray_PaseurPosted on 2009-07-05 at 11:07:11ID: 24780766

Read over the code I posted in lines 36 to 76.  It tests for appropriate sizes and does not resize images that are already small enough.  Hopefully the comments in that section will be helpful.  Best, ~Ray

 

by: ErburethPosted on 2009-07-05 at 15:34:15ID: 24781541

This is because at line 68, you are calling function createThumbs with last parameter 500
If you see the function prototype at line 21, you will see that the last parameter is that thumbWidth, which is desired width of all thumbnails.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...