i'm tryng to resize image of user profile, but i have this error:
NotReadableException in Decoder.php line 96: Unable to init from given
binary data.
MY CONTROLLER
public function updateAvatar(Request $request){
if ($request->hasFile('image')) {
$user_id = Auth::user()->id . '.' . $request->file('image')->getClientOriginalExtension();
// if i insert here: retur $user_id it return: 1.jpg it work well,
// my form work well, before i tryed to upload without resize and it work well.
// i want save image uploaded with id user and extention
// here i'm tryng to resize it, i installed intervation and inserted class
$img = Image::make('images/users',$user_id);
$img->resize(100, 100);
$img->save('images/users',$user_id);
$user = new User;
$user->where('email', '=', Auth::user()->email)
->update(['image' => 'images/users/'.$user_id]);
return redirect('account')->with('message-success', 'Immagine profilo aggiornata con successo!');
}else{
return redirect('account')->with('message-error', 'File non trovato');
}
}
You're trying to supply two arguments to Image::make(), but it should only be given one. I think you might want to do e.g. Image::make('images/users/'.$user_id) instead? Or whatever your full path to the file is.
Try this - I think you were trying to create an Image from a text string, or possibly something that doesn't exist. I don't have my code editor in front of me, so I can't test, let me know what you get?
public function updateAvatar(Request $request){
if ($request->hasFile('image')) {
$user_id = Auth::user()->id . '.' . $request->file('image')->getClientOriginalExtension();
$img = Image::make($request->file('image'));
$img->resize(100, 100);
$img->save('images/users',$user_id);
$user = new User;
$user->where('email', '=', Auth::user()->email)
->update(['image' => 'images/users/'.$user_id]);
return redirect('account')->with('message-success', 'Immagine profilo aggiornata con successo!');
} else{
return redirect('account')->with('message-error', 'File non trovato');
}
}
public function updateAvatar(Request $request){
if ($request->hasFile('image')) {
$user_id = Auth::user()->id . '.' . $request->file('image')->getClientOriginalExtension();
$base=base64_decode($request['image']);
$img = Image::make($base)->save($path);
$img->resize(100, 100);
$img->save('images/users',$user_id);
$user = new User;
$user->where('email', '=', Auth::user()->email)
->update(['image' => 'images/users/'.$user_id]);
return redirect('account')->with('message-success', 'Immagine profilo aggiornata con successo!');
} else{
return redirect('account')->with('message-error', 'File non trovato');
}
}
This will definitely solve your issue..
Related
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();
}
}
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);
I've been searching all around the net to try to fix this problem. Changed the code in my controllersfolder multiple times and still no solution. I changed the permissions of my img folder and products folder to 777 and still no success.
This is the structure of my folders on my FTP cyberduck:
-->app_base/ ( Has Everything from the base laravel folder EXCEPT the /public/ folder)
-->[some other folders...]
-->public_html/
-->daveswebapp.us/ (name of my website. Has all the content of my base public/folder)
-->img
-->products
[empty folder]
This is the error I receive each time I try to upload new product images in my admin panel:
Intervention \ Image \ Exception \ NotWritableException
Can't write image data to path (/home2/ecuanaso/app_base/bootstrap/img/products/1417822656.jpg)
PRODUCTS CONTROLLER CODE:
<?php
class ProductsController extends BaseController {
public function __construct() {
parent::__construct();
$this->beforeFilter('csrf', array('on'=>'post'));
$this->beforeFilter('admin');
}
public function getIndex() {
$categories = array();
foreach(Category::all() as $category) {
$categories[$category->id] = $category->name;
}
return View::make('products.index')
->with('products', Product::all())
->with('categories', $categories);
}
public function postCreate() {
$validator = Validator::make(Input::all(), Product::$rules);
if ($validator->passes()) {
$product = new Product;
$product->category_id = Input::get('category_id');
$product->title = Input::get('title');
$product->description = Input::get('description');
$product->price = Input::get('price');
$image = Input::file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$path = public_path('img/products/' . $filename);
Image::make($image->getRealPath())->resize(468, 249)->save($path);
$product->image = 'img/products/'.$filename;
$product->save();
return Redirect::to('admin/products/index')
->with('message', 'Product Created');
}
return Redirect::to('admin/products/index')
->with('message', 'Something went wrong')
->withErrors($validator)
->withInput();
}
public function postDestroy() {
$product = Product::find(Input::get('id'));
if ($product) {
File::delete('public/'.$product->image);
$product->delete();
return Redirect::to('admin/products/index')
->with('message', 'Product Deleted');
}
return Redirect::to('admin/products/index')
->with('message', 'Something went wrong, please try again');
}
public function postToggleAvailability() {
$product = Product::find(Input::get('id'));
if ($product) {
$product->availability = Input::get('availability');
$product->save();
return Redirect::to('admin/products/index')->with('message', 'Product Updated');
}
return Redirect::to('admin/products/index')->with('message', 'Invalid Product');
}
}
Images should go into public folder and not in app directory in your code you are trying to move the image into app directoy but defining directory address with public_path the following code uploads an image into your public/uploads folder which is then accessible via visiting yourdomain.com/img.jpg
//create two empty variables outside of conditional statement because we gonna access them later on
$filename = "";
$extension = "";
//check if you get a file from input, assuming that the input box is named photo
if (Input::hasFile('photo'))
{
//create an array with allowed extensions
$allowedext = array("png","jpg","jpeg","gif");
/get the file uploaded by user
$photo = Input::file('photo');
//set the destination path assuming that you have chmod 777 the upoads folder under public directory
$destinationPath = public_path().'/uploads';
//generate a random filename
$filename = str_random(12);
//get the extension of file uploaded by user
$extension = $photo->getClientOriginalExtension();
//validate if the uploaded file extension is allowed by us in the $allowedext array
if(in_array($extension, $allowedext ))
{
//everything turns to be true move the file to the destination folder
$upload_success = Input::file('photo')->move($destinationPath, $filename.'.'.$extension);
}
Not sure if a a solution goes here but I figured it out after days of seaching.
I was saving the file into the wrong directory. took out the public from ->save method
I changed
Image::make($image->getRealPath())->resize(468, 249)->save('public/img/products/'.$filename);
to:
Image::make($image->getRealPath())->resize(468, 249)->save('img/products/'.$filename);
I am having some trouble with a photo upload system I'm working on in Laravel. So far, I have the file coming in and saving in public/images/profiles just fine, but I can't figure out how to insert it into the db with the right information. Currently I'm getting a "Call to undefined method Illuminate\Database\Eloquent\Collection::save() " error.
In my controller, I am currently trying to insert it by doing this:
public function updatePhotos($id)
{
if(Input::hasFile('image'))
//If file is being added
{
$extension = Input::file('image')->getClientOriginalExtension();
$fileName = str_random(9).'.'.$extension;
$user = User::find($id);
$user->profile->photo->type = 1;
$user->profile->photo->filename = $fileName;
$user->profile->photo->save();
Input::file('image')->move('public/images/profiles/',$fileName);
}
}
In the Photo model:
public function profile()
{
return $this->hasOne('Profile');
}
In the profile model, I have:
public function photo()
{
return $this->hasMany('Photo','user_id','user_id');
}
Could anybody send me on the right course for this?
Thanks
You are trying to save the user model, you have to create a new photo model, fill it with data and save it.
public function updatePhotos($id)
{
$image = new Image();
$image->user_id = Auth::id();
$image->fill(Input::all());
if (Input::hasFile('file')) {
$file = Input::file('file');
$image->extension = $file->guessClientExtension();
$image->size = $file->getClientSize();
$image->filename = str_random(9) . '.' . $image->extension;
$uploadSuccess = $file->move('public/images/profiles/', $image->filename);
$image->save();
$user = User::find($id);
$user->image = $image->id;
$user-save();
}
}
}
New image object created.
Field user_id on image object is set to the current users ID.
All fillable fields are filled with data from the form.
If input has file, file is set to $image->user_id = Auth::id();
Image extension, size and filename is set on image object.
Image is moved (placed) in public/images/profiles/ folder.
Image object is saved.
Get user object, assign image field with image ID and save user object.
I am trying to delete an old user image, if the user updates his profile picture. I am using Laravel 4.1 and a resourceful UsersController.
Updating the picture works perfectly fine. A new one is saved in my folder and the file nave is overwritten in the database. However, I would like to delete the old image. Therefore I have the following code, which works fine if I use it on an empty page with route get 'test' for example
$oldimage = Auth::user()->profile_picture;
File::delete('img/profile_pictures/users/' . $oldimage);
Everytime I try to implement this into the process of updating the image, the old one is not deleted. I have already in mind that I have to delete the old one before overwriting the file name.
Does this have to do anything with the POST method the Controller uses for updating? How could I fix it?
public function update($id){
$validation = Validator::make(
Input::all(), [
'name'=>'required',
'surname'=>'required',
'email'=>'required',
'email' => 'email']);
if($validation->fails()){
return Redirect::to(
'dashboard#profile'
)->withInput()->withErrors(
$validation->messages());
}
$user = User::find($id);
$user->name = Input::get('name');
$user->surname = Input::get('surname');
$user->email = Input::get('email');
if (Input::hasFile('profile_picture_update')) {
$oldimage = Auth::user()->profile_picture;
File::delete('img/profile_pictures/users/' . $oldimage);
}
$imageFile = Input::file('profile_picture_update');
$newprofile_picture = Image::make(
$imageFile->getRealPath()
)->resize(400, null, true)->crop(400, 400);
$name = time() . '-' .
Input::get('name') .
'-' . Input::get('surname') .
'.' . $imageFile->getClientOriginalExtension();
// $name = time() . '-' . $profile_picture->getClientOriginalName();
// Below the profile_picture variable is overrridden.
$newprofile_picture = $newprofile_picture->save(
public_path().'/img/profile_pictures/users/'.$name
);
$user->profile_picture = $name;
$user->save();
return Redirect::to(
'dashboard#profile'
)->with(
'updatemessage', 'Yep! Deine Ă„nderungen wurden gespeichert.'
);
}
why don't you use the User model you just retrieved to get the old image?
if (Input::hasFile('profile_picture_update')) {
$oldimage = Auth::user()->profile_picture;
File::delete('img/profile_pictures/users/' . $oldimage);
}
replace it with
if (Input::hasFile('profile_picture_update')) {
$oldimage = $user->profile_picture;
File::delete('img/profile_pictures/users/' . $oldimage);
}
I found a way to do this by creating a helper function an then calling the helper function in the controller method.
http://laravel.com/docs/helpers