PHP - Resizing Images Not Worth It?
I am using Amazon's S3 service to allow users to upload images. Since you have to pay for this service, my plan was to resize all uploaded images (maybe to a max of 200 pixels wide or something) immediately before sending them to Amazon.
I googled this and only thing I found said that "resizing on the fly is slow and expensive because disk space is cheaper than CPU." Is this accurate? Anyone have any thoughts on this? I feel like I have to restrict the size of images some way because I don't wan't people uploading huge 2000x2000 images. In case it matters, below is some code I have used below for resizing (albeit on my own server), so I imagine I'll use something similar for this new project which ultimately sends the image to Amazon. Code: [Select] // This is the temporary file created by PHP $uploadedfile = $_FILES['userfile']['tmp_name']; // Create an Image from it so we can do the resize $src = imagecreatefromjpeg($uploadedfile); // Capture the original size of the uploaded image list($width,$height) = getimagesize($uploadedfile); $newheight=70; $newwidth= 70; $tmp=imagecreatetruecolor($newwidth,$newheight); // this line actually does the image resizing, copying from the original // image into the $tmp image imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); // now write the resized image to disk. I have assumed that you want the // resized, uploaded image file to reside in the ./images subdirectory. $imagefolder = 'images/userimages/user' . $_SESSION['userid'] . '.jpg'; $filename = $imagefolder; $_SESSION['filename'] = $filename; if (imagejpeg($tmp,$imagefolder,100)) { $imagemessage = "File is valid, and was successfully uploaded into FOLDER.\n"; $success="yes"; } else { $imagemessage = "Possible file upload attack!\n"; $success="no"; } imagedestroy($src); imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request // has completed. } Similar TutorialsHi, I have a pretty simple application that allows my users to upload images and i'm able to succesfull upload images to a new dir to be outputted. But as to save on download time and server space is there a simple piece of code I can add to the below code that will resize every image on uploded to 460(w) x 300 (h) from my users Code: [Select] <?php if ((($_FILES["article_image"]["type"] == "image/gif") || ($_FILES["article_image"]["type"] == "image/jpeg") || ($_FILES["article_image"]["type"] == "image/pjpeg")) && ($_FILES["article_image"]["size"] < 5000000)) { move_uploaded_file($_FILES["article_image"]["tmp_name"], "images/" . $_FILES["article_image"]["name"]); } ?> Thanks in advance for any help and suggestions I am absolutley stumped with this: im trying to have PHP get the size of an image that has been uploaded to mySQL, and return it to a certain size, lets say 200X200px. The problems im having to finding an existing script to help me understand - and then fit it into a table? All the help from google searches seem to suggest using software, but i would like to learn how to do this properly. First off the upload script: Code: [Select] <?php error_reporting(E_ALL); ini_set("display_errors", 1); echo '<pre>' . print_r($_FILES, true) . '</pre>'; //This is the directory where images will be saved $target = "/home/users/web/b109/ipg.removalspacecom/images/COMPANIES"; $target = $target . basename( $_FILES['upload']['name']); //This gets all the other information from the form $company_name=$_POST['company_name']; $basicpackage_description=$_POST['basicpackage_description']; $location=$_POST['location']; $postcode=$_POST['postcode']; $upload=($_FILES['upload']['name']); // Connects to your Database mysql_connect("server", "user", "password") or die(mysql_error()) ; mysql_select_db("removalspacelogin") or die(mysql_error()) ; //Writes the information to the database mysql_query("INSERT INTO `Companies` (company_name, basicpackage_description, location, postcode, upload) VALUES ('$company_name', '$basicpackage_description', '$location', '$postcode', '$upload')") ; echo mysql_error(); //Writes the photo to the server if(move_uploaded_file($_FILES['upload']['tmp_name'], $target)) { //Tells you if its all ok echo "The file ". basename( $_FILES['upload']['name']). " has been uploaded, and your information has been added to the directory"; } else { //Gives and error if its not echo "Sorry, there was a problem uploading your file."; } ?> this works great, it uploads the users pictures. This displays them out: Code: [Select] <?php $database="removalspacelogin"; mysql_connect ("server", "user", "password"); @mysql_select_db($database) or die( "Unable to select database"); $result = mysql_query( "SELECT company_name, location, postcode, basicpackage_description, premiumuser_description, upload FROM Companies" ) or die("SELECT Error: ".mysql_error()); $num_rows = mysql_num_rows($result); print "\n\n\nThere are $num_rows records.<P>"; echo "<table><tr><th>Comppany Name</th><th>Location</th><th>Postcode</th><th>Basic Members</th><th>Upgraded Users</th><th>Company Logo</th></tr><tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>";// store the records into $row array and loop through while ( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) ) { // Print out the contents of the entry echo "<tr><td>{$row['company_name']}</td>"; echo "<td>{$row['location']}</td>"; echo "<td>{$row['postcode']}</td>"; echo "<td>{$row['basicpackage_description']}</td>"; echo "<td>{$row['premiumuser_description']}</td>"; echo "<td><img src=\"http://www.removalspace.com/images/COMPANIES{$row['upload']}\" alt=\"logo\" /></td></tr>";} echo "</table>"; ?> Right now all the information in my table is fine except the image coloumn, the images are all the same size as they went in, i'd like them to all be one size so there in a uniformed fashion. But need all the rest of the mySQL table displayed, so how does it fit into my script to display the table? Many thanks!??? Please, I need help with resizing uploaded images. Copied below is the code for image upload ( which I tagged "upload.php") Code: [Select] <?php // define a constant for the maximum upload size define ('MAX_FILE_SIZE', 51200); if (array_key_exists('upload', $_POST)) { // define constant for upload folder define('UPLOAD_DIR', 'C:/upload_test/'); // convert the maximum size to KB $max = number_format(MAX_FILE_SIZE/1024, 1).'KB'; // create an array of permitted MIME types $permitted = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png'); foreach ($_FILES['image']['name'] as $number => $file) { // replace any spaces in the filename with underscores $file = str_replace(' ', '_', $file); // begin by assuming the file is unacceptable $sizeOK = false; $typeOK = false; // check that file is within the permitted size if ($_FILES['image']['size'][$number] > 0 || $_FILES['image']['size'][$number] <= MAX_FILE_SIZE) { $sizeOK = true; } // check that file is of an permitted MIME type foreach ($permitted as $type) { if ($type == $_FILES['image']['type'][$number]) { $typeOK = true; break; } } if ($sizeOK && $typeOK) { switch($_FILES['image']['error'][$number]) { case 0: // check if a file of the same name has been uploaded // if (!file_exists(UPLOAD_DIR.$file)) { // move the file to the upload folder and rename it $success = move_uploaded_file($_FILES['image']['tmp_name'][$number], UPLOAD_DIR.$file); // } /* else { // get the date and time ini_set('date.timezone', 'Europe/London'); $now = date('Y-m-d-His'); $success = move_uploaded_file($_FILES['image']['tmp_name'][$number], UPLOAD_DIR.$now.$file); }*/ if ($success) { $result[] = "$file uploaded successfully"; } else { $result[] = "Error uploading $file. Please try again."; } break; case 3: $result[] = "Error uploading $file. Please try again."; default: $result[] = "System error uploading $file. Contact webmaster."; } } elseif ($_FILES['image']['error'][$number] == 4) { $result[] = 'No file selected'; } else { $result[] = "$file cannot be uploaded. Maximum size: $max. Acceptable file types: gif, jpg, png."; } } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Multiple file upload</title> </head> <body> <?php // if the form has been submitted, display result if (isset($result)) { echo '<ol>'; foreach ($result as $item) { echo "<strong><li>$item</li></strong>"; } echo '</ol>'; } ?> <form action="" method="post" enctype="multipart/form-data" name="multiUpload" id="multiUpload"> <p> <label for="image1">File 1:</label> <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE; ?>" /> <input type="file" name="image[]" id="image1" /> </p> <p> <label for="image2">File 2:</label> <input type="file" name="image[]" id="image2" /> </p> <p> <input name="upload" type="submit" id="upload" value="Upload files" /> </p> </form> </body> </html> This works fine , except that it only uploads to C:/upload_test instead of the images folder (../img/) Can you please help with the codes for creating thumbnails while retaining the original upload. Thanks Hi I am trying to resize images as they are uploaded. The problem I have is that the image is uploading and adding to the database, but is not resizing. The code I am using is below Code: [Select] <?php include("config.inc.php"); include('../includes/connect_inc.php'); // initialization $result_final = ""; $counter = 0; // List of our known photo types $known_photo_types = array( 'image/pjpeg' => 'jpg', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/bmp' => 'bmp', 'image/x-png' => 'png' ); // GD Function List $gd_function_suffix = array( 'image/pjpeg' => 'JPEG', 'image/jpeg' => 'JPEG', 'image/gif' => 'GIF', 'image/bmp' => 'WBMP', 'image/x-png' => 'PNG' ); // Fetch the photo array sent by add-photos.php $photos_uploaded = $_FILES['photo_filename']; // Fetch the photo caption array $photo_caption = $_POST['photo_caption']; while( $counter <= count($photos_uploaded) ) { if($photos_uploaded['size'][$counter] > 0) { if(!array_key_exists($photos_uploaded['type'][$counter], $known_photo_types)) { $result_final .= "File ".($counter+1)." is not a photo<br />"; } else { mysql_query( "INSERT INTO gallery_photos(`photo_filename`, `photo_caption`, `photo_category`) VALUES('0', '".addslashes($photo_caption[$counter])."', '".addslashes($_POST['category'])."')" ); $new_id = mysql_insert_id(); $filetype = $photos_uploaded['type'][$counter]; $extention = $known_photo_types[$filetype]; $filename = $new_id.".".$extention; mysql_query( "UPDATE gallery_photos SET photo_filename='".addslashes($filename)."' WHERE photo_id='".addslashes($new_id)."'" ); //resize photos to maximum height or width //define parameters - maximum height & width for new images $image_max_width=599; $image_max_height=599; $max_dimension=800; // Grab the width and height of the image. list($width,$height) = getimagesize($_FILES['photo_filename']); // If the max width input is greater than max height we base the new image off of that, otherwise we // use the max height input. // We get the other dimension by multiplying the quotient of the new width or height divided by // the old width or height. if($image_max_width > $image_max_height){ if($image_max_width > $max_dimension){ $newwidth = $max_dimension; } else { $newwidth = $image_max_width; } $newheight = ($newwidth / $width) * $height; } else { if($image_max_height > $max_dimension){ $newheight = $max_dimension; } else { $newheight = $image_max_height; } $newwidth = ($newheight / $height) * $width; } // Create temporary image file. $tmp = imagecreatetruecolor($newwidth,$newheight); // Copy the image to one with the new width and height. imagecopyresampled($tmp,$image,0,0,0,0,$newwidth,$newheight,$width,$height); //end of resizing // Store the orignal file copy($photos_uploaded['tmp_name'][$counter], $images_dir."/".$filename); // Let's get the Thumbnail size $size = GetImageSize( $images_dir."/".$filename ); if($size[0] > $size[1]) { $thumbnail_width = 100; $thumbnail_height = (int)(100 * $size[1] / $size[0]); } else { $thumbnail_width = (int)(100 * $size[0] / $size[1]); $thumbnail_height = 100; } // Build Thumbnail with GD 1.x.x, you can use the other described methods too $function_suffix = $gd_function_suffix[$filetype]; $function_to_read = "ImageCreateFrom".$function_suffix; $function_to_write = "Image".$function_suffix; // Read the source file $source_handle = $function_to_read ( $images_dir."/".$filename ); if($source_handle) { // Let's create an blank image for the thumbnail $destination_handle = ImageCreate ( $thumbnail_width, $thumbnail_height ); // Now we resize it ImageCopyResized( $destination_handle, $source_handle, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $size[0], $size[1] ); } // Let's save the thumbnail $function_to_write( $destination_handle, $images_dir."/tb_".$filename ); ImageDestroy($destination_handle ); // $result_final .= "<img src='".$images_dir. "/tb_".$filename."' /> File ".($counter+1)." Added<br />"; } } $counter++; } header('Location: add-photos.php'); // Print Result echo <<<__HTML_END <html> <head> <title>Photos uploaded</title> </head> <body> $result_final </body> </html> __HTML_END; ?> Any help would be appreciated. I am looking to resize images from a database and found this guide. It looks relatively simple. Is this the easiest method of resizing images. http://articles.sitepoint.com/article/image-resizing-php Hi I'm trying to setup Pagination at the bottom of the page after showing 10 images in the following script but have no clue where to start and how to implement it into the script. I am trying to upload files to a user profile system. here is the profile page Code: [Select] <?php include('core/init.inc.php'); if (isset($_POST['email'], $_POST['location'], $_POST['about'])) { $errors = array(); if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) { $errors[] = "The email address you entered is not valid"; } if(preg_match('#^[a-z0-9 ]+$#i',$_POST['location'])===0) { $errors[] = 'Your location must only contain A-Z 0-9 and spaces.'; } if (empty($_FILES['avatar']['tmp_name']) === false) { $file_ext = end(explode('.', $_FILES['avatar']['name'])); if(in_array(strtolower($file_ext), array('jpg', 'jpeg', 'gif', 'png')) === false) { $errors[] = 'Your avatar must be an image.'; } } if(empty($errors)) { print_r($_FILES); set_profile_info($_POST['email'],$_POST['location'],$_POST['about'], (empty($_FILES['avatar']['tmp_name'])) ? false : $_FILES['avatar']['tmp_name']); } $userinfo = array( 'email' => htmlentities($_POST['email']), 'location' => htmlentities($_POST['location']), 'about' => htmlentities($_POST['about']) ); } else { $userinfo = fetch_user_info($_SESSION['uid']); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Edit your Profile</title> </head> <body> <div> <?php if(isset($errors) == false) { echo 'Click update to edit your profile.'; } else if(empty($errors)) { echo 'Your profile has been updated.'; } else { echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>'; } ?> </div> <form action="" method="post" enctype="multipart/form-data"> <div> <label for="email">Email: </label> <input type="text" name="email" id="email" value="<?php echo $userinfo['email']; ?>" /> </div> <div> <label for="location">Location: </label> <input type="text" name="location" id="location" value="<?php echo $userinfo['location']; ?>" /> </div> <div> <label for="about">About Me: </label> <textarea name="about" id="about" rows="14" cols="50"><?php echo strip_tags($userinfo['about']); ?></textarea> </div> <div> <label for="avatar">Avatar: </label> <input type="file" name="avatar" id="avatar"/> </div> <div> <input type="submit" value="Update" /> </div> </form> </body> </html> here is the function taken from an external file Code: [Select] function set_profile_info($email, $location,$about,$avatar) { $email = mysql_escape_string(htmlentities($email)); $about = mysql_escape_string(nl2br(htmlentities($about))); $location = mysql_escape_string($location); if (file_exists($avatar)) { $src_size = getimagesize($avatar); if ($src_size['mime'] === 'image/jpeg') { $src_img = imagecreatefromjpeg($avatar); } else if ($src_size['mime'] === 'image/png') { $src_img = imagecreatefrompng($avatar); } else if ($src_size['mime'] === 'image/gif') { $src_img = imagecreatefromgif($avatar); } else { $src_img = false; } if ($src_img !== false) { $thumb_width= 200; if($src_size[0] <= $thumb_width) { $thumb = $src_img; } else { $new_size[0] = $thumb_width; $new_size[1] = ($src_size[1] / $src_size[0]) * $thumb_width; $thumb = imagecreatetruecolor($new_size[0], $new_size[1]); imagecopyresampled($thumb, $src_img, 0, 0, 0, 0, $new_size[0], $new_size[1], $src_size[0], $src_size[1]); } imagejpeg($thumb, "{$GLOBALS['path']}/user_avatars/{$_SESSION['uid']}.jpg"); } } $sql = "UPDATE `users` SET `user_email` = '{$email}', `user_about` = '{$about}', `user_location` = '{$location}' WHERE `user_id` = {$_SESSION['uid']}"; mysql_query($sql); } Below I have returned the array of files to check if its been uploaded correctly. Array ( [avatar] => Array ( [name] => Sonic.jpg [type] => image/jpeg [tmp_name] => /var/tmp/php.waq8n [error] => 0 [size] => 48477 ) ) But I get this error message. Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: '/var/tmp/php.waq8n' is not a valid JPEG file in /web/stud/u0963643/userprofilesection/finaluserprofile/core/inc/user.inc.php on line 71 If someone could point out where in this code I have made an error I would be very grateful Thanks Jamie Little topic that's gonna bug me if I don't ask
I'm trying to learn static layouts, and I'm just getting the hang of them. A few friends are telling me to go responsive to accommodate mobile/tablet users? I can see it from a business sites perspective where you want all types of users and with ease of access, but my site is going to be a gaming modification community, where mobile users aren't really the target audience as it's quicker and easier to download them on the PC than a Phone. I was going to accommodate that audience by allowing them very basic usage (chat, forums, account) and leave off the heavy parts like the gallery, and downloads.
Am I going in the wrong direction? Should I be heading down the responsive route? I've literally only just started the first page for the site, but it'd mean re-learning a whole bunch more new stuff which'd prolong the sites progress.
Just looking for a little advice in which direction to head
So I've been using this websocket: http://code.google.com/p/phpwebsocket/
Love it because I don't know javascript as well as I do PHP. (Absolutely hated learning socket.io and their style of javascript, just gave up on it).
Anyways, I'm using MYSQL with the php socket for the chatroom authentication with my forum. (Sending the cookie values to the socket, to authenticate user). It's working fine and the MYSQL only get's called for each time a user is authenticated (logged into the websocket). The usernames and sessions are actually stored in a Temporary array which is nice. So only on authentication it queries the database for the authentication itself. (Very lightweight and a smart way for a chat system).
My question is, how does this compare to a node.js and socket.io server with a MYSQL plugin, etc? seems like that route would actually be more intensive?
I don't even need to include the socket.io.js for the client / PHP setup I have here as well. This way seems lightweight in my opinion (clientside) but not sure on the server end.
Thoughts?
TLDR: Running a PHP Websocket as compared to a node.js/socket.io server with mysql plugins the same in performance? Is it even noticeable? Should I be worried?
Edit: Disregard compatibility issues too. ( Using this http://tools.ietf.org/html/rfc6455 protocol is fine for my audience and intentions )
Edited by Monkuar, 02 December 2014 - 07:46 PM. I am trying to get a website up for my mother and am running into so many brick walls. There is so much i dont know about php. I know basics. What i would really love is some to try to tutor me through what i need to know. If anyone could do this for me i would be forever grateful. I have started learning OOP, by following a few tutorials, My problem with most tutorial is they show you how, but don't tell you the what and the why. It's all good an well seeing what to do, but if you have no idea why it's being done, you don't learn much. I started a tutorial on Udemy but am not actually gaining a lot from it. I want to alter the code so that it will do it the way I want it to. I am not wanting you to write the code for me, if you do please explain it so that I can understand the logic, preferably show me where to make changes and point me at the php tutorial that can solve my problem. I have been trying to solve this for a couple of weeks now, I tried a few things but none worked.
The full followLinks function function followLinks($url) { global $alreadyCrawled; global $crawling; $host = parse_url($url)["host"]; $parser = new DomDocumentParser($url); $linkList = $parser->getLinks(); foreach($linkList as $link) { $href = $link->getAttribute("href"); if((substr($href, 0, 3) !== "../") AND (strpos($href, $host) === false)) { continue; } else if(strpos($href, "#") !== false) { continue; } else if(substr($href, 0, 11) == "javascript:") { continue; } // I need to change this below somehow, the two arrays are identical, // What I want to do is move $href(crawled) to $alreadyCrawled and remove it from $crawling // I also want to check if the current $href (crawling) is in $alreadyCrawled and if it is skip crawling and move on to the next one. //In essence I want to prevent the crawler from crawling anything already crawled in order to speed up the crawler. $href = createLink($href, $url); if(!in_array($href, $alreadyCrawled)) { $alreadyCrawled[] = $href; $crawling[] = $href; } else { continue;} echo $href . "<br>"; } array_shift($crawling); foreach($crawling as $site) { followLinks($site); } } $startUrl = "https://imagimedia.co.za"; followLinks($startUrl); ?>
Result.
https://imagimedia.co.za/../seo/ https://imagimedia.co.za/../pages/marketing.html https://imagimedia.co.za/../pages/web-design.html http://imagimedia.co.za/ https://imagimedia.co.za/../website-cost-quote.php https://imagimedia.co.za/../blogs/history.html https://imagimedia.co.za/../blogs/payment.html https://imagimedia.co.za/../blogs/copy.html https://imagimedia.co.za/../blogs/cycle.html https://imagimedia.co.za/../blogs/information.html https://imagimedia.co.za/../blogs/privacy.html https://imagimedia.co.za/../blogs/terms.html https://imagimedia.co.za/../blogs/content-is-king.html https://imagimedia.co.za/../blogs/pretoria-north-web-design.html https://imagimedia.co.za/../blogs/annlin-web-design.html https://imagimedia.co.za/../blogs/ http://imagimedia.co.za http://imagimedia.co.za/../seo/ http://imagimedia.co.za/../pages/marketing.html http://imagimedia.co.za/../pages/web-design.html http://imagimedia.co.za/../website-cost-quote.php http://imagimedia.co.za/../blogs/history.html http://imagimedia.co.za/../blogs/payment.html http://imagimedia.co.za/../blogs/copy.html http://imagimedia.co.za/../blogs/cycle.html http://imagimedia.co.za/../blogs/information.html http://imagimedia.co.za/../blogs/privacy.html http://imagimedia.co.za/../blogs/terms.html http://imagimedia.co.za/../blogs/content-is-king.html http://imagimedia.co.za/../blogs/pretoria-north-web-design.html http://imagimedia.co.za/../blogs/annlin-web-design.html http://imagimedia.co.za/../blogs/ I know I am also going to have to exclude duplicates created by the http and https pages. But that is not my main issue. I have a search going on: <?php $sql = "SELECT * FROM video WHERE MATCH(name,description,location,keywords) AGAINST('" . mysql_real_escape_string($_POST['searchfield']) . "' IN BOOLEAN MODE)"; ?> I have rows that contain either "fort worth" or "fort collins" for example. When I search "fort worth" it finds all the rows including the fort collins rows. That is expected as it contains "fort". The issue is "fort collins" is showing up before "fort worth" What can I do fix this? If I take out the "IN BOOLEAN MODE" part then it works, but breaks other parts of my search Hey guys, i have been creating a profile page for a site i am doing. When i upload an image the profile image gets resized to 150px x 150px (CSS) however you can imagine if the image isnt a perfect size it will be squashed. Is there anyway i can resize the image? so that it doesnt look squashed like keep the full size upload image but pass it through a function before it displays in the profile section? if someone could point me in the right direction that would be awesome. Thanks!! Sorry bit rusty but been trying this for hours I upload an image no errors are showing i upload a jpg file and it saves to the server fine but its saving the original size not the new resized image size any ideas?? Code: [Select] if (isset ($_FILES['file'])) { $tmp_name = $_FILES["file"]["tmp_name"]; $file_type = $_FILES["file"]["type"]; $fileatt_name = $_FILES["file"]["name"]; if ($file_type=="image/pjpeg" OR $file_type=="image/jpeg" OR $file_type=="image/jpg") { $src = imagecreatefromjpeg($tmp_name); } // END if ($file_type=="image/pjpeg" OR $file_type=="image/jpeg" OR $file_type=="image/jpg") if ($file_type=="image/png" OR $file_type=="image/x-png") { $src = imagecreatefrompng($tmp_name); } // END if ($file_type=="image/png" OR $file_type=="image/x-png") if ($file_type=="image/gif") { $src = imagecreatefromgif($tmp_name); } // END if ($file_type=="image/gif") list($width,$height)=getimagesize($tmp_name); $width = $width; $height = $height; $newwidth = "200"; $newheight = "200"; $ratio=''; if($width==$height) { $newwidth = "200"; $newheight = "200"; } if($width>$height) { $ratio=($height/$width); $newwidth = "200"; $newheight = ($newwidth*$ratio); } if($width<$height) { $ratio=($width/$height); $newheight = "200"; $newwidth = ($newheight*$ratio); } $tmp = imagecreatetruecolor($newwidth, $newheight); $new=imagecopyresampled($tmp, $src,0,0,0,0,$newwidth,$newheight,$width,$height); $filename = "./yxy/". $fileattt_name; imagejpeg($tmp,$filename,100); imagedestroy($tmp); } Having a nightmare here lol $img->set_size(225); That is resizing the image with a maximum width but i need to resize it to make it have a maximum height but can't figure out how to do it Here's my full code if you want to see it: Code: [Select] <?php include("class.imaging.php"); // The file $dir = "upload/"; $file = $newfile; $filename = $dir . $file; $img = new imaging; $img->set_img($filename); $img->set_quality(120); // Profile Picture $img->set_size(225); $img->save_img("upload/thumb/" . $file); $img->clear_cache(); ?> i have a script that uses simple file function to upload images.. is der a way i can sumhow select multiple files and use them to upload.. or is there a way i can resize or reduced the size of the image as its being uploaded.. if yes please guide me through! i use simple form to upload the file and use the following file to upload move_uploaded_file($_FILES['img']['tmp_name'], "images/albums/{$_FILES['img']['name']}"); Hey everyone. I have been trying to make a script that allows me to resize an image but I am having some trouble. I have got a script that takes an image and resize's it: Code: [Select] <?php $save = $_REQUEST['SavedAs'] ; $file = $_REQUEST['ImgAdd'] ; echo "Creating file: $save"; $size = 0.45; header('Content-type: image/jpeg') ; list($width, $height) = getimagesize($file) ; $modwidth = 240; $modheight = 180; $tn = imagecreatetruecolor($modwidth, $modheight) ; $image = imagecreatefromjpeg($file) ; imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ; imagejpeg($tn, $save, 100) ; header ("Location: $save"); ?> But depending on the image, the aspect ratio looks wrong. Is there anyway to take an image, crop it, then resize it? Or something that makes it look decent? Thanks Hello: I have a photo uploader in my admin area. First time I tried this so it's new to me. The upload form sends it to the page below, and does the resizing and saving. It seems to automatically resize the photos to make thumbnails, which is really nice. However, I am trying to do 2 things and can't figure it out. 1 - I would like to resize the main photo and not the thumbnail (or just use the thumbnail as the main photo, whichever seems easier). I would like it to be 690px wide but let it scale in proportion to what the height should be (not set a height as I think that's what it is doing now). This is the area where it gets resized: Code: [Select] { $thumbnail_width = 690; $thumbnail_height = (int)(100 * $size[1] / $size[0]); } else { $thumbnail_width = (int)(690 * $size[0] / $size[1]); $thumbnail_height = 100; } Also, the thumbnails are coming out very dark and de-colored. How can I set it so it retains all the color and clarity, but just resizes them? Point I'm trying to do is just resize upon upload, as most of my clients do not and will not resize photos before uploading them, and that means each photo from a digital camera will be about 1.3 MBs, which starts to make a photo gallery page very heavy and clunky. This is the full code, if it will help: Code: [Select] <?php // initialization $result_final = ""; $counter = 0; // List of our known photo types $known_photo_types = array( 'image/pjpeg' => 'jpg', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/bmp' => 'bmp', 'image/x-png' => 'png' ); // GD Function List $gd_function_suffix = array( 'image/pjpeg' => 'JPEG', 'image/jpeg' => 'JPEG', 'image/gif' => 'GIF', 'image/bmp' => 'WBMP', 'image/x-png' => 'PNG' ); // Fetch the photo array sent by preupload.php $photos_uploaded = $_FILES['photo_filename']; // Fetch the photo caption array $photo_caption = $_POST['photo_caption']; while( $counter <= count($photos_uploaded) ) { if($photos_uploaded['size'][$counter] > 0) { if(!array_key_exists($photos_uploaded['type'][$counter], $known_photo_types)) { $result_final .= "File ".($counter+1)." is not a photo<br />"; } else { mysql_query( "INSERT INTO gallery_photos(`photo_filename`, `photo_caption`, `photo_category`) VALUES('0', '".addslashes($photo_caption[$counter])."', '".addslashes($_POST['category'])."')" ); $new_id = mysql_insert_id(); $filetype = $photos_uploaded['type'][$counter]; $extention = $known_photo_types[$filetype]; $filename = $new_id.".".$extention; mysql_query( "UPDATE gallery_photos SET photo_filename='".addslashes($filename)."' WHERE photo_id='".addslashes($new_id)."'" ); // Store the orignal file copy($photos_uploaded['tmp_name'][$counter], $images_dir."/".$filename); // Let's get the Thumbnail size $size = GetImageSize( $images_dir."/".$filename ); if($size[0] > $size[1]) //{ //$thumbnail_width = 100; //$thumbnail_height = (int)(100 * $size[1] / $size[0]); //} //else //{ //$thumbnail_width = (int)(100 * $size[0] / $size[1]); //$thumbnail_height = 100; //} { $thumbnail_width = 690; $thumbnail_height = (int)(500 * $size[1] / $size[0]); } else { $thumbnail_width = (int)(690 * $size[0] / $size[1]); $thumbnail_height = 500; } // Build Thumbnail with GD 1.x.x, you can use the other described methods too $function_suffix = $gd_function_suffix[$filetype]; $function_to_read = "ImageCreateFrom".$function_suffix; $function_to_write = "Image".$function_suffix; // Read the source file $source_handle = $function_to_read ( $images_dir."/".$filename ); if($source_handle) { // Let's create an blank image for the thumbnail $destination_handle = ImageCreate ( $thumbnail_width, $thumbnail_height ); // Now we resize it ImageCopyResized( $destination_handle, $source_handle, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $size[0], $size[1] ); } // Let's save the thumbnail $function_to_write( $destination_handle, $images_dir."/tb_".$filename ); ImageDestroy($destination_handle ); // $result_final .= "<img src='".$images_dir. "/tb_".$filename."' style='margin-right: 20px;' />"; } } $counter++; } // Print Result echo <<<__HTML_END $result_final __HTML_END; ?> Anyone know how to fix this? Thanks. As a point of curiosity, I am seeking some clarification. I have developed code to resize an image, thus reducing the file size by a percentage of it's original. My first question is, what exactly is being done to the file? I understand that some data is being removed (or condenced) but how does this effect the image when compared with the original on a webpage? Next, what should my expectation be if I wanted to reverse the process? If I am 'shrinking' an image for a faster upload speed and reduced storage capacity, how successful will I be if I wanted to 'restore' the file size before printing a physical photograph? Will this provide a 'better' end result?
Hi I have create a script that adds a image as blob successfully, however now I want to create a thumbnail, I have the following code; can someone help... # open and code into blob $fp = fopen($safename, 'r'); $content = fread($fp, filesize($safename)); $thumb = $content; $content = addslashes($content); fclose($fp); # resize accordingly... $thumb = new resize($content, $width, $height, 300); # the class that does the resizing (WHERE I THINK ITS GONE WRONG) class resize { public $new_image_blob = ""; function __construct($blob, $width, $height, $amount) { # the maximum width and height as set by the user $thumb_height_max = $amount; $thumb_width_max = $amount; # maintain aspect ratio landscape or portrait if($width < $height) { $new_width = ($thumb_height_max / $height) * $width; $new_height = $thumb_height_max; $needtoresize = ($height < $thumb_height_max); } else { $new_width = $thumb_width_max; $new_height = ($thumb_width_max / $width) * $height; $needtoresize = ($width < $thumb_width_max); } # now that we have the new width and heightwe need to resize the blob $im = imagecreatefromstring($blob); $thumb = imagecreatetruecolor($new_width, $new_height); imagecopyresampled($thumb, $im, 0, 0, 0, 0, $new_width, $new_height, ImageSX($im), ImageSY($im)); $this->new_image_blob = addslashes($thumb); } } # then the query below adds the code (the original blob goes in correctly (ablob) but bblob (the resized blob doesn't)) $iS = "INSERT INTO $tableb (pal, afield, bfield, cfield, dfield, efield, ffield, gfield, ablob, bblob, cblob, dblob) VALUES ('6', '$fk', '$filename', '$size', '$fileExtension', '$width', '$height', '$orientation', '$content', '$thumb->new_image_blob', '$four', '$two')"; |