Get best price on Unlocked Samsung Galaxy A21 | ||||||||||||
|
||||||||||||
|
PHP: Upload and Resize an ImageYou created a cool contact directory and you want to allow people to upload their own photos or you want to create an image repository which you upload images and create thumbnails out of them. Whatever it is, you need to be able to upload images and resize them. PHP has the ability to upload files such as documents or images using the multipart/form-data protocol, but how do you use this and how do you resize the images after they are uploaded? What you need:
This script works only with JPEG images. Also I'll resize the uploaded image only if it is larger than 250x200. Else, I'll leave it as it is. Create Upload Form
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="25000"> Upload Image: <input type="file" name="imgfile"> <font size="1">Click browse to upload a local file</font> <input type="submit" value="Upload Image"> </form> Process Uploaded Data PHP uploads the file to a temp location on your server (defined in php.ini) It also includes the following:
NOTE: imgfile is the name given on the form Before copying the file, we check that a malicious user is not trying to abuse the script by trying to work on files it should
not be, such as /etc/passwd. We do this with the
PHP function is_uploaded_file(). More
detail about this function is at the PHP.net site.
if (is_uploaded_file($imgfile))
{ $newfile = $uploaddir . "/" . $final_filename"; if (!copy($imgfile, $newfile)) { // if an error occurs the file could not // be written, read or possibly does not exist print "Error Uploading File."; exit(); } } Re-Sizing the Uploaded Image
/*== where storing tmp img file ==*/
$tmpimg = tempnam("/tmp" "MKPH"); $newfile = "$uploaddir/scaled.jpg"; /*== CONVERT IMAGE TO PNM ==*/ if ($ext == "jpg") { system("djpeg $imgfile >$tmpimg"); } else { echo("Extension Unknown. Please only upload a JPEG image."); exit(); } /*== scale image using pnmscale and output using cjpeg ==*/ system("pnmscale -xy 250 200 $tmpimg | cjpeg -smoo 10 -qual 50 >$newfile"); The above functions are just the basics of the script. There are a few little things added to complete the script. Such as checking the file extension, handling where to copy the file, and changing the upload filename. Download the complete Script Source Things to Look Out For
Relevant PHP Functions On php.net, there are User Contributed Notes for all PHP fuctions. These are incredibly helpful. I highly recommend them. Getting Required Software
|
privacy policy || © 1997-2016. astonishinc.com All Rights Reserved. |