Resizing Image (create thumbnail) on ftp_put - php

So I have a simple goal but I can't seem to get the one part to work.
1) Upload an image and create 3 different sizes: LG, MD, SM; then rename images.
2) Move the images from server/website A to server/website B.
I have the uploading and renaming working for all three images, but I can't figure out what I'm doing wrong with the re-sizing part. Any help would be greatly appreciated.
Note: I am currently trying to just get one image to resize, I figured one at a time would be smartest to make sure I understand what is happening.
Code:
function thumb_resize_image_new($source, $destination, $image_type, $max_size, $image_width, $image_height, $quality){
if($image_width <= 0 || $image_height <= 0){return false;} //return false if nothing to resize
//do not resize if image is smaller than max size
if($image_width <= $max_size && $image_height <= $max_size){
return true;
}
//Construct a proportional size of new image
$image_scale = min($max_size/$image_width, $max_size/$image_height);
$new_width = ceil($image_scale * $image_width);
$new_height = ceil($image_scale * $image_height);
$new_canvas = imagecreatetruecolor( $new_width, $new_height ); //Create a new true color image
imagealphablending($new_canvas,true);
$success = imagecopyresampled($new_canvas, $source, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height);
return true;
}
if(isset($_POST['sendFile'])) {
$image_name = $_FILES['image_file']['name']; //file name
$destination_folder = "folder/";
$sm_square_size = 300; //Thumbnails will ! be cropped
$sm_prefix = "_sm"; //Small thumb Prefix
$md_square_size = 600; //Thumbnails will ! be cropped
$md_prefix = "_md"; //Medium thumb Prefix
$max_image_size = 1200; //Maximum image size (height and width)
$lg_prefix = "_lg"; //Large thumb Prefix
$jpeg_quality = 90; //jpeg quality
if($image_name != "") {
$image_size = $_FILES['image_file']['size']; //file size
$image_temp = $_FILES['image_file']['tmp_name']; //file temp
$image_size_info = getimagesize($image_temp); //get image size
//echo "Image ".$image_name." Uploaded. ";
if($image_size_info){
$image_width = $image_size_info[0]; //image width
$image_height = $image_size_info[1]; //image height
$image_type = $image_size_info['mime']; //image type
} else {
die("Make sure image file is valid!");
}
//switch statement below checks allowed image type
//as well as creates new image from given file
switch($image_type){
case 'image/png':
$image_res = imagecreatefrompng($image_temp); break;
case 'image/gif':
$image_res = imagecreatefromgif($image_temp); break;
case 'image/jpeg': case 'image/pjpeg':
$image_res = imagecreatefromjpeg($image_temp); break;
default:
$image_res = false;
}
if($image_res){
//Get file extension and name to construct new file name
$image_info = pathinfo($image_name);
$image_extension = strtolower($image_info["extension"]); //image extension
$image_name_only = strtolower($image_info["filename"]);//file name only, no extension
$dateRec = date('d-M-Y-h-i-s');
//create a random name for new image (Eg: fileName_293749.jpg) ;
$new_file_name = $dateRec. '_' . rand(0, 9999);
$thumb_name = $new_file_name.$sm_prefix.'.'.$image_extension;
$medium_name = $new_file_name.$md_prefix.'.'.$image_extension;
$large_name = $new_file_name.$lg_prefix.'.'.$image_extension;
$thumb_path = $destination_folder.$thumb_name;
$medium_path = $destination_folder.$medium_name;
$large_path = $destination_folder.$large_name;
$ftp_server = "";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$ftp_username = "";
$ftp_userpass = "";
$login_conn = ftp_login($ftp_conn, $ftp_username, $ftp_userpass) or die("Could not connect to ftp login");
if((!$ftp_conn) || (!$login_conn)) {
print "FTP connection failed!"; exit();
} else {
// upload a file
if(thumb_resize_image_new($image_res, $image_temp, $image_type, $md_square_size, $image_width, $image_height, $jpeg_quality)) {
echo "thumb created. $success <br />";
} else {
die('Error Creating thumbnail: '.$thumb_path.'<br />');
}
if(ftp_put($ftp_conn, $thumb_path, $image_temp, FTP_BINARY)) {
echo "Successfully uploaded $thumb_name <hr />";
} else {
echo "There was a problem while uploading $thumb_name into $thumb_path <hr />";
}
if(ftp_put($ftp_conn, $medium_path, $image_temp, FTP_BINARY)) {
echo "Successfully uploaded $medium_name <hr />";
} else {
echo "There was a problem while uploading $medium_name into $medium_path <hr />";
}
if(ftp_put($ftp_conn, $large_path, $image_temp, FTP_BINARY)) {
echo "Successfully uploaded $large_name <hr />";
} else {
echo "There was a problem while uploading $large_name into $large_path <hr />";
}
}
ftp_close($ftp_conn);
}
}
}
If anyone knows how to help fix this, or a better way of doing it, I'd forever be thankful!

Related

Resize the image propositionally until required file size is met

Currently have a simple function that works, but it allows user to add big images. I want to allow all image uploads, but there should be a function that resizes the image until certain file size is met (like under 200kb for example)
if($_FILES['file']['size'] != 0){
$uploadOk = 0;
//image object
$image = $_FILES['file'];
//create unique name for file
$imageRandomName = substr(md5(time()), 0, 5) . "-" . $image['name'];
//upload dir
$target_dir = "rest/user" . $_SESSION["username"] . "/events/" . $_SESSION["event_id"] . "/people/";
//make folder for user if non exists
if(!file_exists($target_dir)){
mkdir($target_dir, 0777, true);
}
//file to be upload
$target_file = $target_dir . base($imageRandomName);
//get file type
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
$check = getimagesize($image["tmp_name"]);
if($check !== false){
$uploadOk = 1;
} else {
$uploadOk = 0;
}
if($uploadOk == 0){
echo "noupload";
} else {
if ( move_uploaded_file($image["tmp_name"], $target_file ) ) {
//get file size on server
$filesizeonserver = filesize($target_file);
echo "file: ".$target_file." size: ".$filesizeonserver;
$times = 0;
if($filesizeonserver > 100000){
do{
$resized = resizeImage($target_file, "0.1");
$filesizeonserver = filesize($target_file);
$times++;
} while ($filesizeonserver > 100000);
echo "resized ".$times." times";
} else {
}
//mysql query
} else {
echo "Sorry, there was an error uploading your file.";
}
}
} else {
//do mysql query
}
resizeImage()
function resizeImage($file, $percent){
list($width, $height) = getimagesize($file);
$newwidth = $width-($width*$percent);
$newheight = $height-($height*$percent);
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($file);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
$newImage = imagejpeg($thumb, $file, 100);
return $newImage;
}
Now I am getting somewhere, I think I am really close achieving it, but for some weird reason I am getting image that has dimension of 1px width, 4px height and size of 4kb. Completely black image.
In case you are thinking what image am adding to this function:
1,232,055 bytes, 1220 × 1829, 72dpi, JPEG
EDIT: Okay now I think something is wrong with the resizeImage function. Since it works only first the first time. For some reason it fails to get image and renders it black and tiny.
EDIT2: Now I am getting image resized function, there was nothing wrong with it. I noticed that function keeps resizing the image till to its bitter end. I can see it in the find how it shrinks.
EDIT3: I located the problem. Now it seems that $filesizeonserver is getting always the first value and in do...while its not updating even thou i am setting it to change.
$allowedFileTypes = ['image/png', 'image/gif', 'image/jpeg', 'image/jpg'];
if (in_array($_FILES['image']['type'], $allowedFileTypes)) {
$imageType = $_FILES['image']['type'];
//allow file size under 10mb
if($_FILES['file']['size'] < 10000000){
//image object
$image = $_FILES['file'];
//so there is no same name files
$imageRandomName = substr( md5( time() ), 0, 5 ) . "-" . $image['name'];
//place where image is uploaded
$target_dir = 'rest/user/' . $_SESSION['username'] . '/events/' . $_SESSION['event_id'] . '/people/';
//make folder for users
if ( !file_exists( $target_dir ) ) {
mkdir( $target_dir, 0777, true );
}
//file to be uploded
$target_file = $target_dir . basename( $imageRandomName );
//get file type
//$imageFileType = pathinfo( $target_file, PATHINFO_EXTENSION );
$check = getimagesize($image["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 upload is ok
if ( $uploadOk == 0 ) {
echo "Sorry cant upload";
} else {
if ( move_uploaded_file($image["tmp_name"], $target_file ) ) {
//get file size on server
$filesizeonserver = filesize($target_file);
$times = 0;
if($filesizeonserver > 300000){
do{
clearstatcache();
$resized = resizeImage($target_file, 0.05, $imageType);
$filesizeonserver = filesize($target_file);
$times++;
} while ($filesizeonserver > 300000);
echo "resized ".$times." times";
} else {
}
//sql query
} else {
echo "Sorry, there was an error uploading your file.";
}
}
} else {
//sql query
}
} else {
echo "wrongimagetype";
}
resizeImage()
function resizeImage($file, $percent, $imageType){
list($width, $height) = getimagesize($file);
$newwidth = $width-($width*$percent);
$newheight = $height-($height*$percent);
$thumb = imagecreatetruecolor($newwidth, $newheight);
switch($imageType){
case 'image/png':
$background = imagecolorallocate($thumb, 0, 0, 0);
imagecolortransparent($thumb, $background);
imagealphablending($thumb, false);
imagesavealpha($thumb, true);
$source = imagecreatefrompng($file);
break;
case 'image/gif':
$background = imagecolorallocate($thumb, 0, 0, 0);
imagecolortransparent($thumb, $background);
imagealphablending($thumb, false);
imagesavealpha($thumb, true);
$source = imagecreatefromgif($file);
break;
case 'image/jpeg':
case 'image/jpg':
$source = imagecreatefromjpeg($file);
break;
}
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
switch($imageType){
case 'image/png':
$image = imagepng($thumb, $file, 0);
break;
case 'image/gif':
$image = imagegif($file);
break;
case 'image/jpeg':
case 'image/jpg':
$image = imagejpeg($thumb, $file, 100);
break;
}
return $image;
}
OUTPUT:
File is an image - image/jpeg.resized 17 times
Disclaimer: Whole things works thou image quality suffer a bit. Need to work on that.

PHP Imagejpeg function

I am using php and js for uploading images to a folder. I installed XAMPP and everything worked in localhost. Later, I uploaded my code to a server, changed the paths but it does not work.
I checked the paths in my error.log file and they are OK, also made permissions to 777 and this is the error that it shows:
"PHP Warning: imagejpeg(): Unable to open './uploads/Cartas/imagen_5923239258.jpg' for writing: No such file or directory in /ImageUploader/processupload.php on line 152"
My line 152 is the next one:
imagejpeg($source, $destination, $quality); return true;
My php code is here:
<?php
include '../php/connectionData.php';
$mytype=$_REQUEST['type'];
$updating=$_REQUEST['edit'];
global $image_save_folder;
############ Configuration ##############
$thumb_square_size = 200; //Thumbnails will be cropped to 200x200 pixels
$max_image_size = 500; //Maximum image size (height and width)
$thumb_prefix = "thumb_"; //Normal thumb Prefix
$destination_folder = './ImageUploader/uploads/'.$mytype."/";
//$destination_folder = 'C:/xampp/htdocs/pfc/ImageUploader/uploads/'.$mytype."/"; //old working directory in
$jpeg_quality = 90; //jpeg quality
##########################################
error_log("Destination folder: ".$destination_folder);
//continue only if $_POST is set and it is a Ajax request
if(isset($_POST) && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
$access=1;
// check $_FILES['ImageFile'] not empty
if(!isset($_FILES['image_file']) || !is_uploaded_file($_FILES['image_file']['tmp_name'])){
$access=0;
}
if ($access){
//uploaded file info we need to proceed
$image_name = $_FILES['image_file']['name']; //file name
$image_size = $_FILES['image_file']['size']; //file size
$image_temp = $_FILES['image_file']['tmp_name']; //file temp
$image_size_info = getimagesize($image_temp); //get image size
if($image_size_info){
$image_width = $image_size_info[0]; //image width
$image_height = $image_size_info[1]; //image height
$image_type = $image_size_info['mime']; //image type
}else{
die("Make sure image file is valid!");
}
//switch statement below checks allowed image type
//as well as creates new image from given file
switch($image_type){
case 'image/png':
$image_res = imagecreatefrompng($image_temp); break;
case 'image/gif':
$image_res = imagecreatefromgif($image_temp); break;
case 'image/jpeg': case 'image/pjpeg':
$image_res = imagecreatefromjpeg($image_temp); break;
default:
$image_res = false;
}
if($image_res){
//Get file extension and name to construct new file name
$image_info = pathinfo($image_name);
$image_extension = strtolower($image_info["extension"]); //image extension
$image_name_only = strtolower($image_info["filename"]);//file name only, no extension
//create a random name for new image (Eg: fileName_293749.jpg) ;
$new_file_name = $image_name_only. '_' . rand(0, 9999999999) . '.' . $image_extension;
//folder path to save resized images and thumbnails
$thumb_save_folder = $destination_folder . $thumb_prefix . $new_file_name;
$image_save_folder = $destination_folder . $new_file_name;
//call normal_resize_image() function to proportionally resize image
if(normal_resize_image($image_res, $image_save_folder, $image_type, $max_image_size, $image_width, $image_height, $jpeg_quality))
{
//call crop_image_square() function to create square thumbnails
if(!crop_image_square($image_res, $thumb_save_folder, $image_type, $thumb_square_size, $image_width, $image_height, $jpeg_quality))
{
die('Error Creating thumbnail');
}
/* We have succesfully resized and created thumbnail image
We can now output image to user's browser or store information in the database*/
echo '<div align="center">';
echo '<img src="./ImageUploader/uploads/'.$thumb_prefix . $new_file_name.'" alt="Thumbnail">';
echo '<br />';
echo '<img src="./ImageUploader/uploads/'. $new_file_name.'" alt="Resized Image">';
echo '</div>';
}
imagedestroy($image_res); //freeup memory
}
}
}
##### This function will proportionally resize image #####
function normal_resize_image($source, $destination, $image_type, $max_size, $image_width, $image_height, $quality){
if($image_width <= 0 || $image_height <= 0){return false;} //return false if nothing to resize
//do not resize if image is smaller than max size
if($image_width <= $max_size && $image_height <= $max_size){
if(save_image($source, $destination, $image_type, $quality)){
return true;
}
}
//Construct a proportional size of new image
$image_scale = min($max_size/$image_width, $max_size/$image_height);
$new_width = ceil($image_scale * $image_width);
$new_height = ceil($image_scale * $image_height);
$new_canvas = imagecreatetruecolor( $new_width, $new_height ); //Create a new true color image
//Copy and resize part of an image with resampling
if(imagecopyresampled($new_canvas, $source, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height)){
save_image($new_canvas, $destination, $image_type, $quality); //save resized image
}
return true;
}
##### This function crops image to create exact square, no matter what its original size! ######
function crop_image_square($source, $destination, $image_type, $square_size, $image_width, $image_height, $quality){
if($image_width <= 0 || $image_height <= 0){return false;} //return false if nothing to resize
if( $image_width > $image_height )
{
$y_offset = 0;
$x_offset = ($image_width - $image_height) / 2;
$s_size = $image_width - ($x_offset * 2);
}else{
$x_offset = 0;
$y_offset = ($image_height - $image_width) / 2;
$s_size = $image_height - ($y_offset * 2);
}
$new_canvas = imagecreatetruecolor( $square_size, $square_size); //Create a new true color image
//Copy and resize part of an image with resampling
if(imagecopyresampled($new_canvas, $source, 0, 0, $x_offset, $y_offset, $square_size, $square_size, $s_size, $s_size)){
save_image($new_canvas, $destination, $image_type, $quality);
}
return true;
}
##### Saves image resource to file #####
function save_image($source, $destination, $image_type, $quality){
switch(strtolower($image_type)){//determine mime type
case 'image/png':
imagepng($source, $destination); return true; //save png file
break;
case 'image/gif':
imagegif($source, $destination); return true; //save gif file
break;
case 'image/jpeg': case 'image/pjpeg':
imagejpeg($source, $destination, $quality); return true; //save jpeg file
break;
default: return false;
}
}

How to re-size image with high quality When using this code?

How to re-size image with high quality When using this code ?
.....................................................................................................................................................................
<?PHP
if(isset($_POST["Submit"]))
{
$image_type_check = $_FILES['file']['type']; //file type
$image_name = $_FILES['file']['name']; //file name
$image_size = $_FILES['file']['size']; //file size
$image_temp = $_FILES['file']['tmp_name']; //file temp
$image_size_info = getimagesize($image_temp); //get image size
//Get file extension and name to construct new file name
$image_info = pathinfo($image_name);
$image_extension = strtolower($image_info["extension"]); //image extension
$image_name_only = strtolower($image_info["filename"]);//file name only, no extension
//create a random name for new image (Eg: fileName_293749.jpg);
$new_file_name = '123456789'.$image_extension;
list($width,$height)=getimagesize($image_temp);
$newwidth=985;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$filename = "uploads/".$new_file_name;
imagejpeg($tmp,$filename,100);
}
?>
you should use move_uploaded_file()
to make sure that the paths are OK and the file is valid .
To change the size you need imagecopyresampled() .
your file name is invalid with
$image_info = pathinfo($image_name);
$image_extension = strtolower($image_info["extension"]);
$new_file_name = '123456789'.$image_extension;
you get
$new_file_name == '123456789jpg'
without .
[...]
$image_extension = "." . strtolower($image_info["extension"]);
$target = "uploads/123456789".$image_extension;
if(move_uploaded_file($image_temp,$target)) {
if ($image_extension == '.jpg') {
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($image_temp);
$ratio_orig = $width_orig/$height_orig;
$width = 985;
if ($width_orig > $height_orig) {
$height = $width / $ratio_orig;
} else {
$height = $width * $ratio_orig;
}
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($target);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
imagejpeg($image_p,$target,100);
imagedestroy($image_p);
} //is jpg file
} else { echo "File could not be moved to" .$target; }

php resize image on upload

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;
?>

php resize image after upload and crop it to the center

i have a user profile in php and i want to give users the choice of changing their profile picture. But when they submit their new picture via $_POST i want the picture to be resized to:
height:110px | width:relevant to the height (if the width is bigger than height)
width:110px | height:relevant to the width (if the height is bigger than width)
when the resize is done, i want to crop the picture so it becomes 110px x 110px but i want it to be centered.
For example if the user uploads a picture with 110px width and 200px height (dimensions after the resize) the new image after crop will be 110x110 cropped by 90px from right. What i want is to cropped 45px from left and another 45px from right so it will be centered
the function will accept .png, .gif and .jpg images and will save the new image only in jpg format no matter what the initial format was.
I searched a lot to create such a function and i found an answer but any time i atempt to change some minor detail everything stop working properly.
My code so far:
<?php
$userfile_name = $_FILES["sgnIMG"]["name"];
$userfile_tmp = $_FILES["sgnIMG"]["tmp_name"];
$userfile_size = $_FILES["sgnIMG"]["size"];
$filename = basename($_FILES["sgnIMG"]["name"]);
$file_ext = substr($filename, strrpos($filename, ".") + 1);
$large_image_location = $target_path . $filename;
$ext = '';
if ($file_ext == 'jpg') {
$ext = 1;
} else if ($file_ext == 'gif') {
$ext = 2;
} else if ($file_ext == 'png') {
$ext = 3;
} else {
$ext = 0;
}
$target = $target_path . basename($_FILES["sgnIMG"]["name"]);
if (move_uploaded_file($userfile_tmp, $target)) {
$newImg = resize110($target, $ext);
if (isset($_POST['imupd']) && ($_POST['imupd'] == 'up')) {
$sql = "UPDATE users SET avatar='" . str_replace('im/users/', '', $newImg) . "' WHERE id=" . $_SESSION['sesID'] . "";
$result = mysql_query($sql);
if ($result) {
echo '<img src="' . $newImg . '" width="110" title="' . $file_ext . '"/>';
} else {
echo '<img src="im/avatars/px.png" width="110" title="' . $file_ext . '"/>';
}
}
} else {
}
function getHeight($image)
{
$sizes = getimagesize($image);
$height = $sizes[1];
return $height;
}
function getWidth($image)
{
$sizes = getimagesize($image);
$width = $sizes[0];
return $width;
}
function resize110($image, $ext)
{
chmod($image, 0777);
$oldHeight = getHeight($image);
$oldWidth = getWidth($image);
if ($oldHeight < $oldWidth) {
$newImageHeight = 110;
$newImageWidth = ceil((110 * $oldWidth) / $oldHeight);
imagecopyresampled($newImage, $source, -ceil(($newImageWidth - 110) / 2), 0, 0, 0, $newImageWidth, $newImageHeight, $oldWidth, $oldHeight);
} else {
$newImageHeight = ceil((110 * $oldHeight) / $oldWidth);
$newImageWidth = 110;
imagecopyresampled($newImage, $source, 0, -ceil(($newImageHeight - 110) / 2), 0, 0, $newImageWidth, $newImageHeight, $oldWidth, $oldHeight);
}
$newImage = imagecreatetruecolor(110, 110);
chmod($image, 0777);
return $image;
switch ($ext) {
case 1;
$source = imagecreatefromjpeg($image);
break;
case 2;
$source = imagecreatefromgif($image);
break;
case 3;
$source = imagecreatefrompng($image);
break;
}
imagejpeg($newImage, $image, 90);
return $image;
}
I looked around a lot and combined different parts of code i found. So this script will take a jpg,gif of png image, resize it to 110px width if width is greater of 110px height if height is greater. The ascpect ratio will remain so the remaining pixels will be divided by 2 will be used to center the image.
for a different size just change 110 everywhere.
==================================================================================
<?php
// pfpic -> the name of the <input type="file" name="pfpic"/> where user chooses file
$target_path = "im/users/"; // the directory to store the uploaded and then resampled image
$userfile_name = $_FILES["pfpic"]["name"]; // the name that the image file will have once uploaded
$userfile_tmp = $_FILES["pfpic"]["tmp_name"]; // the temporary name the server uses to store the file
$userfile_size = $_FILES["pfpic"]["size"]; // the size of the file that we want to upload
$filename = basename($_FILES["pfpic"]["name"]); // the full name of the file
$file_ext = substr($filename, strrpos($filename, ".") + 1); // the file extension
$large_image_location = $target_path.$filename; // the full path to the file
$ext='';
if($file_ext=='jpg')
{
$ext=1;
}
else if ($file_ext=='gif')
{
$ext=2;
}
else if ($file_ext=='png')
{
$ext=3;
}
else
{
$ext=0;
}
$target = $target_path.basename(sha1($_SESSION['sesID']).'.'.'jpg');
if($ext!=0)
{
if(move_uploaded_file($userfile_tmp,$target))
{
$newImg=resize110($target,$ext);
echo '<img src="'.$newImg.'"/>';
}
else
{
echo 'the file could not be uploaded, please try again';
}
}
else
{
echo 'this file extension is not accepted, please use "jpg", "gif" or "png" file formats';
}
function getHeight($image)
{
$sizes = getimagesize($image);
$height = $sizes[1];
return $height;
}
function getWidth($image)
{
$sizes = getimagesize($image);
$width = $sizes[0];
return $width;
}
function resize110($image,$ext)
{
chmod($image, 0777);
$oldHeight=getHeight($image);
$oldWidth=getWidth($image);
switch ($ext)
{
case 1;
$source = imagecreatefromjpeg($image);
break;
case 2;
$source = imagecreatefromgif($image);
break;
case 3;
$source = imagecreatefrompng($image);
break;
}
$newImage = imagecreatetruecolor(110,110);
$bgcolor = imagecolorallocate($newImage, 255, 255, 255);
imagefill($newImage, 0, 0, $bgcolor); // use this if you want to have a white background instead of black
// we check tha width and height and then we crop the image to the center
if($oldHeight<$oldWidth)
{
$newImageHeight = 110;
$newImageWidth = ceil((110*$oldWidth)/$oldHeight);
imagecopyresampled($newImage,$source,-ceil(($newImageWidth-110)/2),0,0,0,$newImageWidth,$newImageHeight,$oldWidth,$oldHeight);
}
else
{
$newImageHeight = ceil((110*$oldHeight)/$oldWidth);
$newImageWidth = 110;
imagecopyresampled($newImage,$source,0,-ceil(($newImageHeight-110)/2),0,0,$newImageWidth,$newImageHeight,$oldWidth,$oldHeight);
}
//we save the image as jpg resized to 110x110 px and cropped to the center. the old image will be replaced
imagejpeg($newImage,$image,90);
return $image;
}
?>

Categories