I have a question on how to filter image while moving the file. I used uploadify to upload image. What I did is, before he move the image to the directory, the code filter will covert the image to grayscale.
Here is my code
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
$newImg = imagefilter($tempFile, IMG_FILTER_GRAYSCALE); // This is what I insert
move_uploaded_file($newImg,$targetFile);
echo "1";
}
The code is uploadify.php and I just inserted a filter to make it grayscale. Please help me. Thanks in advance.
Imagefilter works on an image resource, not a file, and also a boolean, not a new image. It's probably worth reading through the documentation, but you'll need to change your code to something along these lines
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
// Create an image resource - exact method will depend on the image type (PNG, JPEG, etc)
$im = imagecreatefrompng($tempFile);
// Apply your filter
imagefilter($im, IMG_FILTER_GRAYSCALE);
// Save your changes
imagepng($im, $tempFile);
move_uploaded_file($tempFile,$targetFile);
echo "1";
}
To use imagefilter you have to load image first. Use one of GD load functions ( like: imagecreatefrompng).
Then you can use filter on loaded image. By the way check parameters for imagefilter (which requires loaded image, not path to image). Here is some example code (that replaces your imagefilter()):
// Check extension of the file, here is example if the file is png, but you have to check for extension and use specified function
$img = imagecreatefrompng($tempFile);
if( imagefilter($img, IMG_FILTER_GRAYSCALE) )
{
// success
}
else
{
// failture
}
// Save file as png to $targetFile
imagepng($img, $targetFile);
// Destroy useless resource
imagedestroy($img);
Related
I'm trying to change all images uploaded to png format. I'm using the Intervention Image package for Laravel, and calling the encode function. Image Files are not changing to .png
Here is my upload script: (Everything is uploading, resizing and appears to be compressing. Just not converting to a png file)
if($request->hasFile('listing_image')){
$classifiedImg = $request->file('listing_image');
$filename = 'listing'.'-'.uniqid().'.'.$classifiedImg->getClientOriginalExtension();
Image::make($classifiedImg)->encode('png', 65)->resize(760, null, function ($c) {
$c->aspectRatio();
$c->upsize();
})->save(public_path('/images/users/listing-images/' . $filename));
$classified->listing_image = $filename;
$classified->save();
}else{
$classified->save();
}
Am I doing something wrong in this section:
Image::make($classifiedImg)->encode('png', 65)->resize(760, null, function ($c)...
OR is this causing the issue:
getClientOriginalExtension();
Thanks BagusTesa, you were correct. This was causing the issue.
getClientOriginalExtension();
To get the extension to convert. I needed to add the extension to the file name.
Change this line:
$filename = 'listing'.'-'.uniqid().'.'.$classifiedImg->getClientOriginalExtension()
To This:
$filename = 'listing' . '-' . uniqid() . '.png';
I have simple resize image function in my laravel project. It should upload original image and make thumbnail of it.
After form submitting I got two images but the original image is placed in wrong directory. This is the function in my controller
if (Input::hasFile('image') && !Input::get('remove_image')) {
$file = Input::file('image');
$filename = str_random(20);
$image = new ImageResize($file);
$original = $filename . '.'. $file->getClientOriginalExtension();
$thumb = $filename . '-thumb.' . $file->getClientOriginalExtension();
$file->move(public_path() . '/uploads', $original);
$imagePath = '/uploads/' . $original;
$thumbPath = '/uploads/' . $thumb;
$image->crop(200, 200);
$image->save('uploads/' . $thumb);
}
Basically when I upload image.jpg I get two images image.jpg and image-thumb.jpg. Both images should be save in uploads i.e. public/uploads/ BUT only thumbnail is saved there.
The original image is saved in **bootstrap**/uploads/. Why is going in bootstrap... directory? I didn't mentioned it anywhere?
You can try to replace the public_path() method to url('/'). Not sure this will help but I don't have good experiences with public_path()
Image::make($request->file('image'))->resize(462, 462)->save('upload_path/filename.jpg'));
Try This Code..
Use Image Intervention to resize and save the image
Image::make($avatar)->resize(250, 250)->save(public_folder('/uploads/'.$filename));
The resize function will resize the image and save function will save the image to uploads folder. Give a desired filename to $filename variable.
Leave only the directory to where you want to save the original. Try to change this line which is moving the image
$file->move(public_path() . '/uploads', $original);
with this one ( remove the public path )
$file->move('uploads', $original);
I have a certain code for image upload .I found this on the internet and there was no explanation of the code either.What i can understand from the code is that php upload a certain file makes it a temporary file and then moves the temporary file to the original location
Code Looks something like this
$filename = $_FILES["img"]["tmp_name"];
list($width, $height) = getimagesize( $filename );
move_uploaded_file($filename, $imagePath . $_FILES["img"]["name"]);
What happens now is that when i try to provide an unique name to the image when it is being moved using the move_uploaded_file then a file does come up inside the folder but it says an invalid file and with the extension type of file.
My code for trying to achieve the same but with an unique name/id for the uploaded image.
$uniquesavename=time().uniqid(rand());
$filename = $_FILES["img"]["tmp_name"];
list($width, $height) = getimagesize( $filename );
move_uploaded_file($filename, $imagePath . $uniquesavename);
How to achieve the same as before and could you please explain me the previous code as well?
Sample code:
// Get file path from post data by using $_FILES
$filename = $_FILES["img"]["tmp_name"];
// Make sure that it's a valid image which can get width and height
list($width, $height) = getimagesize( $filename );
// Call php function move_uploaded_file to move uploaded file
move_uploaded_file($filename, $imagePath . $_FILES["img"]["name"]);
Please try this one:
// Make sure this imagePath is end with slash
$imagePath = '/root/path/to/image/folder/';
$uniquesavename=time().uniqid(rand());
$destFile = $imagePath . $uniquesavename . '.jpg';
$filename = $_FILES["img"]["tmp_name"];
list($width, $height) = getimagesize( $filename );
move_uploaded_file($filename, $destFile);
Edit 1:
To get image type in two ways:
Get the file type from upload file name.
Use php function as below
CODE
// Get details of image
list($width, $height, $typeCode) = getimagesize($filename);
$imageType = ($typeCode == 1 ? "gif" : ($typeCode == 2 ? "jpeg" : ($typeCode == 3 ? "png" : FALSE)));
$name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$location = "uploads/";
$new_name = $location.time()."-".rand(1000, 9999)."-".$name;
if (move_uploaded_file($tmp_name, $new_name)){
echo "uploaded";
}
else{
sleep(rand(1,5));
$new_name = $location.time()."-".rand(1000, 9999)."-".$name;
if (move_uploaded_file($tmp_name, $new_name)){
echo "uploaded";
}
else{
echo"failed, better luck next time";
}
}
here, location is folder inside directory, i mainly create folder "uploads"
time() adds timestamp , which is always unique, until two person upload at same time, which is rare.
moreover, adding 4 digit random number to it , making combination rarest
after that adding actual file name , to making combination unique.
why i use it :
u can extract timestamp later if u need to know when image was uploaded.
u can extract actual filename too.
Lets, say our so unique combination somehow fails,
then, php instance will wait for 1 to 5 second whatever random number is generated. and rename with latest timestamp and regenerated random number.
It's the best u can think of without being resource hog.
you can use
$strtotime = strtotime("now");
$filename = $strtotime.'_'.$_FILES['file']['name'];
I want to create a watermark using my own text for example. I want to create watermark of "ABDULLAH" on each image. I have these lines of code in my uploadify.php file.
<?php
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$ext = end(explode(".", $_FILES['Filedata']['name']));
$FileName = current(explode('.', $_FILES['Filedata']['name']));
$originalFileName = $FileName.".".$ext;
$strRandNum = rand(0,99)+strtotime(date('YmdHis'));
$randomeFileName = $FileName."_".$strRandNum."_uid_".$_REQUEST['user_id'];
$completeFileName = $randomeFileName.".".$ext;
$dir_path = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] .'/'. $dirctory_name. "/";
if( (isset ($dirctory_name)) && ($dirctory_name != "") && (is_dir ($dir_path)) ) {
move_uploaded_file($tempFile,$dir_path.$completeFileName);
}
else {
mkdir($dir_path , 0777);
move_uploaded_file($tempFile,$dir_path.$completeFileName);
}
str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile);
}
?>
well, you can't do it with javascript "uploadify" mr Abdullah
you have to use the php gd lib to be able to put watermark
and that is done AFTER the image is uploaded not during upload
check this out
http://www.sitepoint.com/watermark-images-php/
You're probably going to need some form of server-side functionality.
CodeIgniter provides a built-in and easy way of adding watermarks to images during the file upload process. Check out their documentation for uploading files and image manipulation.
I have this source code where I got it from net tutsplus. I have configured it and made it work in one PHP file. It does work by transferring the original image, but it does not generate to the thumbnails folder.
<?php
$final_width_of_image = 100;
$path_to_image_directory = "../../img/events/" . urldecode($_GET['name']) . "/";
$path_to_thumbs_directory = "../../img/events/" . urldecode($_GET['name']) . "/thumbnails/";
function createThumbnail($filename)
{
if(preg_match('/[.](jpg)$/', $filename))
{
$im = imagecreatefromjpeg($path_to_image_directory . $filename);
}
elseif(preg_match('/[.](gif)$/', $filename))
{
$im = imagecreatefromgif($path_to_image_directory . $filename);
}
elseif(preg_match('/[.](png)$/', $filename))
{
$im = imagecreatefrompng($path_to_image_directory . $filename);
}
$ox = imagesx($im);
$oy = imagesy($im);
$nx = $final_width_of_image;
$ny = floor($oy * ($final_width_of_image / $ox));
$nm = imagecreatetruecolor($nx, $ny);
imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);
imagejpeg($nm, $path_to_thumbs_directory . $filename);
$tn = '<img src="' . $path_to_thumbs_directory . $filename . '" alt="image" />';
echo $tn;
}
if(isset($_FILES['fupload'])) {
if(preg_match('/[.](jpg)|(gif)|(png)$/', $_FILES['fupload']['name'])) {
$filename = $_FILES['fupload']['name'];
$source = $_FILES['fupload']['tmp_name'];
$target = $path_to_image_directory . $filename;
move_uploaded_file($source, $target);
createThumbnail($filename);
}
}
?>
Basically it is supposed to generate a thumbnail of the uploaded image and store the original image into a different folder.
The paths are correct, it works by getting the folder name in the URL, it does work, but nothing works for the thumbnails folder.
BEFORE you ask this related question, yes, thumbnails generation does work on my server by the PHP GD, I have tested it separately. So this is not the problem. :)
How do I get this to work? :(
Well, first off, use imagecopyresampled(), as it will generate a better thumbnail.
Secondly, you shouldn't use the same variable for filesystem directory and for url directory. You should have $filesystem_path_to_thumbs and $url_path_to_thumbs. So you can set them differently.
Third, you may want to do a size check for both width and height. What happens if someone uploads a tall image? Your thumbnail will be outside the target box (but this may not be a big issue).
Fourth, you should prob do a check to see if the thumbnail file exists in the thumbs directory before generating the thumbnail (for performance reasons)...
Finally, the reason it's actually failing, is $final_width_of_image, $path_to_image_directory and $path_to_thumbs_directory are not defined within the function. Either:
Make them global at the start of the function, so you can access them inside of the function global $final_width_of_image, $path_to_image_directory, $path_to_thumbs_directory;
Make them arguments to the function: function createTumbnail($image, $width, $path_to_images, $path_to_thumbs) {
Hard code them inside of the function (Move their declaration from outside the function to inside the function).
Personally, I'd do #2, but it's up to what your requirements and needs are...