I tried 2 implementations, shown below. Both are working well but when I tried to mix them it is not working anymore.
$output['status']=FALSE;
set_time_limit(0);
$allowedImageType = array("image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/x-png" );
if ($_FILES['image_file_input']["error"] > 0) {
$output['error']= "File Error";
}
elseif (!in_array($_FILES['image_file_input']["type"], $allowedImageType)) {
$output['error']= "Invalid image format";
}
elseif (round($_FILES['image_file_input']["size"] / 1024) > 4096) {
$output['error']= "Maximum file upload size is exceeded";
} else {
$temp_path = $_FILES['image_file_input']['tmp_name'];
$file = pathinfo($_FILES['image_file_input']['name']);
$fileType = $file["extension"];
$photo_name = $productname.'-'.$member_id."_".time();
$fileName1 = $photo_name . '-125x125' . ".jpg";
$fileName2 = $photo_name . '-250x250' . ".jpg";
$fileName3 = $photo_name . '-500x500' . ".jpg";
$small_thumbnail_path = "uploads/large/";
createFolder($small_thumbnail_path);
$small_thumbnail = $small_thumbnail_path . $fileName1;
$medium_thumbnail_path = "uploads/large/";
createFolder($medium_thumbnail_path);
$medium_thumbnail = $medium_thumbnail_path . $fileName2;
$large_thumbnail_path = "uploads/large/";
createFolder($large_thumbnail_path);
$large_thumbnail = $large_thumbnail_path . $fileName3;
$thumb1 = createThumbnail($temp_path, $small_thumbnail,$fileType, 125, 125 );
$thumb2 = createThumbnail($temp_path, $medium_thumbnail, $fileType, 250, 250);
$thumb3 = createThumbnail($temp_path, $large_thumbnail,$fileType, 500, 500);
if($thumb1 && $thumb2 && $thumb3) {
$output['status']=TRUE;
$output['small']= $small_thumbnail;
$output['medium']= $medium_thumbnail;
$output['large']= $large_thumbnail;
}
}
echo json_encode($output);
Function File
function createFolder($path)
{
if (!file_exists($path)) {
mkdir($path, 0755, TRUE);
}
}
function createThumbnail($sourcePath, $targetPath, $file_type, $thumbWidth, $thumbHeight){
$source = imagecreatefromjpeg($sourcePath);
$width = imagesx($source);
$height = imagesy($source);
$tnumbImage = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($tnumbImage, $source, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $width, $height);
if (imagejpeg($tnumbImage, $targetPath, 90)) {
imagedestroy($tnumbImage);
imagedestroy($source);
return TRUE;
} else {
return FALSE;
}
}
Aspect ratio code, which is another one I tried to mix this code. But I was unsuccessful
$fn = $_FILES['image']['tmp_name'];
$size = getimagesize($fn);
$ratio = $size[0]/$size[1]; // width/height
$photo_name = $productname.'-'.$member_id."_".time();
{
if( $ratio > 1) {
$width1 = 500;
$height1 = 500/$ratio;
}
else {
$width1 = 500*$ratio;
$height1 = 500;
}
$src = imagecreatefromstring(file_get_contents($fn));
$dst = imagecreatetruecolor($width1,$height1);
$fileName3 = $photo_name . '-500x500' . ".jpg";
imagecopyresampled($dst,$src,0,0,0,0,$width1,$height1,$size[0],$size[1]);
imagedestroy($src);
imagepng($dst,$fileName3); // adjust format as needed
imagedestroy($dst);
if( $ratio > 1) {
$width2 = 250;
$height2 = 250/$ratio;
}
else {
$width2 = 250*$ratio;
$height2 = 250;
}
$src = imagecreatefromstring(file_get_contents($fn));
$dst = imagecreatetruecolor($width2,$height2);
$fileName2 = $photo_name . '-250x250' . ".jpg";
imagecopyresampled($dst,$src,0,0,0,0,$width2,$height2,$size[0],$size[1]);
imagedestroy($src);
imagepng($dst,$fileName2); // adjust format as needed
imagedestroy($dst);
}
What I need is to save my image after resizing but in second code there is no condition check, and I can't get image upload folder path. That's why I need to merge these 2 codes.
Basically I need need to save my image in 3 size formats: 500x500,250x250 and 125x125. Width is fixed, but height is set as per aspect ratio and set upload folder and condition in second code block.
Try this thumbnail function, which takes your source image resource and thumbnail size, and returns a new image resource for the thumbnail.
function createThumbnail($src, int $width = 100, int $height = null) {
// Ensure that src is a valid gd resource
if (!(is_resource($src) && 'gd' === get_resource_type($src))) {
throw new InvalidArgumentException(
sprintf("Argument 1 of %s expected type resource(gd), %s supplied", __FUNCTION__, gettype($src))
);
}
// Extract source image width, height and aspect ratio
$source_width = imagesx($src);
$source_height = imagesy($src);
$ratio = $source_width / $source_height;
// We know that width is always supplied, and that height can be null
// We must solve height according to aspect ratio if null is supplied
if (null === $height) {
$height = round($width / $ratio);
}
// Create the thumbnail resampled resource
$thumb = imagecreatetruecolor($width, $height);
imagecopyresampled($thumb, $src, 0, 0, 0, 0, $width, $height, $source_width, $source_height);
return $thumb;
}
Given your code above, you can now use the function like this
// Get uploaded file information as you have
// Create your source resource as you have
$source = imagecreatefromstring(file_get_contents($fn));
// Create thumbnails and save + destroy
$thumb = createThumbnail($source, 500);
imagejpeg($thumb, $thumb500TargetPath, 90);
imagedestroy($thumb);
$thumb = createThumbnail($source, 250);
imagejpeg($thumb, $thumb250TargetPath, 90);
imagedestroy($thumb);
$thumb = createThumbnail($source, 125);
imagejpeg($thumb, $thumb125TargetPath, 90);
imagedestroy($thumb);
// Don't forget to destroy the source resource
imagedestroy($source);
Currently I'm able to upload jpg files, and I'm saving them as jpg files. Obviously I'm unable to upload/save png files as it's hard-set to jpg.
I'm trying to work out how I can move from jpg only to allow png, jpg and jpeg.
public static function createAvatar()
{
// check if upload fits all rules
AvatarModel::validateImageFile();
// create a jpg file in the avatar folder, write marker to database
$target_file_path = Config::get('PATH_AVATARS') . Session::get('user_id');
AvatarModel::resizeAvatarImage($_FILES['avatar_file']['tmp_name'], $target_file_path, Config::get('AVATAR_SIZE'), Config::get('AVATAR_SIZE'), Config::get('AVATAR_JPEG_QUALITY'));
AvatarModel::writeAvatarToDatabase(Session::get('user_id'));
Session::set('user_avatar_file', AvatarModel::getPublicUserAvatarFilePathByUserId(Session::get('user_id')));
Session::add('feedback_positive', Text::get('FEEDBACK_AVATAR_UPLOAD_SUCCESSFUL'));
return true;
}
public static function resizeAvatarImage($source_image, $destination, $final_width = 130, $final_height = 130, $quality = 8)
{
list($width, $height) = getimagesize($source_image);
if (!$width || !$height) {
return false;
}
//saving the image into memory (for manipulation with GD Library)
$myImage = imagecreatefromjpeg($source_image);
// calculating the part of the image to use for thumbnail
if ($width > $height) {
$y = 0;
$x = ($width - $height) / 2;
$smallestSide = $height;
} else {
$x = 0;
$y = ($height - $width) / 2;
$smallestSide = $width;
}
// copying the part into thumbnail, maybe edit this for square avatars
$thumb = imagecreatetruecolor($final_width, $final_height);
imagecopyresampled($thumb, $myImage, 0, 0, $x, $y, $final_width, $final_height, $smallestSide, $smallestSide);
// add '.jpg' to file path, save it as a .jpg file with our $destination_filename parameter
$destination .= '.jpg';
imagejpeg($thumb, $destination, $quality);
// delete "working copy"
imagedestroy($thumb);
if (file_exists($destination)) {
return true;
}
// default return
return false;
}
public static function writeAvatarToDatabase($user_id)
{
$database = DatabaseFactory::getFactory()->getConnection();
$query = $database->prepare("UPDATE users SET user_has_avatar = TRUE WHERE user_id = :user_id LIMIT 1");
$query->execute(array(':user_id' => $user_id));
}
This particular part is where the issue lies
$destination .= '.jpg';
imagejpeg($thumb, $destination, $quality);
I've tried adding a switch on the file type and then doing imagejpeg/png/jpg(,,,) depending which filetype the file has and it didn't work as it seemed to be trying to pass a .tmp file.
Any ideas?
You will want to create the image from the beginning as the intended file. Here is a class I use, and then added into your class. You can copy from the one class to the other, but you can see where you need to change things at least:
class AvatarModel
{
public static function resizeAvatarImage($source_image, $destination, $final_width = 130, $final_height = 130, $quality = 8)
{
// Initiate class
$ImageMaker = new ImageFactory();
// Here is just a test landscape sized image
$source_image = 'http://media1.santabanta.com/full6/Outdoors/Landscapes/landscapes-246a.jpg';
// This will save the file to disk. $destination is where the file will save and with what name
// $destination = 'image60px.jpg';
// $ImageMaker->Thumbnailer($source_image,$final_width,$final_height,$destination,$quality);
// This example will just display to browser, not save to disk
$ImageMaker->Thumbnailer($source_image,$final_width,$final_height,false,$quality);
}
}
class ImageFactory
{
public $destination;
protected $original;
public function FetchOriginal($file)
{
$size = getimagesize($file);
$this->original['width'] = $size[0];
$this->original['height'] = $size[1];
$this->original['type'] = $size['mime'];
return $this;
}
public function Thumbnailer($thumb_target = '', $width = 60,$height = 60,$SetFileName = false, $quality = 80)
{
// Set original file settings
$this->FetchOriginal($thumb_target);
// Determine kind to extract from
if($this->original['type'] == 'image/gif')
$thumb_img = imagecreatefromgif($thumb_target);
elseif($this->original['type'] == 'image/png') {
$thumb_img = imagecreatefrompng($thumb_target);
$quality = 7;
}
elseif($this->original['type'] == 'image/jpeg')
$thumb_img = imagecreatefromjpeg($thumb_target);
else
return false;
// Assign variables for calculations
$w = $this->original['width'];
$h = $this->original['height'];
// Calculate proportional height/width
if($w > $h) {
$new_height = $height;
$new_width = floor($w * ($new_height / $h));
$crop_x = ceil(($w - $h) / 2);
$crop_y = 0;
}
else {
$new_width = $width;
$new_height = floor( $h * ( $new_width / $w ));
$crop_x = 0;
$crop_y = ceil(($h - $w) / 2);
}
// New image
$tmp_img = imagecreatetruecolor($width,$height);
// Copy/crop action
imagecopyresampled($tmp_img, $thumb_img, 0, 0, $crop_x, $crop_y, $new_width, $new_height, $w, $h);
// If false, send browser header for output to browser window
if($SetFileName == false)
header('Content-Type: '.$this->original['type']);
// Output proper image type
if($this->original['type'] == 'image/gif')
imagegif($tmp_img);
elseif($this->original['type'] == 'image/png')
($SetFileName !== false)? imagepng($tmp_img, $SetFileName, $quality) : imagepng($tmp_img);
elseif($this->original['type'] == 'image/jpeg')
($SetFileName !== false)? imagejpeg($tmp_img, $SetFileName, $quality) : imagejpeg($tmp_img);
// Destroy set images
if(isset($thumb_img))
imagedestroy($thumb_img);
// Destroy image
if(isset($tmp_img))
imagedestroy($tmp_img);
}
}
AvatarModel::resizeAvatarImage();
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", "10000");
$errors = 0;
$image = $_FILES["fileField"]["name"];
$uploadedfile = $_FILES['fileField']['tmp_name'];
if($image){
$filename = stripslashes($_FILES['fileField']['name']);
$extension = strtolower(getExtension($filename));
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")){
echo ' Unknown Image extension ';
$errors = 1;
} else {
$newname = "$product_cn.$extension";
$size = filesize($_FILES['fileField']['tmp_name']);
if ($size > MAX_SIZE*1024){
echo "You have exceeded the size limit";
$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);
}
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 = "../products_images/$newname";
$filename1 = "../products_images/thumbs/$newname";
imagejpeg($tmp, $filename, 100); // file name also indicates the folder where to save it to
imagejpeg($tmp1, $filename1, 100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}
}
getExtension function:
function getExtension($str) {
$i = strrpos($str, ".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
I've wrote some notation in the code since I'm not really familiar with those functions.
For some reason, it doesn't work. When I'm going to the folder "product_images" or "product_images/thumbs", I can't find any image uploaded.
Any idea what's wrong with my code? There should be 60px width image, and 25px width image.
Note: Variables that you don't know where they were declared such as $product_cn were declared before that block of code which works prefectly fine (tested). If you still want a glance at it, feel free to ask for the code.
Here is another nice and easy solution:
$maxDim = 800;
$file_name = $_FILES['myFile']['tmp_name'];
list($width, $height, $type, $attr) = getimagesize( $file_name );
if ( $width > $maxDim || $height > $maxDim ) {
$target_filename = $file_name;
$ratio = $width/$height;
if( $ratio > 1) {
$new_width = $maxDim;
$new_height = $maxDim/$ratio;
} else {
$new_width = $maxDim*$ratio;
$new_height = $maxDim;
}
$src = imagecreatefromstring( file_get_contents( $file_name ) );
$dst = imagecreatetruecolor( $new_width, $new_height );
imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
imagedestroy( $src );
imagepng( $dst, $target_filename ); // adjust format as needed
imagedestroy( $dst );
}
Reference: PHP resize image proportionally with max width or weight
Edit: Cleaned up and simplified the code a bit. Thanks #jan-mirus for your comment.
You can use this library to manipulate the image while uploading. http://www.verot.net/php_class_upload.htm
// This was my example that I used to automatically resize every inserted photo to 100 by 50 pixel and image format to jpeg hope this helps too
if($result){
$maxDimW = 100;
$maxDimH = 50;
list($width, $height, $type, $attr) = getimagesize( $_FILES['photo']['tmp_name'] );
if ( $width > $maxDimW || $height > $maxDimH ) {
$target_filename = $_FILES['photo']['tmp_name'];
$fn = $_FILES['photo']['tmp_name'];
$size = getimagesize( $fn );
$ratio = $size[0]/$size[1]; // width/height
if( $ratio > 1) {
$width = $maxDimW;
$height = $maxDimH/$ratio;
} else {
$width = $maxDimW*$ratio;
$height = $maxDimH;
}
$src = imagecreatefromstring(file_get_contents($fn));
$dst = imagecreatetruecolor( $width, $height );
imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $size[0], $size[1] );
imagejpeg($dst, $target_filename); // adjust format as needed
}
move_uploaded_file($_FILES['pdf']['tmp_name'],"pdf/".$_FILES['pdf']['name']);
<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";
}
}
}
?>
Building onto answer from #zeusstl, for multiple images uploaded:
function img_resize()
{
$input = 'input-upload-img1'; // Name of input
$maxDim = 400;
foreach ($_FILES[$input]['tmp_name'] as $file_name){
list($width, $height, $type, $attr) = getimagesize( $file_name );
if ( $width > $maxDim || $height > $maxDim ) {
$target_filename = $file_name;
$ratio = $width/$height;
if( $ratio > 1) {
$new_width = $maxDim;
$new_height = $maxDim/$ratio;
} else {
$new_width = $maxDim*$ratio;
$new_height = $maxDim;
}
$src = imagecreatefromstring( file_get_contents( $file_name ) );
$dst = imagecreatetruecolor( $new_width, $new_height );
imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
imagedestroy( $src );
imagepng( $dst, $target_filename ); // adjust format as needed
imagedestroy( $dst );
}
}
}
If you want to use Imagick out of the box (included with most PHP distributions), it's as easy as...
$image = new Imagick();
$image_filehandle = fopen('some/file.jpg', 'a+');
$image->readImageFile($image_filehandle);
$image->scaleImage(100,200,FALSE);
$image_icon_filehandle = fopen('some/file-icon.jpg', 'a+');
$image->writeImageFile($image_icon_filehandle);
You will probably want to calculate width and height more dynamically based on the original image. You can get an image's current width and height, using the above example, with $image->getImageHeight(); and $image->getImageWidth();
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);
}}
}
You can use Imagine library also. It uses GD and Imagick.
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;
}
?>
I followed the steps at https://www.w3schools.com/php/php_file_upload.asp and http://www.w3bees.com/2013/03/resize-image-while-upload-using-php.html to produce this solution:
In my view (I am using the MVC paradigm, but it could be your .html or .php file, or the technology that you use for your front-end):
<form action="../../photos/upload.php" method="post" enctype="multipart/form-data">
<label for="quantity">Width:</label>
<input type="number" id="picture_width" name="picture_width" min="10" max="800" step="1" value="500">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
My upload.php:
<?php
/* Get original image x y*/
list($w, $h) = getimagesize($_FILES['fileToUpload']['tmp_name']);
$new_height=$h*$_POST['picture_width']/$w;
/* calculate new image size with ratio */
$ratio = max($_POST['picture_width']/$w, $new_height/$h);
$h = ceil($new_height / $ratio);
$x = ($w - $_POST['picture_width'] / $ratio) / 2;
$w = ceil($_POST['picture_width'] / $ratio);
/* new file name */
//$path = 'uploads/'.$_POST['picture_width'].'x'.$new_height.'_'.basename($_FILES['fileToUpload']['name']);
$path = 'uploads/'.basename($_FILES['fileToUpload']['name']);
/* read binary data from image file */
$imgString = file_get_contents($_FILES['fileToUpload']['tmp_name']);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($_POST['picture_width'], $new_height);
imagecopyresampled($tmp, $image,
0, 0,
$x, 0,
$_POST['picture_width'], $new_height,
$w, $h);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($path,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
//echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
//echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($path)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
/* Save image */
switch ($_FILES['fileToUpload']['type']) {
case 'image/jpeg':
imagejpeg($tmp, $path, 100);
break;
case 'image/png':
imagepng($tmp, $path, 0);
break;
case 'image/gif':
imagegif($tmp, $path);
break;
default:
exit;
break;
}
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
/* cleanup memory */
imagedestroy($image);
imagedestroy($tmp);
}
?>
The name of the folder where pictures are stored is called 'uploads/'. You need to have that folder previously created and that is where you will see your pictures. It works great for me.
NOTE: This is my form:
The code is uploading and resizing pictures properly. I used this link as a guide: http://www.w3bees.com/2013/03/resize-image-while-upload-using-php.html. I modified it because in that code they specify both width and height of resized pictures. In my case, I only wanted to specify width. The height I automatically calculated it proportionally, just keeping proper picture proportions. Everything works perfectly. I hope this helps.
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:
An image is uploaded to server by uploadFile function.
If image has been uploaded correctly, we recover this image and its path by getUserFile function.
Resize image to custom width and height and replace at same path.
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;
}
This class you can use with any framework or core PHP.
For complete detail visit the below link.
https://learncodeweb.com/web-development/laravel-9-upload-multiple-files-and-image-resizer/
There are many libs that you can use to upload & resize multiple images in the Laravel. I come up with a simple and easy solution, it is a GD base class.
All you need to install via composer with the help of the below command.
composer require learncodeweb/filesupload
After installation recreates the autoload file with the help of the below command. (optional)
composer dump-autoload
How to import and use in the Larvel 8/9 (Tested).
use anyFileUpload\FilesUploadAndImageResize as anyFilesUpload;
$files = new anyFilesUpload('array', ['jpg', 'jpeg', 'png'], public_path('uploads'), 0777);
$files->uploadFiles('files', 250, '', '', 100, '850', ['350']);
dd($files->uploadedData);
After uploading files to the server, it returns all uploaded file names. You can dump those in your DB.
Provided Functionalities
Upload Single Or Multiple Files.
Upload Any Type Of Files (Not Only Images).
The image file can Resize.
Create Image Thumbnails (With Keep The Image Aspect Ratio).
You can add a watermark (Text, Image).
Easy Integration With Forms.
Create Any Number Of Thumbnails Under One Upload.
Customizable Paths To Thumbnails Folders.
Customizable Thumbnails Sizes And Dimensions.
Files Extension Filters.
File Size Limit for Uploading.
Based on zeusstl soulution you can add this to 4th line if you want that either of width or height use maxDim and highest measure is set based on this:
if ($height > $width) {
$maxDim = $maxDim * ($height/$width);
} else {
$maxDim = $maxDim * ($width/$height);
}
Download library file Zebra_Image.php belo link
https://drive.google.com/file/d/0Bx-7K3oajNTRV1I2UzYySGZFd3M/view
resizeimage.php
<?php
require 'Zebra_Image.php';
// create a new instance of the class
$resize_image = new Zebra_Image();
// indicate a source image
$resize_image->source_path = $target_file1;
$ext = $photo;
// indicate a target image
$resize_image->target_path = 'images/thumbnil/' . $ext;
// resize
// and if there is an error, show the error message
if (!$resize_image->resize(200, 200, ZEBRA_IMAGE_NOT_BOXED, -1));
// from this moment on, work on the resized image
$resize_image->source_path = 'images/thumbnil/' . $ext;
?>
Hi I based this function from the one I've found on web and tried modifying it up for my PHP page for uploading of their icons but I want to limit the user from uploading an image which should only size 100x100px. Well I just call it using this:
uploadImage($id,$_FILES['upload']['name'],$_FILES['upload']['tmp_name']);
This is the function I made:
function uploadImage($new_name,$imagename,$tmp_name){
if($tmp_name!=null||$tmp_name!=""){
list($width, $height, $type, $attr) = getimagesize($tmp_name);
if($width==100&&$height==100){
$image1 = $imagename;
$extension = substr($image1, strrpos($image1, '.') + 1);
$image = "$new_name.$extension";
$folder = "Images/";
if($image) {
$filename = $folder.$image;
$copied = copy($tmp_name, $filename);
}
else echo "image not uploaded.";
}
else
echo "upload only 100x100px image!";
}
}
Now the problem is that even if I uploaded an image which exceeds the 100 x 100px dimensions it still proceeds without returning any errors and now I'm lost with it.
You probably need to re-factor your code a bit; have a function that checks whether the uploaded image is valid, and then one actually does the upload. Alternatively, you could create a class.
<?php
class ImageUpload
{
public $tmpImage;
public $maxWidth = 100;
public $maxHeight = 100;
public $errors = [];
public function __construct($image)
{
$this->tmpImage = $image;
}
public function upload()
{
// Check image is valid; if not throw exception
// Check image is within desired dimensions
list($width, $height) = getimagesize($this->tmpImage);
if ($width > $this->maxWidth || $height > $this->maxHeight) {
throw new Exception(sprintf('Your image exceeded the maximum dimensions (%d×%d)', $this->maxWidth, $this->maxHeight));
}
// Create filename
// Do the upload logic, i.e. move_uploaded_file()
}
}
You can then use this class as follows:
<?php
$imageUpload = new ImageUpload($_FILES['upload']['tmp_name']);
try {
$imageUpload->upload();
} catch (Exception $e) {
echo 'An error occurred: ' . $e->getMessage();
}
This was written off the cuff, so they may be errors. But hopefully it demonstrates a better way to handle file uploads, and errors that may occur during upload.
well, you can also resize the image after upload.
function createFixSizeImage( $pathToImages, $pathToFixSizeImages, $Width )
{
// open the directory
$dir = opendir( $pathToImages );
// loop through it, looking for any/all JPG files:
while (false !== ($fname = readdir( $dir ))) {
$image_info = getimagesize( "path/to/images/".$fname );
$image_width = $image_info[0];
$image_height = $image_info[1];
$image_type = $image_info[2];
switch ( $image_type )
{
case IMAGETYPE_JPEG:
// parse path for the extension
$info = pathinfo($pathToImages . $fname);
// continue only if this is a JPEG image
if ( strtolower($info['extension']) == 'jpeg' )
{
// load image and get image size
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// give the size,u want
$new_width = 100;
$new_height = 100;
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save Fix Size Images into a file
imagejpeg( $tmp_img, "{$pathToFixSizeImages}{$fname}" );
}
break;
case IMAGETYPE_PNG:
// parse path for the extension
$info = pathinfo($pathToImages . $fname);
// continue only if this is a JPEG image
if ( strtolower($info['extension']) == 'png' )
{
// load image and get image size
$img = imagecreatefrompng( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
$new_width = 100;
$new_height = 100;
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save Fix Size Images into a file
imagejpeg( $tmp_img, "{$pathToFixSizeImages}{$fname}" );
}
break;
case IMAGETYPE_BMP:
echo "bmp";
break;
default:
break;
}
}
}
// close the directory
closedir( $dir );
}
createFixSizeImage("path","path/to/images/to/be/saved",100);
Extending more or less unknown code and then debugging it, is like you wrote some code weeks ago and you don't understand it any longer.
In your case you are extending some existing code (you have not posted the original code, but your wrote that you did it that way) by adding the feature of checking the image size.
So that you do not need to edit much of the (unknown but) working code, create the new feature as a function of it's own:
/**
* #param string $file
* #param int $with
* #param int $height
* #return bool|null true/false if image has that exact size, null on error.
*/
function image_has_size($file, $width, $height)
{
$result = getimagesize($file);
if ($count($result) < 2) {
return null;
}
list($file_width, $file_height) = $result;
return ($file_width == (int) $width)
&& ($file_height == (int) $height);
}
You now have the new functionality in a single function you can much more easily integrate into the original (hopefully otherwise working) code.
Usage:
$imageHasCorrectSize = image_has_size($tmp_name, 100, 100);
So whenever you change code, do it like a surgeon, keeping the cuts as small as possible.