Home » DobibeHow » How to Up Load and Resize Images Using PHP

How to Up Load and Resize Images Using PHP

Complete Example For A PHP Resizing Up Loader code

This PHP tutorial is complete with a free working example code. The picture below shows what the code will output. This script is heavily commented and changeable. It will upload a full image into the program, give you the HTML code to display on your website and show you a preview of the image in the size you select.  If ‘Resized Image’ is checked, will resize image; if not, will upload the image with no resize. The code can resize gif, png, and jpg images.

Code won’t work

If you are running this on your local host. And the image won’t resize. Make sure the PHP’s GD libray is installed.

Example Php Code

 

<?php


//This code is free from dobibe.com
//When a file is uploaded with the name image.
//This is the array that posted.
// So I put them in some variables we can use.

$filerror= $_FILES[“image”][“error”];
$filename= $_FILES[“image”][“name”];
$filetype= $_FILES[“image”][“type”];
$filesize= $_FILES[“image”][“size”];
$filetemp= $_FILES[“image”][“tmp_name”];

// Put images extensions that we want to allow in a array.
//Pjpeg and x-png is what shows in $filetype.

$allowedExts= array(“jpg”, “jpeg”, “gif”, “png”, “pjpeg”, “x-png”, “JPG”);

 


//This shows 7 mb in bytes 7340032 max size of image.

$allowedsize= (7*1024*1024);

// The directory path were to save the image.
// You need a folder named same as $dir.
// Change this as needed.

$dir=”images_a/”;

// This is if you want to change uploaded file name.
$newfilename=$filename;

//Max height in pixels width is relative.
//Change this as needed.

$maxh=$_POST[‘height’];
$maxsize=”300″;

//The complete path for the <img tag not needed just part of the code.
$url=”http://yourwebsite.com/images_a/”;

//Uses alt text filed in the form if not filled out.
//Uses $newfilename variable as the alternative text for the <img tag.

$altvalue=”If not changed will be file name”;
if($_POST[‘alt’]==$altvalue){$alt=$newfilename;}else{ $alt=$_POST[‘alt’];}

?>

<!–This code will send the form to it self. –><form action=”<?php echo htmlentities($_SERVER[‘PHP_SELF’]); ?>” method=”post”
enctype=”multipart/form-data”>
<label for=”file”>File Name Image:</label>
<input type=”file” name=”image” id=”image”><br>
<label for=”height”>Height:</label>
<input name=”height” type=”text” value=”150″ size=”5″ maxlength=”5″>
<?php echo “Max size is “.$maxsize.” Px”; ?><br>
<label for=”Alt”>Alt</label>
<input type=”text” name=”alt” id=”alt” size=”50″ maxlength=”100″
value=”<?php echo $altvalue; ?>”><br>

<label>Resize Image:</label><input name=”resize” type=”checkbox” value=”yes” checked><br>
<input type=”submit” name=”submit” value=”Submit”>
</form>
<!–This code uses a free script from dobibe.com. –>
<?php

//Start of the code this will see if the code was uploaded.
//Echo or print the temp files infomation.
//The echos aren’t needed.
//But it is good to see how it looks and works.


if ($maxsize >= $maxh){
if ($_FILES[“image”][“tmp_name”]){
echo “Uploaded File Name: ” . $filename . “<br>”; //Could delete.
echo “Uploaded Type: ” . $filetype . “<br>”; //Could delete.
echo “Uploaded Size: ” . round($filesize/1024) . ” KB<br>”; //Could delete.
echo “Uploaded Temp File: ” . $filetemp.”<br><br>”; //Could delete.
Run_Function($nextfun=”1″,”n/a”,”n/a”,”n/a”);
} else {echo “Upload a file<br>”;}
} else {echo “Height Exceeds Max <br>”;}

//Start of Run Function

function Run_Function($nextfun,$value1,$value2,$value3)

{
global $dir,$filename,$filetype,$filesize,$allowedsize,

$allowedExts,$filerror,$newfilename,$filetemp,$maxh,$alt,$url;

//This function starts needed functions when called.
if ($nextfun==”1″){
Image1_Check($filename,$filetype,$filesize,$allowedsize,$allowedExts,$filerror);}
if ($nextfun==”2″){
Image2_Upload($dir,$newfilename,$filetemp);}
if ($nextfun==”3″){
Image3_Resize($dir,$newfilename,$maxh,$alt,$url);}
if ($nextfun==”4″ && $_POST[‘resize’] == “yes”){
Image4_Save($value1,$value2,$value3);}
}

//Start of Image1_Check


function Image1_Check($filename,$filetype,$filesize,$allowedsize,$allowedExts,$filerror) {
//Strips $filename to extension example (jpg).
$extname = end(explode(“.”, $filename));
//Strips $filetype to type example (pjpeg).
$exttype = end(explode(“image/”, $filetype));
//Compares upload file size to allowed size.
if ($filesize < $allowedsize)
{
//Looks for a match to the $allowedExts array from $filetype and $filename.
if (in_array($extname, $allowedExts)
&& in_array($exttype, $allowedExts))
{
if ($filerror > 0)
{
//Returns a file error if occured.

echo “Error: ” . $filerror . “<br>”;
}
else
{
//Starts next function #2
Run_Function($nextfun=”2″,”n/a”,”n/a”,”n/a”);
}
} else
{echo “Wrong: file extension <br>”;}
} else
{echo “Size: to big<br>”;}}

//Start of Image2_Upload


function Image2_Upload($dir,$newfilename,$filetemp){
//Checks for same file name in $dir folder.
if (file_exists($dir.$newfilename))
{
echo $newfilename.” already exists<br>”;
}
else
{
//Saves full size from the temp file to your $dir folder.
move_uploaded_file($filetemp,$dir.$newfilename);
//Starts next function #3.
Run_Function($nextfun=”3″,”n/a”,”n/a”,”n/a”);
}}

//Start of Image3_Resize


function Image3_Resize($dir,$newfilename,$maxh,$alt,$url) {
$file=$dir.$newfilename;
//Gets the full size image’s width and height.
list($width, $height) = getimagesize($file);
//This will calculate a height to match $maxh variable.
//And will calculate a relative width to keep the aspect ratio.

$percent=$height/$maxh;
$rewidth = round($width / $percent);
$reheight = round($height / $percent);
//Just displays calculated width and height
echo “Height: “.$reheight.”<br>”; //could delete
echo “Width: “.$rewidth.”<br>”; //could delete
//Displays uploaded image at the calculated size.
//Note no actual resizing has happend yet.

echo ‘<img src=”‘.$dir.$newfilename.'” alt=”‘.$alt.'” width=”‘.$rewidth.'” height=”‘.$reheight.'”><br>’;
//This text box well show the html code to desplay the image on any page.

echo ‘<textarea name=”box” cols=”50″ rows=”5″><img src=”‘.$url.$newfilename.'” alt=”‘.$alt.'” width=”‘.$rewidth.'” height=”‘.$reheight.'”></textarea><br>’;
//Starts next function #4.
Run_Function($nextfun=”4″,$rewidth,$reheight,$file);
}

//Start of Image4_Save


function Image4_Save($rewidth,$reheight,$file){
//This gets width height and file extension type.
//Returns 1 for gif, 2 for jpeg, 3 for png.

list($width, $height, $Ext) = getimagesize($file);

// Runs the matching program to file extension.
switch ($Ext)
{
case 1: $src = imagecreatefromgif($file); break;
case 2: $src = imagecreatefromjpeg($file); break;
case 3: $src = imagecreatefrompng($file); break;
default: return ”; break;
}

//The start of resizing image
$tmp = imagecreatetruecolor($rewidth,$reheight);

// Check for png or gif to preserve its transparency.

if(($Ext == 1) OR ($Ext==3))
{
imagealphablending($tmp, false);
imagesavealpha($tmp,true);
$transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127);
imagefilledrectangle($tmp, 0, 0, $rewidth, $reheight, $transparent);
}
//Creates the image to the new size.
imagecopyresampled($tmp,$src,0,0,0,0,$rewidth, $reheight,$width,$height);

//This switch will match the file name to the function..
//This function will replace the full size image,
//With the new resized one.

switch ($Ext)
{
case 1: imagegif($tmp, $file); break;
case 2: imagejpeg($tmp, $file, 100); break; // Best compression.
case 3: imagepng($tmp, $file, 0); break; // No compression.
default: echo ‘ ‘; break;
}
echo “Resized File Size: ” . round(filesize($file)/1024) . ” KB<br>”;
}

?>

</body>
</html>

Check Also

picture quote transitioning summer clothes

Transitioning Summer Clothes to Fall

Qwikbit by Dobibe Some tips on transitioning summer clothes to fall. Short sleeve or sleeveless …

Leave a Reply

Your email address will not be published. Required fields are marked *

19 − three =

Share on Pinterest Share
Share on Reddit Share
Share on Tumblr Share
Share on Vkontakte Share
Share on Buffer Share
Print this Print