Rotate and save a photo in laravel - php

I want to upload photos in server. But before that I want to rotate that image.
My code is like below,
$photo = $request->file($field);
$temp = imagecreatefromjpeg($photo);
$rotated = imagerotate($temp, 270, 0);
$extension = $photo->getClientOriginalExtension();
$flieNametoStore = time()."___".explode('.',$photo->getClientOriginalName())[0].'.'.$extension;
Storage::disk('public')->put($flieNametoStore, $rotated);
It is not working. It shows error like supplied resource is not a valid stream resource.
I also tried Storage::disk('public')->put($flieNametoStore, File::get($rotated)); but still it doesn't work.
So, I have two questions.
What can I do to achieve my objective? (rotate and save in server.)
Also, I have used imagecreatefromjpeg function. However, I want to execute same code for other file type.(All types supported by laravel validation of image.)
I searched in SO and found some similar questions. However, those solutions are not giving me my desired output.

use imagejpeg function for save photo
imagerotate return a gd resource type not resource...
$photo = request()->file($field);
$temp = imagecreatefromjpeg($photo);
$rotated = imagerotate($temp, 270, 0);
$extension = $photo->getClientOriginalExtension();
$flieNametoStore = time() . "___" . explode('.', $photo->getClientOriginalName())[0] . '.' . $extension;
imagejpeg($rotated, $flieNametoStore);
or
ob_start();
imagejpeg($rotated);
$rotated = ob_get_contents();
ob_clean();
Storage::disk('public')->put($flieNametoStore, $rotated);

Related

Image with laravel

Problem with laravel Image:
I have my code to store the image and it is:
$img = Image::make(asset('public/storage/assets/'.$product->image));
$img->insert(asset('template/images/logo-1000frases-w.png'), 'bottom-left', 10, 10);
$img->save(public_path('public/storage/assets/'.$product->image));
I add a watermark on the image and then I store it.
The problem is.. when I try to store the image it says:
Unable to init from given url (http://138.197.121.221/public/storage/assets/ijTdImC4dIcobYa1QSDA59oDiF8J8e0FjQS1EG3n.jpeg).
But I have the correct path... public, storage, assets, all of them exist; I wonder what could it be?
Thanks!
you may upload your imgae in laravel 5 using this way
$image=$request->file('image');
$fileName=$image->getClientOriginalName();
$path = $image->move('storage/assets/',$fileName);
$folderPath=url('/).''.'/uploads/blog/'.''.$fileName;
image is your key for request image. $folderPath variable is use for save in your database table. This may work for you
I could get a solution:
$file = $request->file('image');
$fileName = time() . '-' . $file->getClientOriginalName();
$path = $file->move('storage/assets/',$fileName);
Then:
$img = Image::make($path);
$img->insert(asset('template/images/logo-1000frases-w.png'), 'bottom-left', 10, 10);
$img->save(public_path('storage/assets/'.$product->image));
And this is it! :D

Php Image creation and upload to folder

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.

Create a unique name for the uploaded image

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'];

Resize copied image on upload as thumbnail

I am working on an uploader and slowly getting it working, I am uploading 3 images at once, and setting arrays for each one as keys, with an increment of ++1. I am wanting to resize the image before it gets copied to the thumbnail folder.
I have this code.
Everything works with it.
As you see, I started on getting the file info, but after that I am totally stuck on what to do after to resize the image proportionally with a maximum width of xpx and height to match it without looking distorted.
Any help would be really appreciated. Thank You.
EDIT --- I started working on it myself and wondering if this is the right approach to what i am doing.
<?php
if (isset($_POST['addpart'])) {
$image = $_FILES['images']['tmp_name'];
$name = $_POST['username'];
$i = 0;
foreach ($image as $key) {
$fileData = pathinfo(basename($_FILES["images"]["name"][$i]));
$fileName[] = $name . '_' . uniqid() . '.' . $fileData['extension'];
move_uploaded_file($key, "image/" . end($fileName));
copy("image/" . end($fileName), "image_thumbnail/" . end($fileName));
// START -- THE RESIZER THAT IS BEING WORKED ON
$source = "image_thumb/" . end($fileName);
$dest = "image_thumb/" . end($fileName);
$quality = 100;
$scale = 1 / 2;
$imsize = getimagesize($source);
$x = $scale * $imsize[0];
$y = $scale * $imsize[1];
$im = imagecreatefromjpeg($source);
$newim = imagecreatetruecolor($x, $y);
imagecopyresampled($newim, $im, 0, 0, 0, 0, $x, $y, $imsize[0], $imsize[1]);
imagejpeg($newim, $dest, $quality);
// END -- THE RESIZER THAT IS BEING WORKED ON
$i++;
}
echo 'Uploaded<br>';
echo 'Main Image - ' . $fileName[0] . '<br>';
echo 'Extra Image 1 - ' . $fileName[1] . '<br>';
echo 'Extra Image 2 - ' . $fileName[2] . '<br>';
echo '<hr>';
}
?>
thanks
Use GD library.
Create input image object using imagecreatefromstring() for example: imagecreatefromstring(file_get_contents($_FILES['images']['tmp_name'][$i]))
It's the simplest way.
Another option is to detect file type and use functions like imagecreatefromjpeg (), imagecreatefrompng(), etc.
Create output empty image using imagecreate()
Use imagecopyresampled() or imagecopyresized() to resize image and copy+paste it from input image to output image
Save output image using function like imagejpeg()
Clean memory using imagedestroy()
The built-in image manipulation commands of PHP makes your code difficult to understand and to maintain. I suggest you to use a library which wraps it into a more productive way.
If you use Intervention/image, for example, your code will look like this:
<?php
// target file to manipulate
$filename = $_FILES['images']['tmp_name'];
// create image instance
$img = Image::make($filename);
// resize to width, height
$img->resize(320, 240);
// save it!
$img->save('thumbs/'. uniqid() . '.' . pathinfo($filename, PATHINFO_EXTENSION));
Read the full documentation here: http://image.intervention.io/use/uploads

Creating thumbnails PHP problem

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...

Categories