Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

PHP - upload and resize image

From Wiki
Jump to: navigation, search
Article Metadata
Article
Created: Maveric (31 Dec 2010)
Last edited: hamishwillee (31 Jul 2012)

Overview

PHP code for uploading an image to server and resizing it on the server with PHP. You can create a HTML page with a form, then use this script on the backend to process the image it receives and show the result back.

Source file

<?php 
error_reporting(1);
$swap="";
 
define ("MAX_SIZE","600");
 
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
 
$errors=0;
 
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$image =$_FILES["file"]["name"];
$uploadedfile = $_FILES['file']['tmp_name'];
 
 
if ($image)
{
 
$filename = stripslashes($_FILES['file']['name']);
 
$extension = getExtension($filename);
$extension = strtolower($extension);
 
 
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
 
$swap='<div class="msgdiv">Unknown Image extension </div> ';
$errors=1;
}
else
{
 
$size=filesize($_FILES['file']['tmp_name']);
 
if ($size > MAX_SIZE*1024)
{
$swap='<div class="msgdiv">File too big.</div> ';
$errors=1;
}
 
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
 
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
 
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
 
echo $scr;
 
list($width,$height)=getimagesize($uploadedfile);
 
$newwidth=60;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
 
$newwidth1=25;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
 
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
 
$filename = "uploads/". $_FILES['file']['name'];
$filename1 = "uploads/small". $_FILES['file']['name'];
 
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
 
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}
 
}
if(isset($_POST['Submit']) && !$errors)
{
$swap='<div class="msgdiv">Image Uploaded Successfully!</div>';
}
?>
This page was last modified on 31 July 2012, at 05:13.
277 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×