I want to create a image dynamically and upload it to a folder. I will be getting image for body,sleeve,collar and cuff dynamically from user selection. I am merging all these images to create a new image and this new image to uploaded in a folder. Am not able to upload the filename to folder and there is no errors displaying also but am able to generate the merged image.
Below is code,
<?php
$body = "img1.jpg";
$sleeve = "img2.jpg";
$collar = "img3.jpg";
$cuff = "img4.jpg";
$outputImage = imagecreatetruecolor(800, 800);
$background = imagecolorallocate($outputImage, 0, 0, 0);
imagecolortransparent($outputImage, $background);
$white = imagecolorallocate($outputImage, 255, 255, 255);
imagefill($outputImage, 0, 0, $white);
$first = imagecreatefrompng($body);
$second = imagecreatefrompng($sleeve);
$third = imagecreatefrompng($collar);
$fourth = imagecreatefrompng($cuff);
imagecopyresized($outputImage,$first,0,0,0,0,600,600,600,600);
imagecopyresized($outputImage,$second,0,0,0,0,600,600,600,600);
imagecopyresized($outputImage,$third,0,0,0,0, 600, 600, 600, 600);
imagecopyresized($outputImage,$fourth,0,0,0,0,600,600,600,600);
$filename = round(microtime(true)).'.png';
imagepng($outputImage, $filename);
define('DIR_IMAGE', '/opt/lampp/htdocs/dutees/image/design-uploads/');
$ret = move_uploaded_file($filename, DIR_IMAGE.$filename);
print_r(error_get_last());
if($ret)
{
echo "success";die;
}
else
{
echo "fail";die;
}
imagedestroy($outputImage);
?>echo "fail";die;
}
imagedestroy($outputImage);
?>
move_uploaded_file won't work on $filename because it's not an uploaded file - it was just created by your code.
Try switching the two lines (like below) and adding your path:
define('DIR_IMAGE', '/opt/lampp/htdocs/dutees/image/design-uploads/');
imagepng($outputImage, DIR_IMAGE . $filename);
And remove the move_uploaded_file line:
//$ret = move_uploaded_file($filename, DIR_IMAGE.$filename);
you are using imagepng(), That saves file to particular location you are providing.
Syntax for imagepng() :
bool imagepng ( resource $image [, mixed $to [, int $quality [, int $filters ]]] )
where $to refers to location where you want to save your image (including filename).
So instead of
$filename = round(microtime(true)).'.png';
imagepng($outputImage, $filename);
define('DIR_IMAGE', '/opt/lampp/htdocs/dutees/image/design-uploads/');
$ret = move_uploaded_file($filename, DIR_IMAGE.$filename);
Try This,
$filename = round(microtime(true)).'.png';
define('DIR_IMAGE', '/opt/lampp/htdocs/dutees/image/design-uploads/');
imagepng($outputImage, DIR_IMAGE.$filename);
You don't need move_uploaded_file() anymore, because the image created is already in your server.
I also had similar problem while creating captcha for new users, and This solution worked.
You should try file_put_contents instead of move_uploaded_file.
file_put_contents('you_file_location/filename', IMAGE_OBJECT_HERE);
or you can also save file using fwrite function.
Related
i have created dynamic watermark image when user uploads using php, images are also displaying , but the problem is i don't know how to move the images into particular folder in my site
$path=JPATH_SITE.'/media/truematrimony/watermark-K'.$id.'_pho_2.jpg';
move_uploaded_file($_FILES["profile_multi2"]["tmp_name"],$path);
$font_path=$_SERVER['DOCUMENT_ROOT'].'/templates/srinivasmatrimony/font/GeosansLight.ttf';
$card = imagecreatefromjpeg($path);
$font_med = 12;
$white = imagecolorallocate($card, 0, 0, 0);
imagettftext($card, $font_lrg, , 40, , $white, $font_path,"kongumarriage.com");
$filenametemp= $_SERVER['DOCUMENT_ROOT'].'/media/truematrimony/watermark- K'.$id.'_pho_2.jpg';
imagejpeg($card, $filenametemp);
$ImageData = file_get_contents($filenametemp);
$ImageDataEnc = base64_encode($ImageData);
unlink($filenametemp);
Use the following function
move_uploaded_file ( string $filename , string $destination )
$filename - name of the file to move
$destination = folder where you want to move
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 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.
I use this piece of code to make thumbnails of an uploaded image.
$file = randString().'.jpg';
$uniPath = 'i/u'.$login;
$completePath = $uniPath.'/a/'.$file;
$thumbPath = $uniPath.'/b/'.$file;
if(copy($_FILES['filename']['tmp_name'], $completePath)){
function convertPic($w_dst, $h_dst, $n_img){
$wxh = $w_dst.'x'.$h_dst;
switch($wxh){
case '150x150': $letter = 'b'; break;
case '50x50': $letter = 'c'; break;
default: $letter = 'z';
}
$dbPath = '/i/u1/'.$letter.'/'.$n_img;
$new_img = $_SERVER['DOCUMENT_ROOT'].$dbPath;
$file_src = "img.jpg"; // temporary safe image storage
$img_src = $file_src;
unlink($file_src);
move_uploaded_file($_FILES['filename']['tmp_name'], $file_src);
list($w_src, $h_src, $type) = getimagesize($file_src); // create new dimensions, keeping aspect ratio
$ratio = $w_src/$h_src;
$h_ratio = ($h_dst / $h_src);
$w_ratio = ($w_dst / $w_src);
if($w_src > $h_src){ //landscape
$w_crop = round($w_src * $h_ratio);
$h_crop = $h_dst;
$src_x = ceil(($w_src - $h_src)/2);
$src_y = 0;
}
elseif($w_src < $h_src){ // portrait
$h_crop = round($h_src * $w_ratio);
$w_crop = $w_dst;
$src_y = ceil(($h_src - $w_src)/2);
$src_x = 0;
}
else { //square
$w_crop = $w_dst;
$h_crop = $h_dst;
$src_x = 0;
$src_y = 0;
}
switch ($type)
{case 1: // gif -> jpg
$img_src = imagecreatefromgif($file_src);
break;
case 2: // jpeg -> jpg
$img_src = imagecreatefromjpeg($file_src);
break;
case 3: // png -> jpg
$img_src = imagecreatefrompng($file_src);
break;
}
$img_dst = imagecreatetruecolor($w_dst, $h_dst); // resample
imagecolorallocate($img_dst, 255, 255, 255) or die("fail imagecolorallocate");
imagecopyresampled($img_dst, $img_src, 0, 0, $src_x, $src_y, $w_crop, $h_crop, $w_src, $h_src) or die("imagecopyresampled($img_dst, $img_src, 0, 0, $src_x, $src_y, $w_crop, $h_crop, $w_src, $h_src)");
imagejpeg($img_dst, $new_img); // save new image
unlink($file_src); // clean up image storage
imagedestroy($img_src);
imagedestroy($img_dst);
return $db_path;
}
convertPic(150, 150, $file);
convertPic(250, 250, $file);
But for some reason the convertPic function does not work if called twice as in the example above. If it is called once everything works fine. I've put an alert if imagecopyresampled fails and it outputs
imagecopyresampled(Resource id #17,
img.jpg, 0, 0, 0, 0, 250, 250, , )
I think the problem is with the temporary image storing but not sure. Please help.
It would appear that you're processing an uploaded image. As part of the processing function, you move the uploaded file from its temporary directory, and then do some work on it.
When you call the function again the second time, the uploaded file is not longer in the temporary directory, and things blow up.
function convertPic(...) {
....
move_uploaded_file($_FILES['filename']['tmp_name'], $file_src);
....
unlink($file_src);
....
}
Basically the first call to convertPic processes and then deletes the "source", which means it's no longer available for the second call immediately afterwards.
I guess problem is with unlink($file_src)...
First, you call convertPic() function and it works OK because your img.jpg is still here, then you remove your image with unlink() and try to call again same routine that actually needs this file to work properly.
Also you can't move same file twice, so you have to move it outside the function, do your job as many times as needed, and after that, unlink image. Unlink should be after double-call of convertPic(), and move_uploaded_file() should be before function convertPic().
Well, that's what I think on first sight.