How to get Interventation/Image after Resize in Laravel - php

I used Interventation image to resize a big size uploaded image. But I don't want to save it into the local directory of Laravel. This is my sample source code.
public function Uploader(Request $request) {
$upload_file = $request->file_upload;
$new_img = Image::make($upload_file)->resize(800, 544);
$new_img->save(\public_path($fileName));
$upload_file_new = "../public/" . $fileName;
}
I want to get the new path of the resized image (by not by saving it). I used
$path = $new_img->basePath();
But it returns the basePath of the $upload_file. How can I get the new path so I can use it on fopen($upload_file_new, 'r'). Please help. Thank you.

you can do like this
$image_new_name = time() . str_random(10) . str_replace(' ','',$upload_file->getClientOriginalName());

Related

Intervention Image encode file extension

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

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

Trying to resize uploaded files as they are saved to server

I am using Glide to deliver image content from one of my sites. This is working well and I have now built a file upload so that admins can upload images to the site for subsequent download.
Some of the images that admins will upload will be much larger than I need (or want the overhead of storing on the server), so I want to downsize them, preferably during the upload routine or failing that, just after they have been saved to their new location (storage/app/images)
So, I've been hacking around with intervention for instance without much success because of my poor understanding of the file names and paths available from getClientOriginalName/Extension etc.
Could anyone show me a pattern for this which would work well. Ideally I'd love to include something like I've seen on others' examples like...
$img = Image::make('foo.jpg')->resize(300, 200);
... in the correct place in my code
foreach($files as $file) {
$fileExtension = $file->getClientOriginalExtension();
$fileMimeType = $file->getMimeType();
if(in_array($fileExtension, $allowableExtensions)) {
if(in_array($fileMimeType, $allowableMimes)) {
array_push($dbFileList, $file->getClientOriginalName());
$newImage = '/images/' . $propertyCode . '/' . $file->getClientOriginalName();
Storage::put('/images/' . $propertyCode . '/' . $file->getClientOriginalName(), file_get_contents($file));
}else{
$errorMessage = 'At least one file was not an image, check your results...';
}
}else{
$errorMessage = 'At least one file was not an image, check your results...';
}
}
Update 1:
Storage::put('/images/' . $propertyCode . '/' . $file->getClientOriginalName(), file_get_contents($file));
$img = Image::make($file);
Storage::put('/images/new/' . $file->getClientOriginalName(), $img);
This updated code outputs the files to the /new directory and all looks fine, but the output files have 'zero bytes'. What am I missing?
Update 2: Final code
The final answer (after using the proper code provided by contributors) was that:
I had to move my app from virtual box on to the dev machine (iMac) to prevent extra confusion with paths
The path for the images must exist prior to making the ->save()
The path variable must be set in advance of the ->save()
I don't need the Storage::put at all, so the larger file never ends up on the server.
Then this final code started to work.
$path = storage_path('app/smallpics/')."/".$file->getClientOriginalName();
$img = Image::make($file)->resize(300,200)->save($path);
Much thanks to all of you. You make my Laravel learning curve a bit less terrifiying!!
You can use Intervention to manipulate your image (resize etc.) as
$new_image = Image::make($file)->resize(300,200)->save('/path/to/save');
The image upload and resize work flow is like:
Upload the image from tmp to your directory.
Make a copy of that image by setting the height, width, quality and save it in the same or some other directory.
Delete the original image.
So as per your code flow:
Storage::put('/images/' . $propertyCode . '/' . $file->getClientOriginalName(), file_get_contents($file));
after this code, put the image compress code and after that delete the original image.
you can use Intervention or just use imagemagick convert command line command for resize or convert.
Pay attention to comments :
public function saveUploadPic(Request $request)
{
$pic = $request->file('<NAME_OF_FILE_INPUT_IN_HTML_FORM>');
#check for upload correctly
if(!$pic->isValid())
{
throw new Exception("IMAGE NOT UPLOADED CORRECTLY");
}
#check for mime type and extention
$ext = $pic->getClientOriginalExtension();
$mime = $pic->getMimeType();
if(!in_array($mime, $allowedMimeTypeArray) || !in_array($ext, $allowedExtArray))
{
throw new Exception("This Image Not Support");
}
#check for size
$size = $pic->getClientSize() / 1024 / 1024;
if($size > $allowedSize)
{
throw new Exception("Size Of Image Is More Than Support Size");
}
########################YOU HAVE TWO OPTION HERE###################
#1- save image in a temporary location with random hash for name if u need orginal image for other process
#below code save image in <LARAVEL_APP_PATH>/storage/app/tmp/pics/
$hash = md5(date("YmdHis").rand(1,10000));
$pic->storeAs('tmp/pics', $hash.'.'.$ext);
#Then resize or convert it
$img = Image::make(storage_path('app/tmp/pics/'.$hash.'.'.$ext))->resize(300, 200);
#save new image whatever u want
$img->save('<PATH_TO_SAVE_IMAGE>');
#after u finish with orginal image delete it
Storage::delete(storage_path('app/tmp/pics/'.$hash.'.'.$ext);
#2- Or just use below for resize and save image witout need to save in temporary location
$img = Image::make($pic->getRealPath())->resize(300,200);
$img->save('<PATH_TO_SAVE_IMAGE>');
}
if you want to use convert see this link.

Image upload and resize function not working as it must

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);

Upload an image and create its thumbnail Laravel 5.2

So yesterday I tried to make an upload file function , for when user makes his products, he can also upload a picture too.
But the picture was too big when I was iterating through the items, so I decided to use intervention package to resize the picture and also create a thumbnail picture.
I made the function but its partially working.
if($file = $request->hasFile('image')) {
$file = $request->file('image');
$extension = $file->getClientOriginalName();
$username = Auth::user()->username;
$destinationPath = public_path('/uploads/products/' . $username);
$thumb = Image::make($file->getRealPath())->resize(100, 100, function ($constraint) {
$constraint->aspectRatio(); //maintain image ratio
});
$thumb->save($destinationPath.'/thumb_'.$extension);
$destinationPath = public_path('/uploads/products/' . $username);
$file->move($destinationPath, $extension);
$product['imagePath'] = '/uploads/products/'. $username . '/' . $extension;
$product['thumbnail'] = '/uploads/products/'. $username . '/thumb_' . $extension;
}
I made it so, different user will create a different file in /uploads/products.
Also I upload the original picture and the resized so the I should have like:
picture.jpg and thumb_picture.jpg.
When the custom file is not created (from the name of the user) I get this error:
Can't write image data to path
(C:\xampp\htdocs\shop\public/uploads/products/book/thumb_Jellyfish.jpg)
When I comment 6,7,8 lines, the function works but it uploads only the original picture as it supposed to. If I remove the comment, the thumbnail works too!
So I guess, after the custom folder has been created, the whole function works fine, but before it has a writable problem.
Any ideas? Everything will be appreciated!
For anyone wonder how to fix this or do something similar, I just found the solution:
if($file = $request->hasFile('image')) {
$file = $request->file('image');
$extension = $file->getClientOriginalName();
$username = Auth::user()->username;
$thumb = Image::make($file->getRealPath())->resize(100, 100, function ($constraint) {
$constraint->aspectRatio(); //maintain image ratio
});
$destinationPath = public_path('/uploads/products/' . $username);
$file->move($destinationPath, $extension);
$thumb->save($destinationPath.'/thumb_'.$extension);
$product['imagePath'] = '/uploads/products/'. $username . '/' . $extension;
$product['thumbnail'] = '/uploads/products/'. $username . '/thumb_' . $extension;
}
So this piece of code makes a dynamic folder (I chose the username of the authenticated user) inside /uploads/products/. In that folder it uploads the picture and also creates a resized one, for thumbnail use. Also, when it creates the thumbnail, it holds the ratio of the original picture so it doesn't lose proportions

Categories