Jump to content

[SOLVED] Creating thumbnail images


bluebyyou

Recommended Posts

I have a script uploading photos. When the file is uploaded i am trying to create a thumbnail of that image. I want the thumbnail to keep the proportions of the original image. So if the image is larger than the thumbnail dimensions I specify it works just fine. However if one or both of the dimensions of the image uploaded is smaller than the thumbnail I want to create I run into trouble. Mostly when the images height is shorter than the intended thumbnails height, but wider. For example a image that is 110px tall x 90px wide causes the script to fail. Can anyone help me figure out what is going wrong here?

 

 

List of sucessful image sizes:

70px tall x 85px wide

1024px tall x 768px wide

100px tall x 80px wide

114px tall x 85px wide

 

150px tall x 80px wide <<creates a thumbnail, but it is not the correct size and information is lost from the image

 

 

Here is the thumbnail portion of the script, if you would like to see the whole thing let me know.

                  <?php
                  //Create Thumbnail Image
                  $src_img = imagecreatefromjpeg("uploads/$new_file_name");
   			 $origw=imagesx($src_img);
   			 $origh=imagesy($src_img);


		 // Thumbnail Dimensions
		 $thumb_width = 114;// Thumbnail Display Width
		 $thumb_height = 85;// Thumbnail Display Height

		 if ($origw <= $thumb_width or $origh <= $thumb_height)
		 {
		 	if ($origh <= $thumb_height and $origw <= $thumb_width) 		// Both Original Dimensions smaller than thumbnail dimensions
			{
		 	$new_w = $origw;				// Keep original width
		 	$new_h = $origh;				// Keep original height
			}

			if ($origh > $thumb_height and $origw <= $thumb_width)  		// Height greater than thumbnail height and Width less than thumbnail width
			{
			$percentage = ($origh / $thumb_height) / 100;
			$new_w = $origw * $percentage;	// shrink width 
		 	$new_h = $origh * $percentage;	// shrink height
			}

			//     \/  I think this one below is the problem  \/
			if ($origh <= $thumb_height and $origw > $thumb_width)  		// Height less than or eaqual thumbnail height and width greater than thumbnail width
			{
			$percentage = ($origw / $thumb_width) / 100;  
		 	$new_w = $origw * $percentage;  // shrink width    
		 	$new_h = $origh * $percentage;	// shrink height      	
			}		

			if($origw > $thumb_width and $origh <= $thumb_height)     		// Wider than thumb with and height smaller than thumb height
		    {
		 	$percentage = ($origw / $thumb_width) / 100;
		 	$new_w = $origw * $percentage;  // shrink width
		 	$new_h = $origh * $percentage; 	// shrink height
		 	}	

			if($origw <= $thumb_width and $origh > $thumb_height)			//  width smaller than thumb width and height greater than thum height
		    {
		 	$percentage = ($origw / $thumb_width) / 100;
		 	$new_w = $origw * $percentage;  // shrink width
		 	$new_h = $origh * $percentage; 	// shrink height
		 	}	
		 }
		 else
		 {
		 $percentage = ($origw / $thumb_width) / 100;			// Both Dimensions larger than thumbnail
		 $new_w = $origw * $percentage;      // shrink width
		 $new_h = $origh * $percentage;      // shrink height
		 }

   			 $dst_img = imagecreatetruecolor($new_w,$new_h);
    		 imagecopyresized($dst_img,$src_img,0,0,0,0,$new_w,$new_h,imagesx($src_img),imagesy($src_img));
		 imagejpeg($dst_img, "uploads/$thumb_file_name");
?>

Link to comment
Share on other sites

firstly grab the aspect ratio of the image (even the bigger ones) then comapre that to the aspect ratio of your defined thumnail...

 

use the result to 'select' a portion of teh orignial that is off the same aspect ratio as your desired thumbnail - when you create the tuhmbnail use the new co-ordinates to select the part of the original (basically you are cropping the image so you will lose a portion at the top and bottom or the left and right).

 

If you want an example of how to do it post back - I'll copy a snippet that I use for resizing/thumbnail creation.

Link to comment
Share on other sites

ToonMariner,

 

I am getting the original dimensions and comparing them in my script. I do not want to crop, I want to resize proportionaly. The dimensions of 114x85 are just what i want the thumbnail to fit with in and be no larger than. Which is working for most size images. I am just having trouble getting it to work for images that are wider than my desired size, but shorter. I might not have been clear that what I have works, but not 100%.

Link to comment
Share on other sites

can you show me an example ToonMariner.. pretty pwease?!   :P

 

hmmmmmmmmmmm: nubile young lady asking me for something (happy birthday to me...) :P

 

OK I don't have time to edit it all so I am attaching the files...

 

Now how to use it...

 

foreach ($_FILES['upfile']['name'] as $key => $value)
{
if	(
	$_FILES['upfile']['error'][$key]	==	0
	)
{
	$image_arr[$key]	=	do_uploads	(
						'upfile' ,
						'/path/to/upload/dir/' ,
						$key ,
						500 ,
						245 ,
						true ,
						150 ,
						100				
						);
}
}

 

This particular example requies that your file inputs be named 'upfile[]' e.g.

 

<input type="file" name="upfile[]" />

 

This allows teh script to handle multiple images being uploaded at once...

 

It loops through each file in the $_FILES array and checks that it uploaded ok if it did then it calls the function to upload the file and do the magic...

 

The function called explained...

$image_arr[$key]	=	do_uploads	(
				'upfile' , // name of the form input
				'/path/to/upload/dir/' , // path to directory file will be saved
				$key , // current key in teh $_FILES array
				500 , // max size of large image
				245 , // max height of large image
				true , // create a thumbnail true = yes, false = no
				150 , // max width of thumbnail
				100 // max height of thumbnail
				);

 

the script requires you to create a folder called 'thumbs' in the directory you are uploading to (you can always mod the class to create it if it doesn't exist).

 

If there is a clash on teh filename then _n will be added to the filename so it doesn't overwrite the image already there.

 

the result of the call is teh files being in their specified location and also an array which gives details on each file - its name, its location, mime type, dimensions etc.

 

just swap the txt extension to php...

 

have fun - feel free to ask questions...

 

the actual resizing is done in the genImage method of the class. You can see all the math there (if you spot an error in the logic or something just fix it - I have a new version of this that works just fine.)

 

 

 

[attachment deleted by admin]

Link to comment
Share on other sites

@ bluebyyou

 

Understood.  Its all a question of ratios - get the ratio fo your thumb (114/85 = 1.34) and the ratio of your original.

 

if the original is wider but shorter then you need to adjust the width to 114 and the height to a similar ratio to work that out...

 

$origw=imagesx($src_img);
$origh=imagesy($src_img);

$thumb_width = 114;
$thumb_height = 85;

$changeinwidth = $origw/$thumb_width;

$newheight = $origh/$changeinwidth;

Link to comment
Share on other sites

Right, I have exactly that alreay in my script.  I have a series of if statements doing the math for all of the different possibilities. The problem I am runnning into is images that have one of its dimensions smaller than the thumbnail dimensions. Specifically images that are longer but shorter than 114 x 85. It works fine for images that are larger than 114 x 85, they are scaled down with no problem. However if there is an image, for example, that is 200px wide x 85 tall, the script is not creating the thumbnail. So i am asking for help with the code I have already written and pasted in in my first post. If seeing the entire script would help let me know.

Link to comment
Share on other sites

Check out this thread / post:

 

http://www.phpfreaks.com/forums/index.php/topic,165733.msg728987.html#msg728987

 

The code holds a working method of calculating new height / width for pictures and it works not matter what dimensions you want and what dimensions you have.

 

Of course this is build on the concept of maximum height and maximum width. If you want a thumbnail of maximum 80x80 px and have a picture which is 20x160 px you will end up with a picture of 10x80 px.

 

Link to comment
Share on other sites

That was very helpful. I definately was able to clean up my code and get it working how I wanted. The only issue i have now is images that are wider than the desired thumbnail with, but shorter than the desired thumbnail height. For example an image that is 150w x 80h does not scale down to fit. It remains the same size(150x80).

 

Here is the new code:

 

<?php			

//Create Thumbnail Image
$src_img = imagecreatefromjpeg("uploads/$new_file_name");     // Uploaded file location
$origw=imagesx($src_img);				                                 // Get Photo width
$origh=imagesy($src_img);						                      // Get Photo height

// Thumbnail Dimensions
$thumb_width = 114;							                      // Thumbnail Display Width
$thumb_height = 85;				      		                      // Thumbnail Display Height

// Thumbnail Image Quality
$img_quality = 75;								                     // Image quality for the web is 75 dpi

$test_h = round($thumb_height / $origh, 2);		                     // Calculate height shrink ratio
$test_w = round($thumb_width / $origw, 2) ;		                     // Calculate width shrink ratio


if ($origh <= $thumb_height && $origw <= $thumb_width) 
{
$new_w = $origw;								//Keep original width
$new_h = $origh;								//Keep original height
}
else if ($origh > $thumb_height || $origw > $thumb_width)
{
if ( $origh > $thumb_height && $origw < $thumb_width )	{
$percentage = $test_h;
$new_w = $origw * $percentage;			// shrink width 
$new_h = $origh * $percentage;				// shrink height
}
else if ($origw > $thumb_width && $origh < $thumb_height )
{
$percentage = $test_h;
$new_w = $origw * $percentage;			// shrink width 
$new_h = $origh * $percentage;				// shrink height
}
else if ($origh > $thumb_height && $origw > $thumb_width)
{
$percentage = $test_w;
$new_w = $origw * $percentage;			// shrink width 
$new_h = $origh * $percentage;				// shrink height
}	
}

$dst_img = imagecreatetruecolor($new_w,$new_h);
imagecopyresized($dst_img,$src_img,0,0,0,0,$new_w,$new_h,imagesx($src_img),imagesy($src_img));
imagejpeg($dst_img, "uploads/$thumb_file_name", $img_quality);

?>

Link to comment
Share on other sites

Unless you wanna stretch and cut in your image (which I don't think you want to) just stick with this very simple code:

 

<?php

//Max height and width
$max_height = 600;
$max_width = 600;

//Getting image size
$size=getimagesize($image);
$width=$size[0];
$height=$size[1];

//Calculating the new height and width
$x_ratio=$max_width/$width;
$y_ratio=$max_height/$height;


if(($width <= $max_width) && ( $height <= $max_height)){
$tn_width=$width;
$tn_height=$height;
}
else if(($x_ratio*$height) < $max_height){
$tn_height=ceil($x_ratio*$height);
$tn_width=$max_width;
}
else{
$tn_width=ceil($y_ratio*$width);
$tn_height=$max_height;
}

?>

 

I have been playing around with your code a little and the variable names are very confusing and your "cases" (different situations with the hight and width) do not seem logic. Unless you want stretching and cutting the above code works.

Link to comment
Share on other sites

My code does work, and I think it covers any possiblility that someone might upload. I am sorry that the variables are confusing. I dont have any stretching or cutting happening.

I tried to rename the variables more in your style. The uploaded images are at www.wiuartinny.com/gallery you can see the ratios on the images, and you san see which ones did not work. (140x50 and 150x80)

<?php

		//Create Thumbnail Image
		$src_img = imagecreatefromjpeg("uploads/$new_file_name");					// Uploaded file location
   			$img_width=imagesx($src_img);												// Get Photo width
   			$img_height=imagesy($src_img);												// Get Photo height

		// Thumbnail Dimensions
	 	$thumb_width = 114;															// Thumbnail Display Width
		$thumb_height = 85;															// Thumbnail Display Height

		// Thumbnail Image Quality
		$img_quality = 75;															// Image quality for the web is 75 dpi

		$height_ratio = round($thumb_height / $img_height, 2);						// Calculate height shrink ratio
		$width_ratio = round($thumb_width / $img_width, 2) ;						// Calculate width shrink ratio


		if ($img_height <= $thumb_height && $img_width <= $thumb_width) 		
		{
		$new_width = $img_width;													//Keep original width		
		$new_height = $img_height;													//Keep original height
		}
		else if ($img_height > $thumb_height || $image_width > $thumb_width)
		{

			if ( $img_height > $thumb_height && $img_width < $thumb_width )		
			{
			$new_width = $img_width * $height_ratio;									// shrink width 
		 	$new_height = $img_height * $height_ratio;								// shrink height
			}
			else if ($img_width > $thumb_width && $img_height < $thumb_height )
			{
                       // This is where the image is not being scaled I believe
			$new_width = $img_width * $height_ratio;									// shrink width 
		 	$new_height = $img_height * $height_ratio;								// shrink height
			}
			else if ($img_height > $thumb_height && $img_width > $thumb_width)
			{
			$new_width = $img_width * $width_ratio;									// shrink width 
			$new_height = $img_height * $width_ratio;								// shrink height	
			}	
		}

   		$dst_img = imagecreatetruecolor($new_width,$new_height);
    	imagecopyresized($dst_img,$src_img,0,0,0,0,$new_width,$new_height,imagesx($src_img),imagesy($src_img));
	imagejpeg($dst_img, "uploads/$thumb_file_name", $img_quality);
?>

Link to comment
Share on other sites

I have tried your code and I know that some combinations of height and with does not work out. For example does an image which is 150x80 px (width x height) resize to

159x84 px.

 

What do you actually wanna do? If you wanted to resize an image to fit within a maximum width and maximum height you would use what I posted since it's the simplest and most logic way of doing such a resize. But since you don't you must want something else...

 

What exactly are you trying to do?

Link to comment
Share on other sites

You have it right that i am trying to do what you think i am. I just tried your code, and it does not work.

 

here are the errors:

 

Warning: Division by zero in /home/content/w/i/u/wiuartinny/html/upload_action.php on line 92

 

Warning: Division by zero in /home/content/w/i/u/wiuartinny/html/upload_action.php on line 93

 

Warning: imagecreatetruecolor(): Invalid image dimensions in /home/content/w/i/u/wiuartinny/html/upload_action.php on line 112

 

Warning: imagecopyresized(): supplied argument is not a valid Image resource in /home/content/w/i/u/wiuartinny/html/upload_action.php on line 113

 

Warning: imagejpeg(): supplied argument is not a valid Image resource in /home/content/w/i/u/wiuartinny/html/upload_action.php on line 114

 

Warning: Cannot modify header information - headers already sent by (output started at /home/content/w/i/u/wiuartinny/html/upload_action.php:92) in /home/content/w/i/u/wiuartinny/html/upload_action.php on line 172

 

Like I said, my code works. It may not be the most simple and elegant solution, but it does work. I really just am trying to figure out why images that are shorter than the max size but wider than the max width do not scale down. They dont scale up either, but remain thier oirginal size.

 

Link to comment
Share on other sites

I can't explain why you code does not work... You have an option specified for the case which does not seem to work. But I do not understand your calculations.

 

Regarding the code I posted I didn't say it was copy'n'paste ready. I only meant the resize mechanism. It has even been represented in a book:

http://wuhtzu.dk/random/php_and_mysql_web_development_c26_p560.jpg

http://wuhtzu.dk/random/php_and_mysql_web_development_c26_p561.jpg

 

 

And to demonstrate it works you can have a look at these to images:

 

http://wuhtzu.dk/sandbox/imagemanipulator/image.php?img=100x600.jpg&max_w=600&max_h=600

http://wuhtzu.dk/sandbox/imagemanipulator/image.php?img=600x100.jpg&max_w=3000&max_h=600

(or any of the images at http://wuhtzu.dk/sandbox/imagemanipulator/image.php)

 

If max_w and max_h specifies maximum height and maximum width of the image you want created. If you can make any of these images (the two linked to or any other from the list) break the resize mechanism please let me know.

 

Link to comment
Share on other sites

I understood that it wasnt copy and paste ready I modified my code to use what you had posted. I apologize that what i have is confusing to you.  I know what i have works. There is probably no chance that a user of my site will even upload an image with the aspect ratio that isn't working . However I would like to get the code I wrote working 100 percent not 99%. So I apreciate your input and it has already helped my improve my code. I am just going to keep working at it to see if i can figure out.

 

I have been printing out the shrunken aspect ratio before the code finishes and the code is creating the correct new ratio, but when the xode finished executing for some reason for the images that are shorter than the thumbnail height and wider than the thumbnail width they are still being saved aa thier original size

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.