How To: Resize Pictures in PHP

The web nowadays requires a level of interactivity never seen before. People love commenting and building communities, and a huge part of that is putting a face to your online presence. To this effect there is a big demand for image processing techniques using web based languages. My web language of choice is PHP and […]

The web nowadays requires a level of interactivity never seen before. People love commenting and building communities, and a huge part of that is putting a face to your online presence. To this effect there is a big demand for image processing techniques using web based languages. My web language of choice is PHP and so here is a short walkthrough, including code, on how to create a picture resizing function.

This function can both keep the aspect ratio of the picture, or force the picture to fit the new dimensions. It is designed for jpeg pictures but can easily be extended to cater for gif and png.

The first thing you need to do is create your form in your web page. This basically requires you to set a flag in the form tag like so:

<form name="myForm" action="uploadpic.php" method="post" enctype="multipart/form-data" />
The enctype flag basically tells the browser to break the form objects down and send in chunks. This is transparent to the user, and to the PHP script receiving the data. But is useful to know.

You will then need a form element with type "File" which will give you the typical input box with a browse button to allow your users to search for the file they want to upload.

<input name="userfile" type="file" size="40" />
Now we need a PHP file to receive the file, we are assuming you have a file called uploadpic.php, within your form handling code you should have something like this to call the function we are about to write:

if (@is_uploaded_file($_FILES["userfile"]["tmp_name"]))
{
$img_name = resizePic("player","userfile","../picupload/",150,150,0,"destination_name.jpg");
}
$_FILES is a server variable containing an array of the uploaded files, note that "userfile" is the name of the form element we specified earlier, the tmp_name is the temporary name given to the object when its uploaded. The first line basically confirms the file was uploaded ok. The second line calls our function resizePic and stores the contents into a variable called $img_name. The return value of the function is discussed later.

OK now onto our function definition, we saw the variables passed to it in the previous section of code, now we can see what each parameter does.

function uploadPic($prefix,$formSrc,$dDir,$maxWidth,$maxHeight,$resizeFlag,$tempName) ;
Continue to read full post....

How To, Resize Pictures in PHP