Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

image resize

Status
Not open for further replies.

gagz

Programmer
Nov 21, 2002
333
US
is there any way to get php to actually physically resize and image? ie make it a thumbnail?
 
gagz,

Yes, there's a way to do it. I wrote something that would let me upload a file and make a thumbnail of it that was either 60 pixels high or 60 pixels wide, depending on whether it was portrait or landscape.

here's a brief sample of how i did it:

1. in my form, i called the file field "img1." PHP has a bunch of built-in variables that it associates with an uploaded file, like its name and mime type, etc., which are all, thankfully, named things like $img1_name and $img1_type. you can read more about that on the php.net docs.

2. here's the php stuff. i hope it helps:

//create a full path to the newly uploaded file
$mypath = "/path/to/uploaded_file");
$working_file=("$mypath" . "$img1_name");

//write a tmp file using a different function depending on mime type
if ($img1_type=="image/jpeg") {
$src_img = imagecreatefromjpeg($working_file);
} elseif ($img1_type=="image/png") {
$src_img = imagecreatefrompng($working_file) or die("couldn't create image using imagecreatefrompng");
}

if (($img1_type=="image/jpeg") || ($img1_type=="image/png")) {
$orig_width = imagesX($src_img);
$orig_height = imagesY($src_img);

//if width is more than height, make width 60 pixels and
//make height proportional
if ($orig_width >= $orig_height) {
$new_w = 60;
$resize_factor = 60/$orig_width;
$new_h = $orig_height * $resize_factor;
} else {
//else use the height and make width proportional
$new_h = 60;
$resize_factor = 60/$orig_height;
$new_w = $orig_width * $resize_factor;
}

$dst_img = imagecreate($new_w,$new_h);
imagecopyresized($dst_img,$src_img,0,0,0,0,$new_w,$new_h,imagesX($src_img),imagesY($src_img));
//make a thumbnail using different functions based on mimetype of original
if ($img1_type=="image/jpeg") {
imagejpeg($dst_img, "../thumbnails/$img1_name");
} elseif ($img1_type=="image/png") {
imagepng($dst_img, "../thumbnails/$img1_name") or die("couldn't use imagepng");
}

echo &quot;<P>thumbnail:<br><a href=../uploaded_images/$img1_name><img src=/thumbnails/$img1_name></a><p>\n&quot;;

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top