Resized image not saving - php

I'm trying to upload an image using storage folder, and also using traits, but when it comes using Intervention i'm really having trouble where to use it.
Here's the FileUploadTrait.php
public function uploadImage($image) {
if ($image) {
$image_name = $image->store('public');
$name = explode("/", $image_name);
$img_name = $name[count($name) - 1];
return $img_name;
}
return null;}}
ProjectsControler.php
public function store(Request $request, Project $project)
{
$this->validate($request, array(
'image' =>'required|image|dimensions:min_width=800,min_height=600'
));
if ($request->hasfile('image')) {
$img_name= $this->uploadImage($request->image);
$image_resize = Image::make($request->image);
$image_resize->resize(800, 600);
}
$projects = Project::create(
array_merge(
$request->except('image', '_token'),
["image"=>$img_name ?? null]
)
);
return redirect('my/path');
}
the image gets uploaded but not resized.

After upload and resizing you have also to save the image to a given destination.
if ($request->hasfile('image')) {
$img_name= $this->uploadImage($request->image);
$image_resize = Image::make($request->image);
$image_resize->resize(800, 600)->save('Your Path');
}

You’re not saving your new resized image.
$image_resize->save();

Related

Trying to Get the name of an uploaded Image

I am trying to get the name of an image and save it instead of saving it as laravel default hashing.
i.e if an image name is go.jpg it should save as go.jpg instead of randomly generated numbers
Here is my controller
private function storeImage($news)
{
if (request()->has('image')){
$news->update([
'image' => request()->image->store('uploads', 'public'),
]);
$image = Image::make(public_path('storage/'. $news->image))->resize(600, 600);
$image->save();
}
}
You can use this method: getClientOriginalName()
if ($request->hasFile('image')) {
return $request->file('image')->getClientOriginalName();
} else {
return 'no file!'
}
http://api.symfony.com/3.0/Symfony/Component/HttpFoundation/File/UploadedFile.html#method_getClientOriginalName
getClientOriginalName use this method.
use Illuminate\Support\Facades\Input;
private function storeImage($news)
{
if (request()->has('image')){
$file = Input::file('image');
$img= $file->getClientOriginalName().'.'.$file->getClientOriginalExtension();
$news->update([
'image' => $img,
]);
$image = Image::make(public_path('storage/'. $news->image))-
>resize(600, 600);
$image->save();
}
}

How to upload Image in Database in Laravel 5.7?

I'm making an app in Laravel 5.7 . I want to upload image in database through it and I want to show it from database.
I have tried different methods around the Internet as I was getting issues in
Intervention\Image\Facades\Image
I followed many advices from Internet make changes in config.app
made changes in Composer
At the end used
use Intervention\Image\Facades\Image as Image;
So I get resolved from issue "Undefined class Image"
but now I' m getting issues as "Undefined class File",
Method getClientOriginalExtension not found.
Method Upsize, make not found.
My code is
<?php
namespace App\Http\Controllers;
use File;
use Intervention\Image\Facades\Image as Image;
use App\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
//
protected $user;
/**
* [__construct description]
* #param Photo $photo [description]
*/
public function __construct(
User $user )
{
$this->user = $user;
}
/**
* Display photo input and recent images
* #return view [description]
*/
public function index()
{
$users = User::all();
return view('profile', compact('users'));
}
public function uploadImage(Request $request)
{
$request->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
//check if image exist
if ($request->hasFile('image')) {
$images = $request->file('image');
//setting flag for condition
$org_img = $thm_img = true;
// create new directory for uploading image if doesn't exist
if( ! File::exists('images/originals/')) {
$org_img = File::makeDirectory('images/originals/', 0777, true);
}
if ( ! File::exists('images/thumbnails/')) {
$thm_img = File::makeDirectory('images/thumbnails', 0777, true);
}
// loop through each image to save and upload
foreach($images as $key => $image) {
//create new instance of Photo class
$newPhoto = new $this->user;
//get file name of image and concatenate with 4 random integer for unique
$filename = rand(1111,9999).time().'.'.$image->getClientOriginalExtension();
//path of image for upload
$org_path = 'images/originals/' . $filename;
$thm_path = 'images/thumbnails/' . $filename;
$newPhoto->image = 'images/originals/'.$filename;
$newPhoto->thumbnail = 'images/thumbnails/'.$filename;
//don't upload file when unable to save name to database
if ( ! $newPhoto->save()) {
return false;
}
// upload image to server
if (($org_img && $thm_img) == true) {
Image::make($image)->fit(900, 500, function ($constraint) {
$constraint->upsize();
})->save($org_path);
Image::make($image)->fit(270, 160, function ($constraint) {
$constraint->upsize();
})->save($thm_path);
}
}
}
return redirect()->action('UserController#index');
}
}
Please suggest me any Image Upload code without updating repositories or suggest me how can I remove issues from this code.
The beginning of time read below link because laravel handled create directory and hash image and put directory
laravel file system
then read file name when stored on directory and holds name on table field when need image retrieve name field and call physical address on server
$upload_id = $request->file('FILENAME');
$file_name = time().$upload_id->getClientOriginalName();
$destination =
$_SERVER["DOCUMENT_ROOT"].'/adminbusinessplus/storage/uploads';
$request->file('FILENAME')->move($destination, $file_name);
$string="123456stringsawexs";
$extension = pathinfo($upload_id, PATHINFO_EXTENSION);
$path = $destination.'/'.$file_name;
$public =1;
$user_id = $request->logedin_user_id;
$hash = str_shuffle($string);
$request->user_id = $request->logedin_user_id;
$request->name = $file_name;
$request->extension = $extension;
$request->path = $path;
$request->public = $public;
$request->hash = $hash;
//$request INSERT INTO MODEL uploads
$file_id = Module::insert("uploads", $request);

Using Image Intervention with Laravel Nova

I have Image Intervention working and pushing to S3, but I can't save the filename to the table.
this is what I have so far:
// Use AS because Image is already a Nova facade
use Intervention\Image\Facades\Image as Cropper;
- - -
Avatar::make('Image Large')
->store(function (Request $request, $model) {
// Create a UUID filename
$fileName = $this->uuid() . '.jpg';
// Crop with Image Intervention
$cropped = Cropper::make($request->image_large)->fit(100, 50, function ($c) {
$c->upsize();
})->encode('jpg', 80);
// Store on S3
Storage::disk('s3_image')->put($fileName, (string) $cropped);
// Save filename in DB
$model->update([
'image_large' => $fileName,
]);
})
->rules('required')
->prunable(),
All working except the last part, saving the filename.
I figured it out
Avatar::make('Image', 'image_large')
->store(function (Request $request, $model) {
// Create a UUID filename
$fileSmall = $this->uuid() . '.jpg';
$fileLarge = $this->uuid() . '.jpg';
// Crop with Image Intervention
$imageSmall = Cropper::make($request->image)->fit(200, 100, function ($c) {
$c->upsize();
})->encode('jpg', 90);
$imageLarge = Cropper::make($request->image)->fit(500, 300, function ($c) {
$c->upsize();
})->encode('jpg', 90);
// Store on S3
Storage::disk('s3_image')->put($fileSmall, (string) $imageSmall);
Storage::disk('s3_image')->put($fileLarge, (string) $imageLarge);
return [
'image_small' => $fileSmall,
'image_large' => $fileLarge,
];
})
->rules('required')
->disk('s3_image')
->hideFromIndex()
->prunable(),

How to validate image store in Controller in Laravel 5.6

in My laravel 5.6 app I have image store function in my Controller like this,
public function store(Request $request)
{
$image = new Category();
if ($request->hasFile('image')) {
$dir = 'images/';
$extension = strtolower($request->file('image')->getClientOriginalExtension()); // get image extension
$fileName = str_random() . '.' . $extension; // rename image
$request->file('image')->move($dir, $fileName);
$image->categoryimage = $fileName;
}
$image->save();
}
now I need validate before save image if saving without image (empty) and if not file format is equel to (png,jpeg,png). how can I do this?
In the first line of your function
$validatedData = $request->validate([
'image' => 'required|file|mimes:jpeg,png'
]);
//image is valid
Take a look at this: docs
You can do this:
//first you should use the Request class at the top of your file
use Illuminate\Http\Request;
public function store(Request $request)
{
$validator = $request->validate([
'image' => 'required|image'
]);
if ($validator->fails()) {
// write what you want here
}
// the rest of your code
}
The file under validation must be an image (jpeg, png, bmp, gif, or svg).

Laravel queue error Serialization of 'Illuminate\Http\UploadedFile' is not allowed

I am trying to upload a file using a queue(bean) in laravel but I get this error: Serialization of 'Illuminate\Http\UploadedFile' is not allowed
My code is:
protected $file;
protected $Id;
public function __construct($file,$Id)
{
$this->file = $file
$this->Id = $Id;
}
public function handle()
{
$qFile = $this->file;
$qId = $this->Id;
$s3 = Storage::disk('s3');
$extension = $qFile->guessExtension();
$filename = uniqid().'.'.$extension;
//Create and resize images
$image = Image::make($qFile)->resize(null, 600, function ($constraint) {
$constraint->aspectRatio();
});
$image->encode($extension);
$imageLarge = Image::make($qFile)->resize(null, 800, function ($constraint) {
$constraint->aspectRatio();
});
$imageLarge->encode($extension);
// upload image to S3
$s3->put("images/{$qId}/main/".$filename, (string) $image, 'public');
$s3->put("images/{$qId}/large/".$filename, (string) $imageLarge, 'public');
// make image entry to DB
File::create([
'a_f_id' => $qId,
'file_name' => $filename,
]);
}
But if I remove:
protected $file;
protected $Id;
I dont get the error
You can’t pass an uploaded file instance to a job. You need to write it to disk somewhere, and then retrieve it when handling the job.

Categories