Get File (Image) Dimesion in Laravel6.x - php

In my laravel project, I have uploaded the image in database and it shows image in view file properly.
Now I want to get the image dimension, So How can I get this?
Can anyone help me plz?
This is my controller for uploading image.
public function store(Request $request)
{
request()->validate([
'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
// if ($request->hasFile('image')) {
// $image = $request->file('image');
// $extension = $image->getClientOriginalExtension();
// $filename = time() . "." . $extension;
// $image->move('public/mediaLibrary', $filename);
// }
$image = $request->file('image');
$extension = $image->getClientOriginalExtension();//Getting extension
$originalname = $image->getClientOriginalName();//Getting original name
//this code will store image in laravel default storage folder $path = $image->storeAs('', $originalname);
$path = $image->move('uploads/media/', $originalname);//This will store in customize folder
$imgsizes = $path->getSize();
$mimetype = $image->getClientMimeType();//Get MIME type
//Start Store in Database
$picture = new mediaLibrary();
$picture->mime = $mimetype;
$picture->imgsize = $imgsizes;
$picture->original_filename = $originalname;
$picture->extension = $extension;
$picture->filename = $path;
$picture->save();
//End Store
return redirect()->route('media.index');
}
This is my blade file code where i want to show
<div class="card-body" >
<span><i class="fa fa-calendar" aria-hidden="true"></i> Uploaded on:</span>
<strong><p class="text-muted" style="display: inline">
{{ date('F d, Y',strtotime($data->created_at)) }} at {{ date('g : ia',strtotime($data->created_at)) }}
</p></strong>
<hr>
<span>File Name:</span>
<strong><p style="display: inline;">{{$data->original_filename}}</p></strong>
<hr>
<span>File type:</span>
<strong><p style="display: inline;">{{$data->extension}}</p></strong>
<hr>
<span>Fle Size:</span>
<strong><p style="display: inline;"></p>{{round(($data->imgsize)/1024 )}}KB</strong>
{{-- <strong><p style="display: inline;"></p>{{(File::size($data->filename))/1024}} KB</strong> --}}
<hr>
<span>Dimension:</span>
<strong><p style="display: inline;">
</p></strong>
</div>

You may use getimagesize() native PHP method
list($width, $height) = getimagesize('path_to_image');
Or via
Intervention Image package
// read width of image
$width = Image::make('public/foo.jpg')->width();
// read height of image
$height = Image::make('public/foo.jpg')->height();

Controller Image Store function
public function store(Request $request)
{
request()->validate([
'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$image = $request->file('image');
$extension = $image->getClientOriginalExtension();//Getting extension
$originalname = $image->getClientOriginalName();//Getting original name
$path = $image->move('uploads/media/', $originalname);//This will store in customize folder
$imgsizes = $path->getSize();
$data = getimagesize($path);
$width = $data[0];
$height = $data[1];
$mimetype = $image->getClientMimeType();//Get MIME type
//Start Store in Database
$picture = new mediaLibrary();
$picture->mime = $mimetype;
$picture->imgsize = $imgsizes;
$picture->original_filename = $originalname;
$picture->extension = $extension;
$picture->width = $width;
$picture->height = $height;
$picture->filename = $path;
$picture->save();
//End Store
return redirect()->route('media.index');
}
And view the file
<div class="card-body" >
<span><i class="fa fa-calendar" aria-hidden="true"></i> Uploaded on:</span>
<strong><p class="text-muted" style="display: inline">
{{ date('F d, Y',strtotime($data->created_at)) }} at {{ date('g : ia',strtotime($data->created_at)) }}
</p></strong>
<hr>
<span>File Name:</span>
<strong><p style="display: inline;">{{$data->original_filename}}</p></strong>
<hr>
<span>File type:</span>
<strong><p style="display: inline;">{{$data->extension}}</p></strong>
<hr>
<span>Fle Size:</span>
<strong><p style="display: inline;"></p>{{round(($data->imgsize)/1024 )}}KB</strong>
{{-- <strong><p style="display: inline;"></p>{{(File::size($data->filename))/1024}} KB</strong> --}}
<hr>
<span>Dimension:</span>
<strong><p style="display: inline;">
{{$data->width}} <i class="fa fa-times" aria-hidden="true"></i> {{$data->height}}
</p></strong>
<hr>
<span>File URL:</span>
<input type="text" class="mediaLib" name="image_url" value="{{url('uploads/media',$data->original_filename)}}" readonly="" style="
display: block;
background-color: #eee;
padding: 0 8px;
line-height: 2;
border-radius: 4px;
border: 1px solid #7e8993;
color: #32373c;
border-spacing: 0;
width:-webkit-fill-available;">
</div>
Note this is the database table fields:
https://imgur.com/O1w8ocT

Related

Handle a list of files over laravel CRUD

I'm working on a form where you have to enter all information you need and at the end, on save all information will be saved at the same times. The form have a list of images where you can add, change and delete pictures.
The way it was made is that all inputs refer to the name carousels[]. Adding the file is alright, the problem is that this way I have no way to identify in backend which file I have to delete or change.
I'm wondering if any Laravel master know a better way to handle a list of files over a form the way a need it to work. So I would be able to add new images, replace an old image by a new one and/or delete a specific image.
There are the pieces of code I'm working with.
Frontend:
#php
$carrousel = $Ids = [];
foreach ($offerImages as $index => $image) {
$carrousel[] = $image['image'];
$ids[] = $index;
}
#endphp
#for($i = 0; $i < 4; $i++)
<div class="col-sm-4 error-block">
<div class="{{ (!empty($carrousel[$i])) ? 'fileinput fileinput-exists':'fileinput fileinput-new' }}" data-provides="fileinput">
<div class="fileinput-preview thumbnail" id="banner{{$i}}" data-trigger="fileinput">
<img src="{{ !empty($carrousel[$i]) ? asset($carrousel[$i]) : (url('/') . "/images/default-thumbnail.png") }}"></div>
<div>
<span class="btn btn-secondary btn-sm btn-file">
<span class="fileinput-new ">Select image</span>
<span class="fileinput-exists">Change</span>
<input type="file" name="carrousels[]" id="carrousel{{$i}}">
</span>
Remove
</div>
</div>
</div>
#endfor
Backend
public function update(UpdateRequest $request)
{
try {
$id = $request->id;
$carrouselFolder = config('constants.DEFAULT.UPLOAD_FOLDERS.CARROUSEL');
$carrousels = [];
Log::debug($request->carrousels);
if ($request->carrousels) {
foreach ($request->carrousels as $image) {
if (!empty($image)) {
//upload image
$imageName = generateRandomString(30) . '.' . $image->getClientOriginalExtension();
if ($image->move(public_path($carrouselFolder), $imageName)) {
$image = $carrouselFolder . $imageName;
}
$carrousels[] = $image;
}
}
}
return redirect()->to(route('...'))
->with('toastSuccess', '...');
} catch (\Exception $e) {
return redirect()->back()->with('toastError', $e->getMessage());
}
}
send another parameter with old carousel, retrive it in controller then if both not empty, delete the old image . you can try this
View code
#php
$carrousel = $Ids = [];
foreach ($offerImages as $index => $image) {
$carrousel[] = $image['image'];
$ids[] = $index;
}
#endphp
#for($i = 0; $i < 4; $i++)
<div class="col-sm-4 error-block">
<div class="{{ (!empty($carrousel[$i])) ? 'fileinput fileinput-exists':'fileinput fileinput-new' }}" data-provides="fileinput">
<div class="fileinput-preview thumbnail" id="banner{{$i}}" data-trigger="fileinput">
<img src="{{ !empty($carrousel[$i]) ? asset($carrousel[$i]) : (url('/') . "/images/default-thumbnail.png") }}"></div>
<div>
<span class="btn btn-secondary btn-sm btn-file">
<span class="fileinput-new ">Select image</span>
<span class="fileinput-exists">Change</span>
<input type="text" name="oldcarrousels[{{$i}}]" value="{{ !empty($carrousel[$i]) ?$carrousel[$i] :'' }}">
<input type="file" name="carrousels[{{$i}}]" id="carrousel{{$i}}">
</span>
Remove
</div>
</div>
</div>
#endfor
Controller code
foreach ($request->carrousels as $in=>$image) {
if (!empty($image)) {
if (!empty($request->oldcarrousels[$in]) || $request->oldcarrousels[$in]!='') {
//image deleting code here
}
//upload image
$imageName = generateRandomString(30) . '.' . $image->getClientOriginalExtension();
if ($image->move(public_path($carrouselFolder), $imageName)) {
$image = $carrouselFolder . $imageName;
}
$carrousels[] = $image;
}
}

How to edit image in Laravel 5.7?

I inserted the image in my database, now I am trying to edit the images and the edited image should be deleted from my folder and a new image should be updated there. Could you please help me where I am mistaking?
Here is my Controller.php file
public function edit($slider)
{
$property=Property::all();
$slider = Slider::find($slider);
$data = ['property'=>$property, 'slider'=>$slider];
return view('admin.slider.edit', $data);
}
public function update(Request $r, $id)
{
$slider=Slider::find($id);
if( $r->hasFile('slider_thumb')){
$thums = $r->slider_thumb;
$slider_thumb = uniqid($chr).'.'.$thums->getClientOriginalExtension();
$img = Image::make($thums->getRealPath());
$img->resize(204, 107, function ($constraint) {
$constraint->aspectRatio();
});
$thumbPath = public_path().'/slider_img/'.$slider_thumb;
if (file_exists($thumbPath)) {
$this->removeImage($thumbPath);
}
$img->save($thumbPath);
$optimizerChain = OptimizerChainFactory::create();
$optimizerChain->optimize($thumbPath);
$slider_thumbimg = $slider_thumb;
}else{
$slider_thumb = NULL;
}
$slider->property_id = $r->property_id;
$slider->slider_image=$slider_imageimg;
$slider->save();
return redirect('/admin/slider');
}
}
here is my HTML file
<form class="form-horizontal" method="POST" action="{{ route('slider.update',['id'=>$slider->id]) }}" enctype="multipart/form-data">
#csrf
#method('PUT')
#if($slider->slider_image == NULL or $slider->slider_image == '')
<img src="{{asset('images/no-image-found.jpg')}}" style="width: 100px; height: 100px;">
#else
<img src="{{ asset('slider_img/'.$slider->slider_image) }}" style="width: 100px; height: 80px;">
#endif
<input type="file" name="slider_image" value="{{ $slider->slider_image }}">
<div class="form-group">
<div class="col-sm-12 text-right">
<button type="submit" class="btn btn-info">
<i class="fa fa-check"></i> Save
</button>
</div>
</div>
</form>
You did not use Laravel standards. you need to refer to laravel filesystem document to upload file. then you need to check request file exist. if request has new file; you should remove old file and upload new file. in else you should not remove old file.
follow below code:
public function store(PostRequest $request,string $slug = null)
{
$postData = $request->all();
//upload and set thumbnail of post, if exist
if($request->file("thumbnail")){
$image = new Images();
$thumbnailName = $image->uploadFile($request,"thumbnail",config("upload_image_path.post-thumbnail"));
$postData["thumbnail"] = $thumbnailName;
}
$post = $this->postService->save($postData,$slug);

Image is not displaying although saving in DB and folder Laravel

Image is not displaying however it is saving in db and folder.
I could not get it where is the problem
apperance.blade.php
<div id="bgimage" class="hovercover text-center">
<img class="img-responsive" src="img/{{$image->image ?? ''}}" style="margin-top: {{$image->position ?? ''}}">
<div class="hover-div">
<form id="hoverform" action="{{url('/employee-appearance')}}" enctype="multipart/form-data" method="post">
{{ csrf_field() }}
<label class="custom-file-upload" title="Change Cover Image" for="file-upload"> <i class="fa fa-file-image-o"></i> Change Cover </label>
<input id="file-upload" name="file" type="file">
</form>
</div>
</div>
<div id="adjimage" class="hovercover1 text-center" style="display: none;">
</div>
imageProcessController
public function upload()
{
$image=DB::table('images')->latest('image','position')->first();
return view('user.employeeforms.appearance',compact('image')) ;
}
public function postupload(Request $request)
{
$file = $request->file('file');
$rules = array('file' => 'required|mimes:png,gif,jpeg,jpg');
$validator = Validator::make(array('file'=> $file), $rules);
if($validator->passes()) {
$image = $file->move( 'img', sprintf('%s-%s.%s', time(), "abc", explode('/', $file->getMimeType())[1]));
$img = new Image;
$img->image = $image->getFilename();
$img->save();
}
}
There may be possibilities that it could be.
But the most likely one is that the symlink has not been set yet!?
php artisan storage:link
If you have already set it, look in the storage/app order where the files are. If they are under storage/app/img then you have to change the link like this:
<img src="img/{{$image->image ?? ''}}"
should be:
<img src="{{ asset('storage/img/' . $image->image ?? "placeholder.jpg" ) }}">

Laravel how to upload an image to a database and show it in view

So i was making a form that consists of three field, the title, thumbnail, and textarea(with texteditor) and it seems that it upload the image just fine since i notice that there is images that i had uploaded in my /public/image folder after i submit the form, but when i check the database the thumbnail field showed not the name of the file in the /public/image folder like 20190713125534.jpg but
C:\xampp\tmp\phpC18A.tmp
im confused i thought it doesn't upload the image at all, but as i explained earlier it does, so my question is how do i change the value of thumbnail field with the filename and how do i show the image in my view ?
this is my Blogcontroller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Blog;
use Validator,Redirect,Response,File;
class BlogController extends Controller
{
public function index()
{
$blogs = Blog::get();
return view('post.post_textarea',[
'blogs' => $blogs
]);
}
public function store(Request $request)
{
Blog::create([
'name' => $request->name,
'message' => $request->message,
'thumbnail' => $request->thumbnail,
]);
if ($files = $request->file('thumbnail')) {
$destinationPath = 'public/image/'; // upload path
$profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $profileImage);
$insert['thumbnail'] = "$profileImage";
}
return redirect()->back();
}
public function getFullPost($blog_id) {
$blogs = Blog::where('id', '=', $blog_id)->get();
return view('post.read')->with(compact('blogs'));
}
}
this is my view for the form
<form enctype="multipart/form-data" method="POST">
{{csrf_field()}}
<div class="form-group">
<h4 style="color: black;" >Judul</h4>
<br>
<input type="text" class="form-control" name="name">
</div>
<div class="form-group">
<h4 style="color: black;" >Thumbnail</h4>
<br>
<input type="file" name="thumbnail">
</div>
<div class="form-group">
<h4 style="color: black;" >Isi</h4>
<br>
<textarea class="form-control" name="message" id="" rows="10"></textarea>
</div>
<div class="form-group">
<button class="pull-right site-btn" type="submit" >Upload<img src="../public/asset/img/icons/double-arrow.png" alt="#"/></button>
</div>
</form>
and this is my view to display the data from database
#foreach ($blogs as $blog)
<div class="blog-item">
<div class="blog-thumb">
<img src="asset/img/blog/1.jpg" alt=""> ->this is where i was supposed to fetch the image
</div>
<div class="blog-text text-box text-white">
<div class="top-meta">{{ Carbon\Carbon::parse($blog->created_at)->format('d-m-Y') }} / di Rakitan</div>
<h3>{{ $blog->name }}</h3>
<p>{!! \Illuminate\Support\Str::words($blog->message, 30, '...') !!}</p>
Lanjutkan Baca <img src="asset/img/icons/double-arrow.png" alt="#"/>
</div>
</div>
#endforeach
try to add this in controller
$blog = new Blog;
$blog->name = $request->name;
$blog->message = $request->message;
if($request->hasFile('thumbnail')) {
$file = Input::file('thumbnail');
//getting timestamp
$timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
$name = $timestamp. '-' .$file->getClientOriginalName();
$file->move(public_path().'/images/', $name);
$blog->thumbnail = url('/images/' . $name);
}
$blog->save();
return back();
than in your view
#foreach ($blogs as $blog)
<div class="blog-item">
<div class="blog-thumb">
<img src="{{ $blog->thumbnail }}" alt=""> ->this is where i was supposed to fetch the image
</div>
<div class="blog-text text-box text-white">
<div class="top-meta">{{ Carbon\Carbon::parse($blog->created_at)->format('d-m-Y') }} / di Rakitan</div>
<h3>{{ $blog->name }}</h3>
<p>{!! \Illuminate\Support\Str::words($blog->message, 30, '...') !!}</p>
Lanjutkan Baca <img src="asset/img/icons/double-arrow.png" alt="#"/>
</div>
</div>
#endforeach
The problem with your code, I think in your store function, you did not save it correctly. Please see my code below to save link of your thumbnail into db.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Blog;
class BlogController extends Controller{
//some your function goes here
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$blog = new Blog;
$blog->name = $request->input('name');
$blog->message = $request->input('message');
$file = $request->file('your_thumbnail');
//make sure yo have image folder inside your public
$destination_path = 'image/';
$profileImage = date("Ymd").".".$file->getClientOriginalName();
$file->move($destination_path, $profileImage);
//save the link of thumbnail into myslq database
$blog->thumbnail = $destination_path . $profileImage;
$blog->save();
return redirect()->back();
}
}

Laravel upload image via another URL and store it in the database

I want to upload (and update) an image via Laravel.
I want an existing image name in my database to be replaced by a new one.
So I have this in my controller:
public function UpdatePic()
{
$rules = array(
'image' => 'required',
);
$random = str_random(40);
$validator = Validator::make(Input::all(), $rules);
//process the storage
if ($validator->fails())
{
Session::flash('error_message', 'Fout:' . $validator->errors());
return Redirect::to('admin/user#tab_2-2')->withErrors($validator);
}else{
//define the new random generated string for imagename
$imagename = str_random(40) . '.' . Input::file('image')->getClientOriginalName();
//store
$userimg = UserImage::find(1);
$userimg->img = $imagename;
$userimg->save();
//save the image
$destinationPath = 'public/img/user_img';
if (Input::hasFile('img'))
{
$file = Input::file('img');
$file->move('public/img/user_img', $imagename);
}
//redirect
Session::flash('success', 'Uw afbeelding is succesvol veranderd!');
return Redirect::to('admin/user#tab_2-2');
}
}
The problem is, When I Got this I'm getting this error:
Creating default object from empty value
I have a post route wich one looks like this:
Route::post('updateuserpic', 'UserController#UpdatePic');
So my view looks like this:
{{ Form::open(array('url' => 'admin/updateuserpic', 'files' => true)) }}
<div class="form-group">
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
<img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=Geen+afbeelding" alt=""/>
</div>
<div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;">
</div>
<div>
<span class="btn default btn-file">
<span class="fileinput-new">
Selecteer een afbeelding
</span>
<span class="fileinput-exists">
Verander
</span>
{{ Form::file('image') }}
</span>
<a href="#" class="btn red fileinput-exists" data-dismiss="fileinput">
Verwijder
</a>
</div>
</div>
<div class="clearfix margin-top-10">
<span class="label label-danger">
waarschuwing!
</span>
<span>
Dit is enkel ondersteund in de laatste versies van Firefox, Chrome, Opera, Safari and Internet Explorer 10!
</span>
</div>
</div>
<div class="margin-top-10">
{{ Form::submit('Opslaan', array('class' => 'btn green')) }}
<a href="{{ Config::get('app.url') }}/admin/user#tab_2-2" class="btn default">
Annuleer
</a>
</div>
{{ Form::close() }}
My Class only has this stuff:
<?php
class UserImage extends Eloquent{
protected $table = 'user_image';
public $timestamps = false;
}
I think the image disappears because I'm using that route, but I don't know how to fix it... It doesn't store the image in the folder and it doesn't store the random name in the database..
Thanks people!
Kindest regards,
Robin
try:
validator::make(Input::file('image'), $rules);
and change the Input from img to image:
if (Input::hasFile('image'))
{
$file = Input::file('image');
$file->move('public/img/user_img', $imagename);
}
also to edit the data in the databse, do:
UserImage::find(1)->update(['img' => $imagename]);
no need to open a object
also your route should be
Route::post('admin/updateuserpic', 'UserController#UpdatePic');
in your blade:
{{ Form::open(array('url' => 'admin/updateuserpic','method' => 'post' ,'files' => true)) }}
Update for comment
$file = array('image' => Input::file('image');
validator::make($file , $rules);
TBH, i think your code shouldn't be so complected. your Routes are fine, try changing your controller to:
<?php
public function UpdatePic(){
//first, I'll just do the file validation
$validator = Validator::make(array( 'image' => Input::file('image')),
array('image' => 'required|image'));
if($validator->fails()){
//return error code
Session::flash('error_message', 'Fout:' . $validator->errors());
return Redirect::to('admin/user#tab_2-2')->withErrors($validator);
}else{
//update the image name
$imageName = str_random(40) . '.' . Input::file('image')->getClientOrignalName();
//store
UserImage::find(1)->update(['img' => $imageName]);
//now move that image to the new location
$file = Input::file('image');
$file->move('public/img/user_img/', $imageName);
//now we have done, lets redirect back
Session::flash('success', 'Uw afbeelding is succesvol veranderd!');
return Redirect::to('admin/user#tab_2-2');
}
}
?>
The solotion I found with some help of other people wherefor thanks!
Controller:
public function UpdatePic(){
//first, I'll just do the file validation
$validator = Validator::make(array( 'image' => Input::file('image')),
array('image' => 'required|image'));
if($validator->fails()){
//return error code
Session::flash('error_message', 'Fout:' . $validator->errors());
return Redirect::to('admin/user#tab_2-2')->withErrors($validator);
}else{
//update the image name
$imageName = str_random(40) . '.' . Input::file('image')->getClientOriginalName();
//store
UserImage::where('uid', '=', Auth::user()->id)->update(['img' => $imageName]);
//now move that image to the new location
$file = Input::file('image');
$file->move('public/img/user_img/', $imageName);
//now we have done, lets redirect back
Session::flash('success', 'Uw afbeelding is succesvol veranderd!');
return Redirect::to('admin/user#tab_2-2');
}
}
The view is just an normal input.
Hope this can help other people!
Special thanks to Ashley Wrench
I used raw PHP for the job
$source = $data['Poster']; /* URL of remote image */
$dest = "posters/".$data['Year']; /* Path */
if (!file_exists($dest)) {
mkdir($dest, 0777, true); /* Create directory */
}
$dest .= "/".$data['imdbID'].".jpg"; /* Complete file name */
/* Copy the file */
copy($source, $dest);

Categories