Laravel, Fetching image from public/uploads folder - laravel-5

Controller :
public function index()
{
if (!file_exists("uploads/profiles/".\Auth::User()->id.".jpeg")) {
$image_content = File::get("uploads/profiles/default.jpg");
$image = response($image_content, 200)->header('Content-Type', 'image/jpeg');
$size = getimagesize($image);
$aspectratio = $size[0]/$size[1];
$img_thumbnail = Image::make($image)->resize(50*$aspectratio,50);
$img_profile = Image::make($image)->resize(160*$aspectratio,160);
$imgname = \Auth::User()->id;
$img_thumbnail->save('uploads/thumbnails/'.$imgname.".jpeg");
$img_profile->save('uploads/profiles/'.$imgname.".jpeg");
}
Error : : failed to open stream: No such file or directory.
Actually, I want to fetch the default.jpg image and save it to two other folders with different extension.

if( !file_exists('uploads/thumbnails/'. $folder)){
#mkdir('uploads/thumbnails/'. $folder, 0755);
}
if( !file_exists('uploads/profiles/'. $folder)){
#mkdir('uploads/profiles/'. $folder, 0755);
}
$img = 'uploads/profiles/'. \Auth::User()->id. '.jpeg';
if ( !file_exists($img)){
$save_extension = '.jpeg';
Image::make($img)
->resize(50, null, function ($constraint) {
$constraint->aspectRatio();
})->save('uploads/thumbnails/' . \Auth::User()->id . $save_extension);
Image::make($img)
->resize(160, null, function ($constraint) {
$constraint->aspectRatio();
})->save('uploads/profiles/' . \Auth::User()->id . $save_extension);
}
http://image.intervention.io/api/resize

public function index()
{
if (!file_exists("uploads/profiles/".\Auth::User()->id.".jpeg")) {
$image = File::get("uploads/profiles/default.jpg");
return response($image)->header('Content-Type', 'image/jpeg');
}

Make sure you're have the right permission to uploads/profiles/
chmod -R 777 /uploads/profiles/

Related

Save both original image and conversion to webp in laravel storage

I'm trying to save original jpg image and also a converted webp image to my storage when I'm storing images in my project.
public function store($data)
{
if (!$data->hasFile('fileName')) {
return response()->json(['upload_file_not_found'], 400);
}
$allowedfileExtension = ['jpg', 'jpeg'];
$files = $data->file('fileName');
$errors = [];
$images = [];
foreach ($data->fileName as $mediaFiles) {
$extension = $mediaFiles->getClientOriginalExtension();
$check = in_array($extension, $allowedfileExtension);
if ($check) {
// $path = $mediaFiles->store('public/images');
$name = $mediaFiles->getClientOriginalName();
//store image file into directory and db
$image = new Image();
$image->title = $name;
// $image->path = substr($path, 7);
$image->description = $data->description;
$image->author_id = $data->author_id;
$image->save();
//put image to storage wih unique folder
$path = $mediaFiles->storeAs('public/images/article-images/'.$image->id, $name);
//try to convert to webp and add to storage
$image = InterventionImage::make($mediaFiles)->encode('webp', 90)->resize(200, 250)->save('public/images/' . $name . '.webp');
//
//update images path in database
$image->update(['path' => substr($path, 7)]);
//add to attach the article id
if ($data->article_id) {
$image->articles()->attach($data->article_id);
}
array_push($images, $image);
} else {
return response()->json(['invalid_file_format'], 422);
}
}
return $images;
}
I'm using intervention library but when I try to save converted image to my storage I get the error "message": "Can't write image data to path (public/images/newimage.jpg.webp)",
can someone help with this or have any other suggestion how to do this?
if you want to convert image in to WEBP without any service or package, try this method. work for me. have any question can ask. Thankyou
$post = $request->all();
$file = #$post['file'];
$code = 200;
$extension = $file->getClientOriginalExtension();
$imageName = $file->getClientOriginalName();
$path = 'your_path';
if(!$file->move(public_path($path), $imageName)){
$code = 404;
}
if(in_array($extension,["jpeg","jpg","png"])){
//old image
$webp = public_path().'/'.$path.'/'.$imageName;
$im = imagecreatefromstring(file_get_contents($webp));
imagepalettetotruecolor($im);
// have exact value with WEBP extension
$new_webp = preg_replace('"\.(jpg|jpeg|png|webp)$"', '.webp', $webp);
// set qualityy according to requirement
return imagewebp($im, $new_webp, 50);
}
this will save JPG/PNG and WEBP file both to the move Folder.
If someone ever have the same problem I did it like this
public function newStore($data)
{
if (!$data->hasFile('fileName')) {
return response()->json(['upload_file_not_found'], 400);
}
$allowedfileExtension = ['jpg', 'jpeg'];
$files = $data->file('fileName');
$errors = [];
$images = [];
foreach ($data->fileName as $mediaFiles) {
$extension = $mediaFiles->getClientOriginalExtension();
$check = in_array($extension, $allowedfileExtension);
if ($check) {
// $path = $mediaFiles->store('public/images');
$name = $mediaFiles->getClientOriginalName();
//getting the name of the file without extension
$filename = pathinfo($name, PATHINFO_FILENAME);
//store image file into directory and db
$image = new Image();
$image->title = $name;
// $image->path = substr($path, 7);
$image->description = $data->description;
$image->author_id = $data->author_id;
$image->save();
//put image to storage in unique folder
$path = $mediaFiles->storeAs('public/images/article-images/' . $image->id, $name);
//imege conversion in webp format and move to right folder
$interventionImage = InterventionImage::make($mediaFiles)->stream("webp", 100);
Storage::disk('local')->put($filename . '.webp', $interventionImage, 'public');
Storage::move($filename . '.webp', 'public/images/article-images/' . $image->id . '/' . $filename . '.webp');
//update images path in database
$image->update(['path' => substr($path, 7)]);
//add to attach the article id
if ($data->article_id) {
$image->articles()->attach($data->article_id);
}
array_push($images, $image);
} else {
return response()->json(['invalid_file_format'], 422);
}
}
return $images;
}
and my folder structure looks like this:

my image are not saved in upload folder in laravel

whenever I uploaded an image in laravel, the image is upload to the database but after database uploading, my image didn't save that image in my root folder,
here is my upload code:
public function store(Request $request)
{
$records = $request->all();
if ($records != '') {
if ($request->session()->has('is_user_logged')) {
$UserPostModel = new UserPostModel;
$UserPostModel->uid = $request->session()->get('uid');
$UserPostModel->uname = $request->session()->get('name');
$UserPostModel->msg = $request->input('status');
$UserPostModel->eid = $request->input('event');
if ($request->hasFile('image')) {
if ($request->file('image')->isValid()) {
$fileName = $request->file('image')->getClientOriginalName();
$fileName = time() . "_" . $fileName;
$request->file = move_uploaded_file('uploads',$fileName);
$UserPostModel->image = $fileName;
}
}
$UserPostModel->save();
return redirect('uprofile')->with('message', 'Seccessfully Post !');
} else {
return redirect('login');
}
} else {
return redirect('/uprofile')->with('message', 'Please select image!');
}
}
Use store method and pass the driver as the second argument
$path = $request->file('image')->store($store_path, 'public');
Please replace this code with your image upload condition.
if ($file = $request->file('image')) {
$name = time() . $file->getClientOriginalName();
$file->move('uploads', $name);
$UserPostModel->image = $name;
}
$UserPostModel -> save();

how to update image when i have my function

I'm having problem with this code in update photo:
I already have function on it but it doesnt work
if (isset($request['image'])) {
$image = request()->file('image')->move("pictures/{$users[0]['username']}", 'public');
}
if (isset($request['licenseimage_front'])) {
$request['licenseimage_front'] = request()->file('licenseimage_front')->store("licensepicture/front/{$users[0]['username']}", 'public');
}
if (isset($request['licenseimage_back'])) {
$request['licenseimage_back'] = request()->file('licenseimage_back')->store("licensepicture/back/{$users[0]['username']}", 'public');
}

Method break after calling function in same controller

I made a method that handles image. The problem is I want to call that method in my Edit method few times because there are 3 buttons for uploading image. But after calling my method for IMAGE the EDIT method just stops after first image. How can I stop that?
if($request->has('picture1')) {
return $this->upload_image($company, $asset, $request->picture1);
}
if($request->has('picture2')) {
return $this->upload_image($company, $asset, $request->picture2);
}
if($request->has('picture3')) {
return $this->upload_image($company, $asset, $request->picture2);
}
And this is my function for uploading image
public function upload_image($company, $asset, $image)
{
$filename = uniqid(rand());
$image = str_replace('data:image/png;base64,', '', $image);
$image = str_replace(' ', '+', $image);
if (!file_exists(public_path('/uploads/assets/pictures/' . $company->id . '/'))) {
File::makeDirectory(public_path('/uploads/assets/pictures/' . $company->id . '/'), 0777, true);
}
Image::make($image)->resize(1024, null, function ($constraint) { $constraint->aspectRatio();})
->save( public_path('/uploads/assets/pictures/' . $company->id . '/'. $filename ) );
}
How can i go back to my function after handling first image?
You have to simply remove the return keyword like this :
if($request->has('picture1')) {
$this->upload_image($company, $asset, $request->picture1);
}
if($request->has('picture2')) {
$this->upload_image($company, $asset, $request->picture2);
}
if($request->has('picture3')) {
$this->upload_image($company, $asset, $request->picture2);
}

Receive function fails to get image

I am working on multiple file upload code is not showing any error
public function imagenewAction()
{
$form = new ImageNewForm();
$form->get('submit')->setValue('Submit');
$request = $this->getRequest();
// die('checko');
if($request->isPost())
{
// die('checko');
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('file');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
$form->setData($data);
if ($form->isValid())
{
//New Code
$dataNew=array('','image','image1');
for($i=1;$i<=2;$i++)
{
$addressProof = $data[$dataNew[$i]]['name'];
$addressProofextension = pathinfo($addressProof, PATHINFO_EXTENSION);
// $addressProofimg = $addressProof . $i . "." . $addressProofextension;
$addressProofimg = $addressProof;
//$verificationdocuments->setdocphotocopy($addressProofimg);
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setDestination('public/img/upload');
$adapter->addFilter(new \Zend\Filter\File\Rename(array(
'target' => 'public/img/upload',
'overwrite' => true
)), null, $addressProofimg);
if(!$adapter->receive($addressProofimg))
{
print_r ( $adapter->getMessages (), 1 );
}
else
{
echo "Image Uploaded";
}
}
}
}
return array('form' => $form);
}
It is giving blank error messages and not uploading images please help me to get away with this I am stuck from last 2 days

Resources