Unable to create thumbnail while image is uploading in Laravel - php

I'm trying to create thumbnail of image while it is uploading. The problem is that the thumbnail isn't created at all. Also is not saved in database.
This is what I have added in my function
$image = $request->file('image');
if( $image && $image->isValid()){
$imagename = str_random(20).'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/uploads');
$thumb_img = Image::make($image->getRealPath())->resize(100, 100);
$thumb_img->save($destinationPath.'/'.$imagename,80);
$image->move($destinationPath, $imagename);
}
$item->image = $filename;
$item->image_thumb = $thumb_img;
It's saves only the original image both places - uploads dir and in database but nothing regarding the thumbnail.
I'm using Intervention package.

Nothing is saving because you override the same image twice. Look what you have:
First, you creating thumbnail and saves it into the /uploads
After this, you save the original into the same directory with same name e.g. overriding the thumb.
You just need to make different name for the thumbnail:
$thumb_img = Image::make($image)->resize(100, 100)->save($destinationPath.'/thumb_'.$imagename, 80);
Notice the prefix for the thumb thumb_...

Related

Encoding format (tmp) is not supported for image resize laravel

i want to resize uploaded image and store in folder.then show in web.
i used enctype="multipart/form-data" on form in blade.php.
file successfully show in web without resize.
when try to resize image i got error
controller.php
public function dili(Request $request)
{
$di = new diligent;
$di->jobtype = $request->jobtype;
$di->jobC = $request->jobC;
$di->details = $request->details;
$image = $request->file('image');
$path = $image->getClientOriginalName();
$destinationPath = public_path('img');
Image::make($image)->resize(300, 100)->save($image);
$a = $image->move($destinationPath, $path);
$di->image = $path;
$di->save();
$de = diligent::all();
return view('admin')->with('dw', $de);
}
Error Message
Encoding format (tmp) is not supported.
1) use getRealPath() inside Image::make()
2) save image in particular path. try like this.
if($request->hasFile('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(300, 100);
$image_resize->save(public_path('img/' .$filename));
}
Make sure you installed Image intervention library.
The Intervention image save() method requires a filename so it knows what file format (jpg, png, etc..) to save your image in.
The reason you are getting the error is it does not know what encoding to save the temporary image object (tmp) in.
Here is an example
->save('my-image.jpg', 90)
There is also a optional second parameter that controls the quality output. The above outputs at 90% quality.
http://image.intervention.io/api/save

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

Resize the uploaded image using php

I need to resize the uploaded image and save it with given resolutions. Assume user uploads just only one single image and I save it like 35x35, 100x100 and 512x512 after finishing the upload. finally his one upload save in my folder as 3 images with different resolutions. I've done up to this point using laravel...
public function postSingleUpload()
{
//create the relevant directory to add the user image
//get the directory name (directory name equals to user id)
$dirPath = sprintf("images/users/avatar/%s/", Auth::user()->id);
//create the directory named by user id
if (!file_exists($dirPath)) {
mkdir($dirPath, 0700);
}
$file = Input::file('image');
//save image with given resulutions
//---- this part i need --------//
}
so please help me for this.
Here is what I have done to save the uploaded image with given resolutions:
//First Copy the uploaded image to some location
Input::file('profilePic')->move('Users/'.$username.'/Wallpics/',$name)
//Set this attribute for quality after resampling
$quality = 90;
$src = 'Users/'.$username.'/Wallpics/'.$name;
//Run this on recently saved uploaded image
$img = imagecreatefromjpeg($src);
//get this values from user by submitting form ( either by crop or by textboxes)
$width=(int)Input::get('w');
$height=(int)Input::get('h');
$x=(int)Input::get('x');
$y=(int)Input::get('y');
//This is the code to resample the image and generate a new to ur requirements
$dest = ImageCreateTrueColor($width, $height);
imagecopyresampled($dest, $img, 0, 0,$x,$y, $width, $height,$width,$height);
imagejpeg($dest, 'Users/'.$username.'/profilePic/'.$name, $quality);
//Set the path in database
$profile->profilePic=asset('Users/'.$username.'/profilePic/'.$name);
$profile->save();

Automatically resize Wordpress images to a maximum width and height upon uploading?

I created a blog where some users can upload images through the Wordpress dashboard. The site gets bogged down quickly because the original images are so big. Some users don't have the knowledge to resize the images themselves before uploading them, and I don't want to have to resize them manually.
Is there any way I can set a maximum width and height for uploaded images? I don't even want the original to remain on the website. I want the largest version of the image on the website to match the width and height restrictions I set.
add this code in your theme's functions.php it will replace the original image with the the re-sized version.
function replace_uploaded_image($image_data) {
// if there is no large image : return
if (!isset($image_data['sizes']['large'])) return $image_data;
// paths to the uploaded image and the large image
$upload_dir = wp_upload_dir();
$uploaded_image_location = $upload_dir['basedir'] . '/' .$image_data['file'];
$large_image_location = $upload_dir['path'] . '/'.$image_data['sizes']['large']['file'];
// delete the uploaded image
unlink($uploaded_image_location);
// rename the large image
rename($large_image_location,$uploaded_image_location);
// update image metadata and return them
$image_data['width'] = $image_data['sizes']['large']['width'];
$image_data['height'] = $image_data['sizes']['large']['height'];
unset($image_data['sizes']['large']);
return $image_data;
}
add_filter('wp_generate_attachment_metadata','replace_uploaded_image');
Article Source: http://goo.gl/nkszUn
Well why dont you create a new image size?
http://codex.wordpress.org/Function_Reference/add_image_size
And use that image on your templates.
This will work for new image uploads as well as older ones replacing user uploaded large images automatically with your defined Large size from admin panel's media settings:
add_filter('wp_generate_attachment_metadata','replace_uploaded_image');
function replace_uploaded_image($image_data) {
// if there is no large image : return
if (!isset($image_data['sizes']['large'])) return $image_data;
// paths to the uploaded image and the large image
$upload_dir = wp_upload_dir();
$uploaded_image_location = $upload_dir['basedir'] . '/' .$image_data['file'];
// $large_image_location = $upload_dir['path'] . '/'.$image_data['sizes']['large']['file']; // ** This only works for new image uploads - fixed for older images below.
$current_subdir = substr($image_data['file'],0,strrpos($image_data['file'],"/"));
$large_image_location = $upload_dir['basedir'] . '/'.$current_subdir.'/'.$image_data['sizes']['large']['file'];
// delete the uploaded image
unlink($uploaded_image_location);
// rename the large image
rename($large_image_location,$uploaded_image_location);
// update image metadata and return them
$image_data['width'] = $image_data['sizes']['large']['width'];
$image_data['height'] = $image_data['sizes']['large']['height'];
unset($image_data['sizes']['large']);
return $image_data;
}

Categories