I got a form where the user is inserting some data and also uploading an image.
To deal with the image, I got the following code:
define(\"MAX_SIZE\"
A full example with Zebra_Image library, that I think is so easy and useful. There are a lot of code, but if you read it, there are a lot of comments too so you can make copy and paste to use it quickly.
This example validates image format, size and replace image size with custom resolution. There is Zebra library and documentation (download only Zebra_Image.php file).
Explanation:
Main function
private function uploadImage() {
$target_file = "../img/blog/";
//this function could be in the same PHP file or class. I use a Helper (see bellow)
if(UsersUtils::uploadFile($target_file, $this->selectedBlog->getId())) {
//This function is at same Helper class.
//The image will be returned allways if there isn't errors uploading it, for this reason there aren't validations here.
$blogPhotoPath = UsersUtils::getUserFile($target_file, $this->selectedBlog->getId());
// create a new instance of the class
$imageHelper = new Zebra_Image();
// indicate a source image
$imageHelper->source_path = $blogPhotoPath;
// indicate a target image
$imageHelper->target_path = $blogPhotoPath;
// since in this example we're going to have a jpeg file, let's set the output
// image's quality
$imageHelper->jpeg_quality = 100;
// some additional properties that can be set
// read about them in the documentation
$imageHelper->preserve_aspect_ratio = true;
$imageHelper->enlarge_smaller_images = true;
$imageHelper->preserve_time = true;
$imageHelper->handle_exif_orientation_tag = true;
// resize
// and if there is an error, show the error message
if (!$imageHelper->resize(450, 310, ZEBRA_IMAGE_CROP_CENTER)) {
// if there was an error, let's see what the error is about
switch ($imageHelper->error) {
case 1:
echo 'Source file could not be found!';
break;
case 2:
echo 'Source file is not readable!';
break;
case 3:
echo 'Could not write target file!';
break;
case 4:
echo 'Unsupported source file format!';
break;
case 5:
echo 'Unsupported target file format!';
break;
case 6:
echo 'GD library version does not support target file format!';
break;
case 7:
echo 'GD library is not installed!';
break;
case 8:
echo '"chmod" command is disabled via configuration!';
break;
case 9:
echo '"exif_read_data" function is not available';
break;
}
} else {
echo 'Image uploaded with new size without erros');
}
}
}
External functions or use at same PHP file removing public static qualifiers.
public static function uploadFile($targetDir, $fileName) {
// File upload path
$fileUploaded = $_FILES["input-file"];
$fileType = pathinfo(basename($fileUploaded["name"]),PATHINFO_EXTENSION);
$targetFilePath = $targetDir . $fileName .'.'.$fileType;
if(empty($fileName)){
echo 'Error: any file found inside this path';
return false;
}
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf');
if(in_array($fileType, $allowTypes)){
//Max buffer length 8M
var_dump(ob_get_length());
if(ob_get_length() > 8388608) {
echo 'Error: Max size available 8MB';
return false;
}
// Upload file to server
if(move_uploaded_file($fileUploaded["tmp_name"], $targetFilePath)){
return true;
}else{
echo 'Error: error_uploading_image.';
}
}else{
echo 'Error: Only files JPG, JPEG, PNG, GIF y PDF types are allowed';
}
return false;
}
public static function getUserFile($targetDir, $userId) {
$userImages = glob($targetDir.$userId.'.*');
return !empty($userImages) ? $userImages[0] : null;
}
You can use this library to manipulate the image while uploading. http://www.verot.net/php_class_upload.htm
index.php :
<!DOCTYPE html>
<html>
<head>
<title>PHP Image resize to upload</title>
</head>
<body>
<div class="container">
<form action="pro.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="submit" value="Submit" />
</form>
</div>
</body>
</html>
upload.php
<?php
if(isset($_POST["submit"])) {
if(is_array($_FILES)) {
$file = $_FILES['image']['tmp_name'];
$sourceProperties = getimagesize($file);
$fileNewName = time();
$folderPath = "upload/";
$ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$imageType = $sourceProperties[2];
switch ($imageType) {
case IMAGETYPE_PNG:
$imageResourceId = imagecreatefrompng($file);
$targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
imagepng($targetLayer,$folderPath. $fileNewName. "_thump.". $ext);
break;
case IMAGETYPE_GIF:
$imageResourceId = imagecreatefromgif($file);
$targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
imagegif($targetLayer,$folderPath. $fileNewName. "_thump.". $ext);
break;
case IMAGETYPE_JPEG:
$imageResourceId = imagecreatefromjpeg($file);
$targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
imagejpeg($targetLayer,$folderPath. $fileNewName. "_thump.". $ext);
break;
default:
echo "Invalid Image type.";
exit;
break;
}
move_uploaded_file($file, $folderPath. $fileNewName. ".". $ext);
echo "Image Resize Successfully.";
}
}
function imageResize($imageResourceId,$width,$height) {
$targetWidth =200;
$targetHeight =200;
$targetLayer=imagecreatetruecolor($targetWidth,$targetHeight);
imagecopyresampled($targetLayer,$imageResourceId,0,0,0,0,$targetWidth,$targetHeight, $width,$height);
return $targetLayer;
}
?>
You can use Imagine library also. It uses GD and Imagick.
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data" id="something" class="uniForm">
<input name="new_image" id="new_image" size="30" type="file" class="fileUpload" />
<button name="submit" type="submit" class="submitButton">Upload Image</button>
</form>
<?php
if(isset($_POST['submit'])){
if (isset ($_FILES['new_image'])){
$imagename = $_FILES['new_image']['name'];
$source = $_FILES['new_image']['tmp_name'];
$target = "images/".$imagename;
$type=$_FILES["new_image"]["type"];
if($type=="image/jpeg" || $type=="image/jpg"){
move_uploaded_file($source, $target);
//orginal image making part
$imagepath = $imagename;
$save = "images/" . $imagepath; //This is the new file you saving
$file = "images/" . $imagepath; //This is the original file
list($width, $height) = getimagesize($file) ;
$modwidth = 1000;
$diff = $width / $modwidth;
$modheight = $height / $diff;
$tn = imagecreatetruecolor($modwidth, $modheight) ;
$image = imagecreatefromjpeg($file) ;
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
echo "Large image: <img src='images/".$imagepath."'><br>";
imagejpeg($tn, $save, 100) ;
//thumbnail image making part
$save = "images/thumb/" . $imagepath; //This is the new file you saving
$file = "images/" . $imagepath; //This is the original file
list($width, $height) = getimagesize($file) ;
$modwidth = 150;
$diff = $width / $modwidth;
$modheight = $height / $diff;
$tn = imagecreatetruecolor($modwidth, $modheight) ;
$image = imagecreatefromjpeg($file) ;
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
//echo "Thumbnail: <img src='images/sml_".$imagepath."'>";
imagejpeg($tn, $save, 100) ;
}
else{
echo "File is not image";
}
}
}
?>
This thing worked for me. No any external liabraries used
define ("MAX_SIZE","3000");
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["image-1"]["name"];
$uploadedfile = $_FILES['image-1']['tmp_name'];
if ($image)
{
$filename = stripslashes($_FILES['image-1']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
echo "Unknown Extension..!";
}
else
{
$size=filesize($_FILES['image-1']['tmp_name']);
if ($size > MAX_SIZE*1024)
{
echo "File Size Excedeed..!!";
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['image-1']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['image-1']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
echo $scr;
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=1000;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=1000;
$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 = "../images/product-image/Cars/". $_FILES['image-1']['name'];
$filename1 = "../images/product-image/Cars/small". $_FILES['image-1']['name'];
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}
}