Image source not readable : Image Upload in Laravel - laravel-5

I'm trying to upload an image to our system. It is working well when I'm using it in localhost but when I'm testing in server, it's throwing an error Image source not readable. I'm trying to upload a 2.2MB photo since my max size of image upload is 3MB. Uploading images less than or equal to 2MB in server has no problem but in local, it accepts up to 3MB in which it is the expected behavior. I'm using docker for my local development and my server is CentOS7. Is there some configurations I should touch so that it can accept 3MB image size in my server? Or is there something I have to change in my code below in processing the image?
REQUEST
public function rules()
{
return [
'photo' => 'image|mimes:jpeg,png,jpg|max:3000',
];
}
Controller
$photo = $request->file('photo');
$server_dir = storage_path(config('const.upload_local_temp_path'));
FileHelper::addDirectory($server_dir, 0777);
$file_name = FileHelper::makeUniqFileName($photo->getClientOriginalExtension(), $server_dir);
$filepath = $server_dir . $file_name;
$img_path = FileHelper::storeResizeImg($photo->path(), $filepath, null, 300);
$img_url = FileHelper::getPublicPath($img_path);
return $img_url;
FILEHELPER
/*
*
*/
public static function addDirectory($directory, $mod)
{
if (!File::exists($directory)) {
File::makeDirectory($directory, $mod, true);
}
}
/**
*
*/
public static function storeResizeImg($file, $filepath, $width, $height)
{
$org_img = Image::make($file);
$org_img->orientate();
$org_img = $org_img->resize($width, $height, function ($constraint) {
$constraint->aspectRatio();
});
$org_img->save($filepath);
return $filepath;
}
public static function makeUniqFileName($ext, $path)
{
$file_name = '';
while (1) {
$file_name = sha1(rand().microtime()).'.'.$ext;
if (!File::exists($path. $file_name)) {
break;
}
}
return $file_name;
}
UPDATE
Error message that the image size is greater than 3MB is working in my local, but in server it says : The given data was invalid.
Please let me know of your thoughts.

Related

Image resizing not working with Intervention image Package

The photo is saved, but without resizing, the original photo is actually saved
protected function uploadImage($images = '') {
$path = 'upload/images';
if (request()->hasFile('image') && $files = request()->file('image'))
$images = Image::make($files->store($path, 'public_files'))->resize(320, 240);
return $images;
}
public function store(CreateGalleryRequest $request, Job $job) {
$image = $this->uploadImage();
if ($request->hasFile('image')) {
$data['image'] = $image . $image->dirname . '/' . $image->basename;
} else
$data['image'] = null;
$job->gallery()->create($data);
return redirect(route('jobs.gallery.index' , ['job' => $job->id]));
}
You need to call save() function to save image
...
$images = Image::make($files->store($path, 'public_files'))->resize(320, 240)->save('image path');
...
wrote:
$images = Image::make($files->store($path, 'public_files'))->resize(320, 240)->save($files->store($path, 'public_files'));
error:
Illuminate\Database\QueryException
actually there is an error in the following code:
$job->gallery()->create($data);

How to queue upload to s3 using Laravel?

I'm dispatching a job to queue my video file, the files are being stored on s3.
Everything is working except if I upload a video file for example that's 20mb, when I look in my bucket it says the file is 120b. So this makes me think that I'm uploading the path and filename as a string instead of the file object.
And for some reason, when I try getting the file using the Storage::get() or File::get() and dd the result, it shows a bunch or random and crazy characters.
It seems like I can only get these weird characters, or a string, I can't get the file object for some reason.
In my controller I'm also storing it in the public disk (I will delete the file later in my Jobs/UploadVideos.php file).
CandidateProfileController.php:
$candidateProfile = new CandidateProfile();
$candidateProfile->disk = config('site.upload_disk');
// Video One
if($file = $request->file('video_one')) {
$file_path = $file->getPathname();
$name = time() . $file->getClientOriginalName();
$name = preg_replace('/\s+/', '-', $name);
$file->storePubliclyAs('videos', $name, 'public');
$candidateProfile->video_one = $name;
}
if($candidateProfile->save()) {
// dispatch a job to handle the image manipulation
$this->dispatch(new UploadVideos($candidateProfile));
return response()->json($candidateProfile, 200);
} else {
return response()->json([
'message' => 'Some error occurred, please try again.',
'status' => 500
], 500);
}
Jobs/UploadVideos.php:
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $candidateprofile;
public $timeout = 120;
public $tries = 5;
/**
* Create a new job instance.
*
* #param CandidateProfile $candidateProfile
*/
public function __construct(CandidateProfile $candidateProfile)
{
$this->candidateprofile = $candidateProfile;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$disk = $this->candidateprofile->disk;
$filename = $this->candidateprofile->video_one;
$original_file = storage_path() . '/videos/' . $filename;
try {
// Video One
Storage::disk($disk)
->put('videos/'.$filename, $original_file, 'public');
// Update the database record with successful flag
$this->candidateprofile->update([
'upload_successful' => true
]);
} catch(\Exception $e){
Log::error($e->getMessage());
}
}
File Storage docs
The 2nd parameter for put() should be the contents of the file not the path to the file. Also, unless you've updated the public disk in your config/filesystem.php, the video isn't going to be stored in storage_path() . '/videos/...'.
To get this to work you should just need to update your Job code:
$filename = 'videos/' . $this->candidateprofile->video_one;
Storage::disk($this->candidateprofile->disk)
->put($filename, Storage::disk('public')->get($filename), 'public');
$this->candidateprofile->update([
'upload_successful' => true,
]);
Also, wrapping your code in a try/catch will mean that the Job won't retry as it will technically never fail.

Multiple Image Upload in Laravel tweak to add additional field

I have a need to upload multiple images. This code below works well. This is using Intervention Image plugin. I am trying to customise this code to add another field which is a ForeignKey value to the parent of this image model. $request has the value coming from form. How to save it along with images?
The value is:
$request('vehicle_id')
How can tweak the below method so as save includes this vehicle_id as well?
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');
// create new directory for uploading image if doesn't exist
if( ! File::exists('images/'.auth()->user()->id)) {
$org_img = File::makeDirectory('images/'.auth()->user()->id, 0777, true);
}
// loop through each image to save and upload
foreach($images as $key => $image) {
//create new instance of Photo class
$newPhoto = new $this->photo;
//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/'.auth()->user()->id . $filename;
$newPhoto->image = 'images/'.auth()->user()->id.$filename;
//don't upload file when unable to save name to database
if ( ! $newPhoto->save()) {
return false;
}
// upload image to server
if ($org_img == true) {
Image::make($image)->fit(900, 500, function ($constraint) {
$constraint->upsize();
})->save($org_path);
}
}
}
return redirect('/home')->with('success','Images Uploaded');
}
I found solution
public function uploadImage(Request $request)
{
$request->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'vehicle' => 'required'
]);
//check if image exist
if ($request->hasFile('image')) {
$images = $request->file('image');
// create new directory for uploading image if doesn't exist
if( ! File::exists('images/'.auth()->user()->id.'/')) {
$org_img = File::makeDirectory('images/'.auth()->user()->id.'/', 0777, true);
}
// loop through each image to save and upload
foreach($images as $key => $image) {
//create new instance of Photo class
$newPhoto = new $this->photo;
//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/'.auth()->user()->id.'/' . $filename;
$newPhoto->image = 'images/'.auth()->user()->id.'/' . $filename;
$newPhoto->vehicle = $request->input('vehicle');
//don't upload file when unable to save name to database
if ( ! $newPhoto->save()) {
return false;
}
// upload image to server
Image::make($image)->fit(900, 500, function ($constraint) {
$constraint->upsize();
})->save($org_path);
}
}
return redirect('/home')->with('success','Images Uploaded');

Laravel Image source not readable error

I am working on uploading a video locally and then use it locally to upload to s3. It successfully uploads to s3 but I get this error:
Image source not readable
/var/www/yt/vendor/intervention/image/src/Intervention/Image/AbstractDecoder
I found this error when I was trying to delete the image after I uploaded it to s3. I think it is the reason the delete does not work. How do I fix the error?
public function avatar(Request $request)
{
$imageData = $request->get('image');
$img = Image::make($request->get('image'))->fit(300)->encode('jpg');
// calculate md5 hash of encoded image
$hash = md5($img->__toString());
// use hash as a name
$path = "avatars/{$hash}.jpg";
// save it locally
$test = $img->save(storage_path($path));
// $url = "/images/{$hash}.jpg"
$url_local = $path;
$path = Storage::putFile('avatars', new File(storage_path($url_local)));
if($path){
//TODO make into event
Storage::disk('local')->delete(storage_path($url_local));
// \Debugbar::error($test);
}
$user = User::find(Auth::id());
$user->avatar_url = $path;
if ($user->save()) {
return response()->json(['avatar' => $user->gen_avatar()]);
}
}

Laravel intervention/image doesn't resize image

I am trying to use laravel intervention plugin. I installed it without problem but can't use it.
I am trying to make a test function which returns resized image, but without success;
I think the problem may be in image path, please help me fix my code.
function test($img)
{
/* $img = Image::make('public/image1.jpg');
$img->resize(300, 200);
return $img; */
$image = Image::make('http://localhost/cms/digital-cms/public/image1.jpg')->resize(200, 200, function ($c) {
$c->aspectRatio();
$c->upsize();
});
return $image;
//$h=200; $w=200;
//return Image::make(public_path('public/image1.jpg')->resize($h, $w)->response('jpg'));
}
//get image
$image=$request->file('image');
//rename image
$input = time().'.'.$image->getClientOriginalExtension();
//your directory to upload
$destinationPath = 'main/images/company';
//save and resize image
$img = Image::make($image->getRealPath());
$img->resize(20,20, function ($constraint) {
$constraint->aspectRatio();
})->save($destinationPath.'/'.$input);
You should use response function on Image class to return the image
$image = Image::make('http://localhost/cms/digital-cms/public/image1.jpg')->resize(200, 200, function ($c) {
$c->aspectRatio();
$c->upsize();
});
return $image->response();
In my case, I was resizing, cropping (fit) but the final image is still the same as original. Found out that I had to add function encode, to produce the manipulated image
return $image->encode('jpg', 80);

Resources