Laravel : Upload 64base image instead of normal - php

I have an application using React and Laravel where I'm uploading images.
I'm using Laravel Image Intervention package.
When testing my API, the upload for a normal image works perfectly.
Using React, the user can select an image from his pc and crop it, then he sees the preview as a generated cropped 64base image.
I would want to upload the generated 64base image to my database instead of a normal one, how to do so ?
Fileupload controller
public function Store(Request $request)
{
$this->validate($request, [
'filename' => 'image|required|mimes:jpeg,png,jpg,gif,svg'
]);
$originalImage= $request->file('filename');
$thumbnailImage = Image::make($originalImage);
// Define upload path
$originalPath = public_path('/images/');
// Save Orginal Image
$thumbnailImage->save($originalPath.time().$originalImage->getClientOriginalName());
// Save In Database
$imagemodel= new Photo();
$imagemodel->photo_name=time().$originalImage->getClientOriginalName();
$imagemodel->save();
return back()->with('success', 'Image Upload successful');
}

This one should work
$folderPath = "images/";
$image_parts = explode(";base64,", $request->file('file'));
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = $folderPath . uniqid() . '. '.$image_type;
// file_put_contents($file, $image_base64);
Storage::put($file, $image_base64);
Possible alternative:
$image = Image::make(base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $request->file('file'))))->stream();
Storage::put($file, $image, 'public');

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

Using Intervention Image to resize an image in the storage folder

I have a function in my Laravel application that allows users to upload profile pictures to their profile.
Here is the method:
/**
* Store a user's profile picture
*
* #param Request $request
* #return void
*/
public function storeProfilePicture(User $user = null, Request $request)
{
$user = $user ?? auth()->user();
//Retrieve all files
$file = $request->file('file');
//Retrieve the file paths where the files should be moved in to.
$file_path = "images/profile-pictures/" . $user->username;
//Get the file extension
$file_extension = $file->getClientOriginalExtension();
//Generate a random file name
$file_name = Str::random(16) . "." . $file_extension;
//Delete existing pictures from the user's profile picture folder
Storage::disk('public')->deleteDirectory($file_path);
//Move image to the correct path
$path = Storage::disk('public')->putFile($file_path, $file);
// Resize the profile picture
$thumbnail = Image::make($path)->resize(50, 50, function ($constraint) {
$constraint->aspectRatio();
});
$thumbnail->save();
$user->profile()->update([
'display_picture' => Storage::url($path)
]);
return response()->json(['success' => $file_name]);
}
I am trying to use the Intervention Image library to resize the uploaded picture from the storage folder, but I always get the same error.
"Image source not readable", exception: "Intervention\Image\Exception\NotReadableException"
I have also tried with Storage::url($path) as well as storage_path($path)
Here below code work very well with the storage path, you can directly make thumb image from request and put anywhere as a desire path as follows.
Note that here I am not deleting previse stored files or directory as I am assuming that was done already.
$file = $request->file('file');
$path = "public/images/profile-pictures/{$user->username}/";
$file_extension = $file->getClientOriginalExtension();
$file_name = time(). "." . $file_extension;
// Resize the profile picture
$thumbnail = Image::make($file)->resize(50, 50)->encode($file_ext);
$is_uploaded = Storage::put( $path .$file_name , (string)$thumbnail ); // returns true if file uploaded
if($is_uploaded){
$user->profile()->update([
'display_picture'=> $path .$file_name
]);
return response()->json(['success' => $file_name]);
}
Happy coding

Image upload success but it doesn't show the right path on Laravel

I am uploading an image on my form then resizing it using a library. I can upload the pic with no problem here is my code:
public function store()
{
$this->validate(request(),[
'title'=>'required',
'body'=>'required|min:5 ',
'photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
$image = request()->file('photo');
$fileName = $image->getClientOriginalName();
$publicPath = 'images/';
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(1200, 800);
$image_resize->save($publicPath.$fileName);
auth()->user()->addPost(new Posts( [
'title'=>request('title'),
'body'=>request('body'),
'photo'=> $fileName
]));
return redirect('/');
}
my issue is that the image doesn't show up on my front view. I have tried to remove the resizing its still the same
Well the issue here is that when u are saving the post on database photo option u are saving only the filename, you should concatinate your public path with the image path like so: 'photo'=> $publicPath.$fileName
$image = request()->file('photo');
$fileName = $image->getClientOriginalName();
$publicPath = 'images/';
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(1200, 800);
$image_resize->save($publicPath.$fileName);
auth()->user()->addPost(new Posts( [
'title'=>request('title'),
'body'=>request('body'),
'photo'=> $publicPath.$fileName
]));
So try now it should work.

How to compress image before uploading in Laravel?

I'm making a images gallery website where users can upload any image and they will be displayed on frontend. I need to compress images without effecting it's quality to reduce there size so that page load speed should not effect that much. I'm using following code to upload image:
$rules = array('file' => 'required');
$destinationPath = 'assets/images/pages'
$validator = Validator::make(array('file' => $file), $rules);
if ($validator->passes()) {
$filename = time() . $uploadcount . '.' . $file->getClientOriginalExtension();
$file->move($destinationPath, $filename);
return $filename;
} else {
return '';
}
The best and easiest way to compress images before uploading to the server, I found here:-
https://github.com/spatie/laravel-image-optimizer
You need to optimize the image for web usage as user may upload images that are way to large (Either in size or resolution). You may also want to remove the meta data from the images to decrease the size even more. Intervention Image perfect for resizing/optimizing images for web usage in Laravel. You need to optimize the image before it is saved so that the optimized version is used when loading the web page.
Intervention Image
https://tinypng.com provides an API service for compressing images. All you need to do is install their PHP library in Laravel, get a developer key from their website. After that by the adding the below code, you can compress your uploaded image. In the code, I am assuming you have stored your file under 'storage' directory.
$filepath = public_path('storage/profile_images/'.$filename);
\Tinify\setKey("YOUR_API_KEY");
$source = \Tinify\fromFile($filepath);
$source->toFile($filepath);
Here is the link to a blog which explains how to upload and compress images in Laravel http://artisansweb.net/guide-upload-compress-images-laravel
**Using core php **
function compress($source_image, $compress_image)
{
$image_info = getimagesize($source_image);
if ($image_info['mime'] == 'image/jpeg') {
$source_image = imagecreatefromjpeg($source_image);
imagejpeg($source_image, $compress_image, 20); //for jpeg or gif, it should be 0-100
} elseif ($image_info['mime'] == 'image/png') {
$source_image = imagecreatefrompng($source_image);
imagepng($source_image, $compress_image, 3);
}
return $compress_image;
}
public function store(Request $request)
{
$image_name = $_FILES['image']['name'];
$tmp_name = $_FILES['image']['tmp_name'];
$directory_name = public_path('/upload/image/');
$file_name = $directory_name . $image_name;
move_uploaded_file($tmp_name, $file_name);
$compress_file = "compress_" . $image_name;
$compressed_img = $directory_name . $compress_file;
$compress_image = $this->compress($file_name, $compressed_img);
unlink($file_name);
}

Generate a thumbnail of any upload file

I have a website where users upload document files. I want to display thumbnails of these documents. How can I display the first page of a document file as an image using codeigniter?
Below is the controller code:
public function do_upload()
{
require_once APPPATH . "php_include/authenticate.php";
$path = "uploads/file_attachment/";
if($_FILES['userfile']['name'] != ''){
$image = $_FILES['userfile']['name'];
$ext = pathinfo($image, PATHINFO_EXTENSION);
$filename = basename($image,'.'.$ext);
$filename = preg_replace("/[^a-zA-Z0-9]+/", "-", $filename);
$image = $filename.'.'.$ext;
move_uploaded_file($_FILES["userfile"]["tmp_name"],$path.$image);
$data = array(
'user_id' => $user_id,
'file' => $image,
);
$this->signupmodel->addfile($data);
}
}
This may be a bit of overkill for you but I described a bulletproof way to upload images. There are all kinds of ways where the extension (.jpg, .gif) does not match the image. Browsers have to do similar testing before rendering an image.
This code also chooses the most efficient image type to save it as and scales the image to multiple dimensions.
Stackoverflow: Scaling Images

Categories