I have the following image upload script, that uploads an image, renames and resizes a thumbnail too. When uploading image (all JPG) some upload and display fine, yet others upload the main image fine but the thumbnail is just a black square.
Does anyone have any idea as to what the problem is?
[edit] I have added PNG to the filetypes, and it uploads correctly, however 'real' JPG files now upload the black thumbnail. I am thinking that I need to somehow check the file extension and apply imagecreatefromjpeg/imagecreatefrompng based on what is returned?
if this is the case, i am thinking an if/else statement where highlighted will do? - not sure what to check against to get the extension (jpg/png) though...
if(isset($_POST['submit'])){
// get file info
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$thumbName = $_FILES['file']['name']; //
$thumbTmpName = $_FILES['file']['tmp_name']; //
$thumbSize = $_FILES['file']['size']; //
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
//allow file types
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png'); // ADDED PNG HERE
if(in_array($fileActualExt, $allowed)){
if($fileError === 0){
if($fileSize < 1000000){
$fileNameNew = $row['item_img'].".".$fileActualExt; //code!
$fileDestination = 'images/'.$col_id.'/'.$fileNameNew; //number
move_uploaded_file($fileTmpName, $fileDestination);
// if(???){ // START POSSIBLE IF/ELSE HERE?
// create thumbnail
$src = imagecreatefromjpeg($fileDestination);
list($width, $height) = getimagesize($fileDestination);
$thumbWidth = 100;
$thumbHeight = 100;
// } else { // POSSIBLE ELSE HERE?
// ADDED THIS FOR PNG
$src = imagecreatefrompng($fileDestination);
list($width, $height) = getimagesize($fileDestination);
$thumbWidth = 100;
$thumbHeight = 100;
// } // END POSSIBLE IF/ELSE HERE?
$tmp = imagecreatetruecolor($thumbWidth,$thumbHeight);
imagecopyresampled($tmp, $src, 0,0,0,0, $thumbWidth, $thumbHeight, $width, $height);
imagejpeg($tmp, 'images/'.$col_id.'/thumbs/'.$fileNameNew.'', 100);
imagedestroy($src);
imagedestroy($tmp);
//CHECK FOR IMAGE
$checkImgQuery = $db->prepare("SELECT item_image.item_image, item_item.item_id FROM item_image JOIN item_item ON item_item.item_img = item_image.item_image WHERE item_id = :item_id");
$checkImgQuery->execute(array(':item_id' => $item_id));
$check = $checkImgQuery->rowCount();
if($check > 0){
// UPDATE
} else {
// ADD
}
} else {
$error[] = 'your file is too big';
}
} else {
$error[] = 'there was an error uploading your file';
}
} else {
$error[] = 'you cannot upload files of this type';
}
}
Since it is not always happening, this is almost certain to come from the files, as they are the only thing that changes... I'm guessing your jpeg files are either corrupted (but not enough to not display the picture, but maybe make the PHP code crash) or they simply aren't real jpegs...
Here's what I'd recommend: There is no need to force the users on only one file type while PHP alone can handle multiple, so we can check the mime type and act accordingly.
switch(mime_content_type($fileDestination){
case 'image/jpeg':
$src = imagecreatefromjpeg($fileDestination);
break;
case 'image/png':
$src = imagecreatefrompng($fileDestination);
break;
case 'image/gif':
$src = imagecreatefromgif($fileDestination);
break;
default:
$error[] = 'your file is not of a recognized type';
}
if(isset($src)){
//do what you were doing.
}
So we test the mime type and use the corresponding function. Not that I did not include everything, but that should be a good start.
If you want an easier implementation, you could use this:
$src = imagecreatefromstring(file_get_content($fileDestination));
When creating an image from a string, the type is automatically detected. This would return false if the file is not recognized.
You will want to be careful with transparency when saving from PNG to JPG... But I'll leave that part to you.
Related
I have a photo upload area. it was working without any problems. But then I started to notice that it didn't upload some images. in others, colors and pixels began to appear incorrect. No problems with old files. only some of the new uploads.
This problem started to occur on its own without any changes in my codes.
I'm cropping a photo using cropper js.
not every upload is like this. I leave the interesting examples here.
sometimes it doesn't load the image at all.
How can something that works properly fail by itself?
sorry my bad english. thanks in advance to everyone who helped
$file = $_FILES['avatar'];
$fileName = $_FILES['avatar']['name'];
$fileTmpName = $_FILES['avatar']['tmp_name'];
$fileError = $_FILES['avatar']['error'];
$fileSize = $_FILES['avatar']['size'];
$fileType = $_FILES['avatar']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if(in_array($fileActualExt, $allowed)){
if($fileError === 0){
if($fileSize < 100000000){
$fileNameNew = time().md5(time().$o_id.$fileName)."_".sha1($user_id.rand(10,99)).$l_category.".".$fileActualExt;
$fileDestination = "photos/".$fileNameNew;
function compressImage($source, $destination, $quality) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source);
elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source);
elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source);
imagejpeg($image, $destination, $quality);
return true;
}
compressImage($fileTmpName, $fileDestination, 90);
}
I would check if these are filetype related or not. First and last one could be paletted PNG with shifted or partially applied/recognised palette.
The middle one should be a processing error as it has a visible split of contrast in the upper part.
Should be sort of autoexposure that is running on them and fails to do it's job well?
I would say this isn't upload or file error as that'll cause the file to be roken totally 'after' the error and most likely GD won't do a getimagesize() on them nor can use those files.
Also some PHP-related hints:
The pathinfo() is used to get the 'last' extension.
$fileActualExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
That imagecreatefrom* is pain in the ass, but you can use a helper to make it better, also you should use the getimagesize(), imagejpeg() and iamgecreatefrom*() return values for checking if they were really okay.
function getGDImage($source) {
if (!($info = getimagesize($source))) {
return false;
}
switch($info['mime']) {
case 'image/jpeg': return imagecreatefromjpeg($source);
case 'image/gif': return imagecreatefromgif($source);
case 'image/png': return imagecreatefrompng($source);
default: return false;
}
}
function compressImage($source, $destination, $quality) {
return ($image = getGDImage($source))
? imagejpeg($image, $destination, $quality)
: false;
}
I'm (a newbie in php) still working on a time off project and another problem came up, for which I can't find a solution. Therefore I hope u guys can help me! Worked great the last time I posted something on here! I really appreciate your help...thx ahead!
My problem:
I want users to be able to upload pictures when they are logged in. They got several little buttons on their profile with images on them...and they should be able to change them...
I want to have it like this -> When a user uploads an image, the script shall create a new folder on the server. This shall happen in the "user_images" folder (that exists already). So a user with e.g. "id=55" creates a folder "55" in "user_images" when he uploads images. I tried and tried and tried and tried...with different syntax in line -> "$upload_dir =" but without any success :-/ I just don't get it to work...
Here is the part of the script:
<?php
include 'dbconfig.php';
page_protect();
$rs_settings = mysql_query("select * from user where id='$_SESSION[user_id]'");
while ($row_settings = mysql_fetch_array($rs_settings));
error_reporting (E_ALL ^ E_NOTICE);
session_start();
//only assign a new timestamp if the session variable is empty
if (!isset($_SESSION['user_id']) || strlen($_SESSION['user_id'])==0){
$_SESSION['user_id'] = mysql_query("select * from user where id='$_SESSION[user_id]'");
//assign the timestamp to the session variable
$_SESSION['user_file_ext']= "";
}
$upload_dir = "user_images/";
$upload_path = $upload_dir;
$large_image_prefix = "Large_";
$thumb_image_prefix = "button_";
$large_image_name = $large_image_prefix.$_SESSION['user_id'];
image (append the timestamp to the filename)
$thumb_image_name = $thumb_image_prefix.$_SESSION['user_id'];
image (append the timestamp to the filename)
$max_file = "1"; // Maximum file size in MB
$max_width = ""; // Max width allowed for the large image
$thumb_width = "87"; // Width of thumbnail image
$thumb_height = "35"; // Height of thumbnail image
// Only one of these image types should be allowed for upload
$allowed_image_types =
array('image/pjpeg'=>"jpg",'image/jpeg'=>"jpg",'image/jpg'=>"jpg",'image/png'=>"png",
'image/x-png'=>"png",'image/gif'=>"gif");
$allowed_image_ext = array_unique($allowed_image_types); // do not change this
$image_ext = ""; // initialise variable, do not change this.
foreach ($allowed_image_ext as $mime_type => $ext) {
$image_ext.= strtoupper($ext)." ";
}
function resizeImage($image,$width,$height,$scale) {
list($imagewidth, $imageheight, $imageType) = getimagesize($image);
$imageType = image_type_to_mime_type($imageType);
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
switch($imageType) {
case "image/gif":
$source=imagecreatefromgif($image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$source=imagecreatefromjpeg($image);
break;
case "image/png":
case "image/x-png":
$source=imagecreatefrompng($image);
break;
}
imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,
$width,$height);
switch($imageType) {
case "image/gif":
imagegif($newImage,$image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
imagejpeg($newImage,$image,90);
break;
case "image/png":
case "image/x-png":
imagepng($newImage,$image);
break;
}
chmod($image, 0777);
return $image;
}
function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width,
$start_height, $scale){
list($imagewidth, $imageheight, $imageType) = getimagesize($image);
$imageType = image_type_to_mime_type($imageType);
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
switch($imageType) {
case "image/gif":
$source=imagecreatefromgif($image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$source=imagecreatefromjpeg($image);
break;
case "image/png":
case "image/x-png":
$source=imagecreatefrompng($image);
break;
}
imagecopyresampled($newImage,$source,0,0,$start_width,$start_height,$newImageWidth,
$newImageHeight,$width,$height);
switch($imageType) {
case "image/gif":
imagegif($newImage,$thumb_image_name);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
imagejpeg($newImage,$thumb_image_name,90);
break;
case "image/png":
case "image/x-png":
imagepng($newImage,$thumb_image_name);
break;
}
chmod($thumb_image_name, 0777);
return $thumb_image_name;
}
function getHeight($image) {
$size = getimagesize($image);
$height = $size[1];
return $height;
}
function getWidth($image) {
$size = getimagesize($image);
$width = $size[0];
return $width;
}
$large_image_location = $upload_path.$large_image_name.$_SESSION['user_file_ext'];
$thumb_image_location = $upload_path.$thumb_image_name.$_SESSION['user_file_ext'];
if(!is_dir($upload_dir)){
mkdir($upload_dir, 0777);
chmod($upload_dir, 0777);
}
if (file_exists($large_image_location)){
if(file_exists($thumb_image_location)){
$thumb_photo_exists = "<img
src=\"".$upload_path.$thumb_image_name.$_SESSION['user_file_ext']."\" alt=\"Thumbnail
Image\"/>";
}else{
$thumb_photo_exists = "";
}
$large_photo_exists = "<img
src=\"".$upload_path.$large_image_name.$_SESSION['user_file_ext']."\" alt=\"Large
Image\"/>";
} else {
$large_photo_exists = "";
$thumb_photo_exists = "";
}
if (isset($_POST["upload"])) {
//Get the file information
$userfile_name = $_FILES['image']['name'];
$userfile_tmp = $_FILES['image']['tmp_name'];
$userfile_size = $_FILES['image']['size'];
$userfile_type = $_FILES['image']['type'];
$filename = basename($_FILES['image']['name']);
$file_ext = strtolower(substr($filename, strrpos($filename, '.') + 1));
//Only process if the file is a JPG, PNG or GIF and below the allowed limit
if((!empty($_FILES["image"])) && ($_FILES['image']['error'] == 0)) {
foreach ($allowed_image_types as $mime_type => $ext) {
//loop through the specified image types and if they match the
extension then break out
//everything is ok so go and check file size
if($file_ext==$ext && $userfile_type==$mime_type){
$error = "";
break;
}else{
$error = "Only <strong>".$image_ext."</strong> images accepted for upload<br />";
}
}
//check if the file size is above the allowed limit
if ($userfile_size > ($max_file*1048576)) {
$error.= "Images must be under ".$max_file."MB in size";
}
}else{
$error= "Select an image for upload";
}
//Everything is ok, so we can upload the image.
if (strlen($error)==0){
if (isset($_FILES['image']['name'])){
//this file could now has an unknown file extension (we hope it's one of the ones set above!)
$large_image_location = $large_image_location.".".$file_ext;
$thumb_image_location = $thumb_image_location.".".$file_ext;
//put the file ext in the session so we know what file to look for once its uploaded
$_SESSION['user_file_ext']=".".$file_ext;
move_uploaded_file($userfile_tmp, $large_image_location);
chmod($large_image_location, 0777);
$width = getWidth($large_image_location);
$height = getHeight($large_image_location);
//Scale the image if it is greater than the width set above
if ($width > $max_width){
$scale = $max_width/$width;
$uploaded = resizeImage($large_image_location,$width,$height,$scale);
}else{
$scale = 1;
$uploaded = resizeImage($large_image_location,$width,$height,$scale);
}
//Delete the thumbnail file so the user can create a new one
if (file_exists($thumb_image_location)) {
unlink($thumb_image_location);
}
}
//Refresh the page to show the new uploaded image
header("location:".$_SERVER["PHP_SELF"]);
exit();
}
?>
It would be really cool if someone could help me to fix these problems...you may know how hard it is, when you're just a rookie! If there's more weird syntax in there...let me know, I'm just a beginner (like we all have been at the beginning) and trying to get better :)
Thank you guys!
Keeping in mind that allowing any user to upload content to your server creates a security hole that requires special attention, this is a bit of code I've used in the past for an internal-use application:
$folderPath = "/uploads/" . $folderName;
$exist = is_dir($folderPath);
if(!$exist) {
mkdir("$folderPath");
chmod("$folderPath", 0755);
}
else { echo "Folder already exists"; }
You can also chmod right from mkdir but was having issues with doing that on this particular server config.
http://php.net/manual/en/function.mkdir.php
UPDATED with more complete example:
// Define path where file will be uploaded to
// User ID is set as directory name
$folderPath = "/uploads/$userID";
// Check to see if directory already exists
$exist = is_dir($folderPath);
// If directory doesn't exist, create directory
if(!$exist) {
mkdir("$folderPath");
chmod("$folderPath", 0755);
}
else { echo "Folder already exists"; }
// PROCESS FILE UPLOAD
// Set initial/temporary upload location
// temp_uploads must have proper read/write permissions (755 or 777)
$target_path = "/uploads/temp_uploads/";
// Append the name of the uploaded file to the temp directory
$target_path .= basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
$filename = basename( $_FILES['uploadedfile']['name']);
// Location where temporary file is being stored
$temp_location = '/uploads/temp_uploads/' . basename( $_FILES['uploadedfile']['name']);
// Final destination where file will be located
$destination = "/uploads/$folderPath/$filename";
rename($temp_location, $destination);
}
You are assigning a mysql query resource to the $_SESSION["user_id"]
$_SESSION['user_id'] = mysql_query("select * from user where id='$_SESSION[user_id]'");
I think you want to get the user id out of that query
Also if your code produces any errors it would be great if you included them in your question
ps. don't use mysql_* functions, they are deprecated and create unwanted security holes if not used properly, learn dibi, pdo, or any other newer database layer
$file_name=basename($_FILES['uploadedfile']['name']);
mkdir("upload/".$username,0777);
$target_path = "upload/$username/". $file_name;
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php resizing image on upload rotates the image when i don't want it to
I have created my first ever upload code and was testing it, the image resizes and uploads fine. The only issue I have is that it rotates.
Here is the code:
$errors = array();
$message = "";
if(isset($_POST["test"])){
$name = rand(1,999999) . $_FILES["uploadfile"]["name"];
$temp_name = $_FILES["uploadfile"]["tmp_name"];
$size = $_FILES["uploadfile"]["size"];
$extension = strtolower(end(explode('.', $_FILES['uploadfile']['name'])));
$path = "testupload/" . $name;
$info = getimagesize($temp_name);
$originalwidth = $info[0];
$originalheight = $info[1];
$mime = $info["mime"];
$acceptedHeight = 750;
$acceptedWidth = 0;
$acceptedMimes = array('image/jpeg','image/png','image/gif');
$acceptedfileSize = 4102314;
$acceptedExtensions = array('jpg','jpeg','gif','png');
echo $size;
// check mimetype
if(!in_array($mime, $acceptedMimes)){$errors[] = "mime type not allowed - The file you have just uploaded was a: " . $extension . " file!";}
if(!$errors){if($size > $acceptedfileSize){$errors[] = "filesize is to big - Your file size of this file is: " . $size;}}
if(!$errors){if(!in_array($extension, $acceptedExtensions)){$errors[] = "File extension not allowed - The file you have just uploaded was a: " . $extension . " file!";}}
if(!$errors){
// create the image from the temp file.
if ($extension === 'png'){
$orig = imagecreatefrompng($temp_name);
}elseif ($extension === 'jpeg'){
$orig = imagecreatefromjpeg($temp_name);
}elseif ($extension === 'jpg'){
$orig = imagecreatefromjpeg($temp_name);
}elseif ($extension === 'gif'){
$orig = imagecreatefromgif($temp_name);
}
// work out the new dimensions.
if ($acceptedHeight === 0){
$newWidth = $acceptedWidth;
$newHeight = ($originalheight / $originalwidth) * $acceptedWidth;
}else if ($acceptedWidth === 0){
$newWidth = ($originalwidth / $originalheight) * $acceptedHeight;
$newHeight = $acceptedHeight;
}else{
$newWidth = $acceptedWidth;
$newHeight = $acceptedHeight;
}
$originalwidth = imagesx($orig);
$originalheight = imagesy($orig);
// make ssure they are valid.
if ($newWidth < 1){ $newWidth = 1; }else{ $newWidth = round($newWidth ); }
if ($newHeight < 1){ $newHeight = 1; }else{ $newHeight = round($newHeight); }
// don't bother copying the image if its alreay the right size.
if ($originalwidth!== $newWidth || $originalheight !== $newHeight){
// create a new image and copy the origional on to it at the new size.
$new = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($new, $orig, 0,0,0,0, $newWidth, $newHeight, $originalwidth, $originalheight);
}else{
// phps copy on write means this won't cause any harm.
$new = $orig;
}
// save the image.
if ($extension === 'jpeg' || $extension === 'jpg'){
imagejpeg($new, $path, 100);
}else if ($save_ext === 'gif'){
imagegif($new, $path);
}else{
imagepng($new, $path, round(9 - (100 / (100 / 9))));
}
$message = $path;
Can someone please let me know what is going on?
Check the original image is actually in the orientation you expect. I work with images all day and the majority of the time it's Windows Photo Viewer showing the image in a certain orientation (reading an orientation change in the EXIF) but if you open it up in Photoshop it's different.
I tested your code with two images: one was landscape (width > height), the other was portrait (height > width). The code works.
The problem seems to be what #Tavocado said: newer cameras have a sensor to detect the orientation of the camera when the photo was taken, and they store that info in the photo. Also, newer photo viewing software reads that info back from the photo and rotates it before displaying the image. So you all the time see the image with the right orientation (sky up, earth down). However PHP functions (and the rest of the world) don't use that information and display the image as is was taken. That means that you will have to rotate yourself portrait images.
Just load your images in the browser (drag the file on the address bar) you you will see how the image is really stored in the file, without any automatic rotation.
The problem is that the image has embedded EXIF data, probably from the device that took the photo.
Investigate whether your images have embedded rotation information, using exif_read_data, and then auto-correct the rotation with a function like this.
I'm working in my site which is in zen cart, actually a want to add a little functionality on it, and that is.... When I upload a image for a product I also want to create a thumbnail size of that image to be in a folder. Now I tried to search a file where the code to upload image goes on... I found a file in htdocs/admin_folder/includes/modules/new_product_preview.php
Now after getting details from user from a page htdocs/admin_folder/product.php it form post it in new_product_review.php page with a action defined in it and here the code for uploading image I've just simply added code as follows but it is not uploading the image in folder.
I've tried to echo the name of the file, so I've just put the alert for the image name parameters, I'm getting the $_FILES["products_image"]["tmp_name"] as something like, /tmp/gsnVaX.. like but
when I check $_FILES["products_image"]["name"] it gives the correct name of the file...
Why its not putting the image in temporary folder? When I put the resize code on it then it saves image in my folder with the same size which I wanted but whole image is just blank black.
Code is:
$image = "../images/thumbs/anki_".$_FILES["products_image"]["name"];
move_uploaded_file($_FILES["products_image"]["tmp_name"],$image);
and code when I'm doing this through resize is:
$control = "products_image";
$fileName = $_FILES[$control]['name'];
$uploadedfile = $_FILES[$control]['tmp_name'];
echo "<script>alert('".$fileName."');</script>";
$exts = explode(".",$fileName);
$ext = array_pop($exts);
$uploadedfile = $_FILES[$control]['name'];
$extension = $ext;
$extension = strtolower($extension);
if($extension=="jpg" || $extension=="jpeg" )
{
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
$newwidth = 140;
list($width,$height)=getimagesize($uploadedfile);
$newheight=($height/$width)*$newwidth;
$newheight = 135;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = "../images/thumbs/". $fileName;
imagejpeg($tmp,$filename,100);
imagedestroy($src);
imagedestroy($tmp);
What am I doing wrong with it?
When i made this function:
function makeThumbnail($type, $name, $size, $tmp_name, $thumbSize) {
//make sure this directory is writable!
$path_thumbs = "uploaded_files/";
//the new width of the resized image, in pixels.
$img_thumb_width = $thumbSize; //
$extlimit = "yes"; //Limit allowed extensions? (no for all extensions allowed)
//List of allowed extensions if extlimit = yes
$limitedext = array(".gif",".jpg",".png",".jpeg",".bmp");
//the image -> variables
$file_type = $type;
$file_name = $name;
$file_size = $size;
$file_tmp = $tmp_name;
//check if you have selected a file.
echo $file_tmp."<br>";
echo $file_name."<br>";
echo $file_type."<br>";
echo $file_size."<br>";
if(!is_uploaded_file($file_tmp)){
echo "Error: Please select a file to upload!. <br>--back";
exit(); //exit the script and don't process the rest of it!
}
//check the file's extension
$ext = strrchr($file_name,'.');
$ext = strtolower($ext);
//uh-oh! the file extension is not allowed!
if (($extlimit == "yes") && (!in_array($ext,$limitedext))) {
echo "Wrong file extension. <br>--back";
exit();
}
//so, whats the file's extension?
$getExt = explode ('.', $file_name);
$file_ext = $getExt[count($getExt)-1];
//create a random file name
$rand_name = md5(time());
$rand_name= rand(0,999999999);
//the new width variable
$ThumbWidth = $img_thumb_width;
/////////////////////////////////
// CREATE THE THUMBNAIL //
////////////////////////////////
//keep image type
if($file_size){
if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
$new_img = imagecreatefromjpeg($file_tmp);
}elseif($file_type == "image/x-png" || $file_type == "image/png"){
$new_img = imagecreatefrompng($file_tmp);
}elseif($file_type == "image/gif"){
$new_img = imagecreatefromgif($file_tmp);
}
//list the width and height and keep the height ratio.
list($width, $height) = getimagesize($file_tmp);
//calculate the image ratio
$imgratio=$width/$height;
if ($imgratio>1){
$newwidth = $ThumbWidth;
$newheight = $ThumbWidth/$imgratio;
}else{
$newheight = $ThumbWidth;
$newwidth = $ThumbWidth*$imgratio;
}
//function for resize image.
if (function_exists(imagecreatetruecolor)){
$resized_img = imagecreatetruecolor($newwidth,$newheight);
}else{
die("Error: Please make sure you have GD library ver 2+");
}
//the resizing is going on here!
imagecopyresampled($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
//finally, save the image
ImageJpeg ($resized_img,"$path_thumbs/$rand_name.$file_ext", 100);
ImageDestroy ($resized_img);
ImageDestroy ($new_img);
}
//ok copy the finished file to the thumbnail directory
// move_uploaded_file ($file_tmp, "$path_big/$rand_name.$file_ext");
/*
Don't want to copy it to a separate directory?
Want to just display the image to the user?
Follow the following steps:
2. Uncomment this code:
/*
/* UNCOMMENT THIS IF YOU WANT */
echo "OK THUMB " . $thumbSize;
exit();
//*/
//and you should be set!
//success message, redirect to main page.
$msg = urlencode("$title was uploaded! Upload More?");
}
Then it stopped working, but outside a function, it works good.
As you can see i added "echo $file...." because i wanted to see if they have value, and they do have the right values.
I just get the error Error: Please select a file to upload.
This function is running after an normal upload image script(full size).
When i call the function i do:
makeThumbnail($_FILES[$fieldname]['type'], $_FILES[$fieldname]['name'], $_FILES[$fieldname]['size'], $_FILES[$fieldname]['tmp_name'], 100);
At my other file where its not in a function, theres no difference only that the variables is:
$file_type = $_FILES['file']['type'];
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
But it should work, I cant find anything wrong, but it doesnt and i keep getting that error. If i remove the is_uploaded_file function, i get a bunch of another errors.
Make sure you are not using move_uploaded_file() before calling the function.
I use timthumb to process the image into a thumbnail when it outputs it to screen, instead of when it's uploaded.
It means you only have one file and not one master size and one thumb size. TimThumb reduces the size of the file on serverside so it appears nice and smooth on the browserside. Have a look at it: TimThumb Link