I am trying to upload various images into a dynamically created folder on my server, then take each image and resize it while uploading it into the folder as well creating a new image and a new name.. example: image.jpg (original image) and image-resized.jpg (being the thumbnail image).
The thing I can not figure out is how to resize all images. I am not sure if I should put it in a loop. All I need is for each image I upload (could be 5 a time). It loops through and resizes them all and not just a single image. Here is my code any help would be appreciated!
Code to create folders and move picture into those folders:
// Desired folder structure
$structure = './Fotos/'.$newfolder;
// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.
if (!mkdir($structure, 0, true)) {
die('Failed to create folders...');
}else{
$placefoldername = mysql_query("INSERT INTO datefolders (FolderDate) VALUES ('$newfolder')") or die(mysql_error());
echo "<div class=\"success\">El folder fue agregado con exito.<input type=\"button\" name=\"close\" value=\"X\" class=\"close\" /></div>";
}}
// ...
}
if(isset($_POST['upload'])){
$FolderDate = $_POST['fecha-folder'];
$FolderName = $_POST['FolderName'];
$hour = $_POST['hour'];
// Desired folder structure
$structure = './Fotos/'.$FolderDate.'/'.$hour.'/'.$FolderName;
// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.
for($i=0;$i<count($_FILES['fileupload']['name']);$i++) {
$names = $_FILES['fileupload']['name'][$i];
$target_path = "Fotos/".$FolderDate."/".$hour."/".$FolderName."/";
$target_path = $target_path . basename( $_FILES['fileupload']['name'][$i]);
if(move_uploaded_file($_FILES['fileupload']['tmp_name'][$i], $target_path)) {
$success = 1;
Code to create a smaller (resized image) and also place into the already created folder:
$img = $names;
$imgPath = $structure;
function resizeImage($img, $imgPath, $suffix, $by, $quality)
{
//Create a thunbnail image by resizing the picture
// Open the original image.
$original = imagecreatefromjpeg("$imgPath/$img") or die("Error Opening original (<em>$imgPath/$img</em>)");
list($width, $height, $type, $attr) = getimagesize("$imgPath/$img");
// Determine new width and height.
$newWidth = ($width/$by);
$newHeight = ($height/$by);
// Resample the image.
$tempImg = imagecreatetruecolor($newWidth, $newHeight) or die("Cant create temp image");
imagecopyresized($tempImg, $original, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height) or die("Cant resize copy");
// Create the new file name.
$newNameE = explode(".", $img);
$newName = ''. $newNameE[0] .''. $suffix .'.'. $newNameE[1] .'';
// Save the image.
imagejpeg($tempImg, "$imgPath/$newName", $quality) or die("Cant save image");
// Clean up.
imagedestroy($original);
imagedestroy($tempImg);
return true;
}
$resize = resizeImage($img, $imgPath, "-resized", 23, 100);
Why are you defining the function resizeImage in the for loop? It is being redefined every time the loop iterates. This could be part of the problem. Define the function outside the loop and see if that works.
you can try;
when your first image proccess end use imagedestroy() then second image will proccessed.
Related
I have problem with my reszie image (code) when I run this code in localhost the code is work fine, but when I implement in website. the code give a warning.
<br /><b>Warning</b> : imagecreatefromjpeg([-1, [], 17, 1, 18, 1, 19, 23, true, [true, true],26,1,27,1,30,1,33]) expects parameter 1 to be resource, boolean given in <b>fungsi/f_upload_banner.php</b> on line <b>34</b><br />
This is my code for resize
<?php
$target_dir = "../uploads/images/banner/";
$image1 =$_FILES['txtfile']['name'];
$filename1 = stripslashes($_FILES['txtfile']['name']);
$ext1 = substr($image1, strrpos($image1, '.')+1);
$idimg1 = md5(uniqid() . time() . $filename1) . "-1." . $ext1;
$target_file1 = $target_dir . basename($idimg1);
//identify images file
$realImages = imagecreatefromjpeg($target_file1);
$width = imageSX($realImages);
$height = imageSY($realImages);
//save for thumbs size
$thumbWidth = 150;
$thumbHeight = ($thumbWidth / $width) * $height;
//change images size
$thumbImage = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($thumbImage, $realImages, 0,0,0,0, $thumbWidth, $thumbHeight, $width, $height);
//save thumbnail images
imagejpeg($thumbImage,$target_dir."thumb_".$idimg1);
//remove images object from memory
imagedestroy($realImages);
imagedestroy($thumbImage);
?>
Where is wrong?
You're trying to use the original file name (after mangling) as the source for imagecreatefromjpeg(), when you should be using the temporary name assigned by the upload process: $_FILES['txtfile']['tmp_name']
Do this:
$realImages = imagecreatefromjpeg($_FILES['txtfile']['tmp_name']);
You're also not moving the uploaded file to a permanent location. The temporary version will be deleted when your script terminates and the file will be lost.
Note also that your code is doing no error checking whatsoever, so if your upload fails you won't know about it. See the PHP section on Handling File Upload
I applied a filter to the .jpg images of a folder as follows:
$images = glob('images/*.jpg');
foreach($images as $image) {
$image_prefix = "image-beautiful-";
$image = imagecreatefromjpeg($image);
$rand = rand(50, 500);
imagefilter($image, IMG_FILTER_COLORIZE, 75, 15, 10);
$new_image = imagejpeg($image, $image_prefix .$rand.'.jpg');
imagedestroy($image);
}
The generated images save in the main directory. How can I directly save them to another folder like generated-images using PHP?
according to the doco for imagejpg, the second parameter is the path and filename, so try adding the folder to the image prefix:
$image_prefix = "generated-images" . DIRECTORY_SEPARATOR . "image-beautiful-"
I am working on project its about gemstone where I make admin panel where user can upload images am trying to resize the images it work some how but it give me black output in given dir where I am uploading .
Here is my code .
$target_path = SITE_ROOT .DS. $this->upload_dir .DS. $this->filename;
// Make sure a file doesn't already exist in the target location
if(file_exists($target_path)) {
$this->errors[] = "The file {$this->filename} already exists.";
return false;
}
// i am trying to resize the image
if( copy ($this->temp_path,$this->filename) or die ("Could not copy")){
$imagefile=$this->filename;
list($width, $height) = getimagesize($this->filename);
$image_p = imagecreatetruecolor($this->new_width,$this->new_height);
if ($this->type =='jpg')
{
$img = imagecreatefromgif($imagefile);
imagecopyresampled($image_p, $img, 0, 0, 0, 0, $this->new_width,$this->new_height, $width, $height);
imagegif($image_p,$target_path);
}
else{ echo 'something went wrongs';}
}
// Attempt to move the file
if(move_uploaded_file($this->temp_path, $target_path)) {
// Success
// Save a corresponding entry to the database
if($this->create()) {
// We are done with temp_path, the file isn't there anymore
unset($this->temp_path);
return true;
}
} else {
// File was not moved.
$this->errors[] = "The file upload failed, possibly due to incorrect permissions on the upload folder.";
return false;
}
First of all change the imagecopyresampled function to imagecopyresized function.
imagecopyresized($image_p, $img, 0, 0, 0, 0, $new_width,$new_height, $width, $height);
Than change the function from imagecreatefromgif to imagecreatefromjpeg because you are using jpg in if condition.And write the path below i have given like that.
move_uploaded_file($this->temp_path, imagejpeg($image_p,$target_path,100));
And sure to unlink if you don't than it will bring you two image files because you are using copy function be sure to unlink.
unlink($this->filename);
I have just done it. I hope it will work for you too.
This script will load an image (jpg, gif or png) and then save a PNG local copy for caching.
I'm trying to find a way to resize the image to 300x300 before saving it as a PNG.
I tried to use the function imagecopyresampled() but the image is still not resized.
2 problems now :
The script saves a resized PNG image in the correct folder, but the image is empty (it's all black)
The first time i will load the image, i will get an error (image cannot be displayed because it contains error) but the image will still be saved as PNG in the cache folder. Second time i load the image, it will be displayed correctly (using the cached version) but it isn't resized.
Here's the full code of my page. The first part is used to cache the image, the second part is used to display the non-cached image (it reads an image from a ZIP file and output the content without extracting anything)
if (empty($_GET['display'])) {
header('Content-Type: image/png');
$imgpochette = $_GET['i'];
$ENABLE_CACHE = true;
$CACHE_TIME_HOURS = 744;
$CACHE_FILE_PATH = "pochette_album/$imgpochette.png";
if($ENABLE_CACHE && file_exists($CACHE_FILE_PATH) && (time() - filemtime($CACHE_FILE_PATH) < ($CACHE_TIME_HOURS * 60 * 60))) {
echo #file_get_contents($CACHE_FILE_PATH);
} else {
// Load the requested image
$imgdisplay = "http://www.pirate-punk.com/pochette.php?i=$imgpochette&display=1";
$image = imagecreatefromstring(file_get_contents($imgdisplay));
$width = "30";
$height = "30";
list($originalWidth, $originalHeight) = getimagesize($CACHE_FILE_PATH);
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $width, $height, $originalWidth, $originalHeight);
// Send the image
imagepng($new_image, $CACHE_FILE_PATH);
exit();
#file_put_contents($CACHE_FILE_PATH, $output);
echo $output;
}
}
if (!empty($_GET['display'])) {
function showimage($zip_file, $file_name) {
$z = new ZipArchive();
if ($z->open($zip_file) !== true) {
echo "File not found.";
return false;
}
$stat = $z->statName($file_name);
$fp = $z->getStream($file_name);
// search for a path/to/file matching file, returning the index of it
$index = $z->locateName($file_name, ZipArchive::FL_NOCASE|ZipArchive::FL_NODIR);
// get the name of the file based on the index
$full_file_name = $z->getNameIndex($index);
// now get the stream
$fp = $z->getStream($full_file_name);
if(!$fp) {
echo "Could not load image.";
return false;
}
header('Content-Type: image/jpeg');
header('Content-Length: ' . $stat['size']);
fpassthru($fp);
return true;
}
$imgsrcencoded = $_GET['i'];
$imagesrc = base64_decode($imgsrcencoded);
$explodez = explode("#",$imagesrc);
$imgg = utf8_encode($explodez[1]);
$dirnfile = $explodez[0];
$zipp = end((explode('/', $dirnfile)));
$dirr = str_replace($zipp,"",$dirnfile);
$dirr = rtrim($dirr,"/");
$imgg = rtrim($imgg);
chdir($dirr);
if (empty($_GET['debug'])) {
echo showimage($zipp,$imgg);
}
}
Get the solution for .png images
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