Пример #1
1
 public function findByUserNameOrCreate($userData)
 {
     $user = User::where('social_id', '=', $userData->id)->first();
     if (!$user) {
         $user = new User();
         $user->social_id = $userData->id;
         $user->email = $userData->email;
         $user->first_name = $userData->user['first_name'];
         $user->last_name = $userData->user['last_name'];
         $name = str_random(32);
         while (!User::where('avatar', '=', $name . '.jpg')->get()->isEmpty()) {
             $name = str_random(32);
         }
         $filename = $name . '.' . 'jpg';
         Image::make($userData->avatar_original)->fit(1024, 1024)->save(public_path() . '/avatars_large/' . $filename);
         Image::make(public_path() . '/avatars_large/' . $filename)->resize(200, 200)->save(public_path() . '/avatars/' . $filename);
         $user->avatar = $filename;
         $user->gender = $userData->user['gender'];
         $user->verified = $userData->user['verified'];
         $user->save();
         \Session::put('auth_photo', $filename);
     } else {
         $this->checkIfUserNeedsUpdating($userData, $user);
         \Session::put('auth_photo', $user->avatar);
     }
     return $user;
 }
Пример #2
0
 public function postAdd(Request $request, Agent $agent)
 {
     $data = $request->all();
     $validation = Validator::make($data, Poster::getValidationRules());
     if ($validation->fails()) {
         return view('message', ['OKs' => [], 'errors' => $validation->errors()->all()]);
     }
     $original_image_dir = 'images/original/';
     $small_image_dir = 'images/small/';
     $original_image_name = $original_image_dir . "no_image.jpg";
     $small_image_name = $small_image_dir . "no_image_sml.jpg";
     if ($request->hasFile('image')) {
         $time = time();
         $original_image_name = $original_image_dir . $time . '.jpg';
         $small_image_name = $small_image_dir . $time . '.jpg';
         Image::make(Input::file('image'))->save($original_image_name)->resize(200, null, function ($constraint) {
             $constraint->aspectRatio();
         })->save($small_image_name);
     } else {
     }
     $data['image'] = $original_image_name;
     $data['image_sml'] = $small_image_name;
     $data['author_ip'] = $request->getClientIp();
     $data['author_browser'] = $agent->browser();
     $data['author_country'] = "Ukraine";
     Poster::create($data);
     return view('message', array('OKs' => ['Poster created'], 'errors' => ['']));
 }
Пример #3
0
 public function update(Request $request)
 {
     $user = $request->auth;
     $id = $request->route('id');
     $uniq = md5(uniqid(time(), true));
     if ($request->hasFile('image')) {
         $types = array('115x69', '285x170', '617x324');
         // Width and height for thumb and resiged
         $sizes = array(array('115', '69'), array('285', '170'), array('617', '324'));
         $targetPath = 'img/media/';
         $image = $request->file('image');
         $ext = $image->getClientOriginalExtension();
         foreach ($types as $key => $type) {
             Image::make($image)->fit($sizes[$key][0], $sizes[$key][1])->save($targetPath . $type . "/" . $uniq . '.' . $ext);
         }
     }
     $post = PostModel::findOrFail($id);
     $post->pos_name = ucfirst($request->input('pos_name'));
     $post->pos_slug = $request->input('pos_slug');
     if ($request->hasFile('image')) {
         $post->pos_image = $uniq . '.' . $ext;
     }
     $post->pos_sum = $request->input('pos_sum');
     $post->pos_desc = $request->input('pos_desc');
     $post->pos_status_cd = "ACT";
     $post->cat_id = $request->input('cat_id');
     $post->updated_by = $user->usr_id;
     if (!$post->save()) {
         return "Error";
     }
     return Redirect::route('postHome');
 }
 public function putEdit(Request $request)
 {
     if (!ACL::hasPermission('awards', 'edit')) {
         return redirect(route('awards'))->withErrors(['Você não pode editar os prêmios.']);
     }
     $this->validate($request, ['title' => 'required|max:45', 'warning' => 'required', 'image' => 'image|mimes:jpeg,bmp,gif,png'], ['title.required' => 'Informe o título do prêmio', 'title.max' => 'O título do prêmio não pode passar de :max caracteres', 'warning.required' => 'Informe o aviso sobre o prêmio', 'image.image' => 'Envie um formato de imagem válida', 'image.mimes' => 'Formato suportado: .png com fundo transparente']);
     $award = Awards::find($request->awardsId);
     $award->title = $request->title;
     $award->warning = $request->warning;
     if ($request->image) {
         //DELETE OLD IMAGE
         if ($request->currentImage != "") {
             if (File::exists($this->folder . $request->currentImage)) {
                 File::delete($this->folder . $request->currentImage);
             }
         }
         $extension = $request->image->getClientOriginalExtension();
         $nameImage = Carbon::now()->format('YmdHis') . "." . $extension;
         Image::make($request->file('image'))->resize($this->imageWidth, $this->imageHeight)->save($this->folder . $nameImage);
         $award->image = $nameImage;
     }
     $award->save();
     $success = "Prêmio editado com sucesso";
     return redirect(route('awards'))->with(compact('success'));
 }
Пример #5
0
 public static function uploadTextarea($texto, $tipo_midia)
 {
     $nomeTipo = TipoMidia::findOrFail($tipo_midia)->descricao;
     // gravando imagem do corpo da noticia
     $dom = new \DOMDocument();
     $dom->loadHtml($texto, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
     $images = $dom->getElementsByTagName('img');
     // foreach <img> in the submited message
     foreach ($images as $img) {
         $src = $img->getAttribute('src');
         // if the img source is 'data-url'
         if (preg_match('/data:image/', $src)) {
             // get the mimetype
             preg_match('/data:image\\/(?<mime>.*?)\\;/', $src, $groups);
             $mimetype = $groups['mime'];
             // Generating a random filename
             $filename = md5(uniqid());
             $filepath = "uploads/" . $nomeTipo . "/" . $filename . '.' . $mimetype;
             // @see http://image.intervention.io/api/
             $image = Image::make($src)->encode($mimetype, 100)->save(public_path($filepath));
             $new_src = asset($filepath);
             $img->removeAttribute('src');
             $img->setAttribute('src', $new_src);
         }
     }
     return $dom->saveHTML();
 }
Пример #6
0
 /**
  * Update the users profile
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  int  $id
  * @return \Illuminate\Http\Response
  */
 public function store(Request $request)
 {
     $user = User::find($request->input('user_id'));
     $user->name = $request->input('name');
     $user->email = $request->input('email');
     $user->username = $request->input('username');
     if ($request->input('password') != '') {
         $user->password = bcrypt($request->input('password'));
     }
     $user->update();
     $company = Company::where('user_id', $request->input('user_id'))->first();
     $company->name = $request->input('company_name');
     $company->description = $request->input('company_description');
     $company->phone = $request->input('company_phone');
     $company->email = $request->input('company_email');
     $company->address1 = $request->input('company_address');
     $company->address2 = $request->input('company_address2');
     $company->city = $request->input('company_city');
     $company->postcode = $request->input('company_postcode');
     if ($request->hasFile('logo')) {
         $file = $request->file('logo');
         $name = Str::random(25) . '.' . $file->getClientOriginalExtension();
         $image = Image::make($request->file('logo')->getRealPath())->resize(210, 113, function ($constraint) {
             $constraint->aspectRatio();
         });
         $image->save(public_path() . '/uploads/' . $name);
         $company->logo = $name;
     }
     $company->update();
     flash()->success('Success', 'Profile updated');
     return back();
 }
Пример #7
0
 /**
  * Store a newly created resource in storage.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return \Illuminate\Http\Response
  */
 public function store($image, $type, $primary_id, $current_link)
 {
     $image_link = array_key_exists($type, Input::all()) ? Input::file($type) != '' ? '/allgifted-images/' . $type . '/' . $primary_id . '.' . $image->getClientOriginalExtension() : $current_link : $current_link;
     array_key_exists($type, Input::all()) ? File::exists(public_path($image_link)) ? File::delete(public_path($image_link)) : null : null;
     $image ? Image::make($image)->fit(500, 300)->save(public_path($image_link)) : null;
     return $image_link;
 }
Пример #8
0
 protected function makeImage($file, $height, $width, $randomFilename, $thumbnail = null)
 {
     $md5 = md5_file($file->getRealPath());
     $img = Image::make($file)->fit($height, $width);
     $path = 'images/';
     if ($thumbnail != null) {
         $path = 'images/thumb/';
     }
     $image = Images::where('md5_hash', $md5)->first();
     if ($image === null or $image->thumbnail_file == null) {
         Clockwork::info('Storing on Filesystem');
         $img->save(storage_path() . '/app/' . $path . $randomFilename . '.png', 90);
     }
     if ($image === null and $thumbnail === null) {
         Clockwork::info('New Image');
         $image = new Images();
         $image->user_id = Auth::user()->id;
         $image->filename = $file->getClientOriginalName();
         $image->file = $randomFilename . '.png';
         $image->height = $height;
         $image->width = $width;
         $image->md5_hash = $md5;
     } elseif ($thumbnail != null and $image->thumbnail_file == null) {
         Clockwork::info('Thumbnail Updated');
         $image->thumbnail_file = $randomFilename . '.png';
     }
     $image->save();
     return $image;
 }
 public function putEdit(Request $request)
 {
     if (!ACL::hasPermission('winners2014', 'edit')) {
         return redirect(route('winners2014'))->withErrors(['Você não pode editar os ganhadores de 2014.']);
     }
     $this->validate($request, ['category' => 'required', 'position' => 'required', 'name' => 'required|max:50', 'city' => 'required|max:45', 'state' => 'required|max:2|min:2', 'quantityVotes' => 'required|numeric', 'image' => 'image|mimes:jpeg,bmp,gif,png'], ['category.required' => 'Escolha a categoria', 'position.required' => 'Escolha a posição', 'name.required' => 'Informe o nome do ganhador', 'name.max' => 'O nome do ganhador não pode passar de :max caracteres', 'city.required' => 'Informe o nome da cidade do ganhador', 'city.max' => 'O nome da cidade não pode passar de :max caracteres', 'state.required' => 'Informe o Estado do ganhador', 'state.max' => 'O UF do Estado deve ter apenas :max caracteres', 'state.min' => 'O UF do Estado deve ter apenas :min caracteres', 'quantityVotes.required' => 'Informe a quantidade de votos', 'quantityVotes.numeric' => 'Somente números são aceitos', 'image.image' => 'Envie um formato de imagem válida', 'image.mimes' => 'Formatos suportados: .jpg, .gif, .bmp e .png']);
     $winner = WinnersLastYear::find($request->winnersLastYearId);
     $winner->category = $request->category;
     $winner->position = $request->position;
     $winner->name = $request->name;
     $winner->city = $request->city;
     $winner->state = $request->state;
     $winner->quantityVotes = $request->quantityVotes;
     if ($request->photo) {
         //DELETE OLD PHOTO
         if ($request->currentPhoto != "") {
             if (File::exists($this->folder . $request->currentPhoto)) {
                 File::delete($this->folder . $request->currentPhoto);
             }
         }
         $extension = $request->photo->getClientOriginalExtension();
         $namePhoto = Carbon::now()->format('YmdHis') . "." . $extension;
         $img = Image::make($request->file('photo'));
         if ($request->photoCropAreaW > 0 or $request->photoCropAreaH > 0 or $request->photoPositionX or $request->photoPositionY) {
             $img->crop($request->photoCropAreaW, $request->photoCropAreaH, $request->photoPositionX, $request->photoPositionY);
         }
         $img->resize($this->photoWidth, $this->photoHeight)->save($this->folder . $namePhoto);
         $winner->photo = $namePhoto;
     }
     $winner->save();
     $success = "Ganhador editado com sucesso";
     return redirect(route('winners2014'))->with(compact('success'));
 }
Пример #10
0
 /**
  * Create a new user instance after a valid registration.
  *
  * @param  array  $data
  * @return User
  */
 protected function create(array $data)
 {
     //Dodavanje slika
     if (isset($data['foto'])) {
         $image = $data['foto'];
         $image_name = $image->getClientOriginalName();
         $image->move('img/korisnici', $image_name);
         $image_final = 'img/korisnici/' . $image_name;
         $int_image = Image::make($image_final);
         $int_image->resize(300, null, function ($promenljiva) {
             $promenljiva->aspectRatio();
         });
         $int_image->save($image_final);
     } else {
         $image_final = 'img/default/slika-korisnika.jpg';
     }
     //Dodavanje novog grada
     if ($data['novi_grad']) {
         $pomocna = DB::table('grad')->where('grad.naziv', '=', $data['novi_grad'])->first();
         if ($pomocna) {
             $data['grad_id'] = $pomocna->id;
         } else {
             Grad::create(['naziv' => $data['novi_grad']]);
             $pomocna = DB::table('grad')->where('grad.naziv', '=', $data['novi_grad'])->first();
             $data['grad_id'] = $pomocna->id;
         }
     }
     //Dodavanje novog korisnika
     $aktivacioni_kod = str_random(30);
     $podaci = array('aktivacioni_kod' => $aktivacioni_kod);
     Mail::send('emails.aktiviranje_naloga', $podaci, function ($message) {
         $message->to(Input::get('email'), Input::get('username'))->subject('Активирање налога');
     });
     return User::create(['prezime' => $data['prezime'], 'ime' => $data['ime'], 'password' => bcrypt($data['password']), 'username' => $data['username'], 'email' => $data['email'], 'adresa' => $data['adresa'], 'grad_id' => $data['grad_id'], 'telefon' => $data['telefon'], 'opis' => $data['bio'], 'foto' => $image_final, 'aktivacioni_kod' => $aktivacioni_kod, 'token' => $data['_token']]);
 }
Пример #11
0
 /**
  * Create a new UploadImageAbstract instance
  *
  * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file
  */
 public function __construct($file)
 {
     $this->file = $file;
     $this->hash = mt_rand(1000000000, 4294967295);
     $this->image = InterventionImage::make($this->file);
     $this->uploaded_at = Carbon::now();
 }
Пример #12
0
 public function create(Offer $offer, Request $request)
 {
     if ($request->user()->cannot('edit-offer', [$offer])) {
         abort(403);
     }
     $this->validate($request, ['title' => 'required', 'image' => 'required|image', 'expired_at' => 'required']);
     $user = Auth::user();
     // wildcard is needed
     $offer = $user->offers()->where('id', $offer->id)->where('status', 1)->valid()->firstOrFail();
     $input = $request->all();
     $data = $request->input('cropper_json');
     $data = json_decode(stripslashes($data));
     $image = $input['image'];
     $imageName = $user->id . str_random(20) . "." . $image->getClientOriginalExtension();
     $image->move(public_path() . '/img/files/' . $user->id, $imageName);
     $src = public_path() . '/img/files/' . $user->id . '/' . $imageName;
     $img = Image::make($src);
     $img->rotate($data->rotate);
     $img->crop(intval($data->width), intval($data->height), intval($data->x), intval($data->y));
     $img->resize(851, 360);
     $img->save($src, 90);
     $service = $user->coupon_gallery()->create(['offer_id' => $offer->id, 'title' => $input['title'], 'description' => $input['description'], 'expired_at' => $input['expired_at'], 'image' => $user->id . "/" . $imageName]);
     Flash::success(trans('messages.offerCreated'));
     $user->usage->add(filesize(public_path() . '/img/files/' . $user->id . '/' . $imageName) / (1024 * 1024));
     // storage add
     return redirect()->back();
 }
 /**
  * Display the specified resource.
  *
  * @param $image_slug
  * @param int $width
  * @return Response
  */
 public function show($image_slug, $width = 500)
 {
     $currentUser = $this->getUser();
     //$size = (Input::get('size')? (is_numeric(Input::get('size'))? Input::get('size') : 500) : 500);//TODO: Extract this to global config
     $comicImage = ComicImage::where('image_slug', '=', $image_slug)->first();
     if (!$comicImage) {
         return $this->respondNotFound(['title' => 'Image Not Found', 'detail' => 'Image Not Found', 'status' => 404, 'code' => '']);
     }
     $userCbaIds = $currentUser->comics()->lists('comic_book_archive_id')->all();
     $comicCbaIds = $comicImage->comicBookArchives()->lists('comic_book_archive_id')->all();
     foreach ($comicCbaIds as $comicCbaId) {
         if (!in_array($comicCbaId, $userCbaIds)) {
             return $this->respondNotFound(['title' => 'Image Not Found', 'detail' => 'Image Not Found', 'status' => 404, 'code' => '']);
         }
     }
     $img = Image::make($comicImage->image_url);
     $imgCache = Image::cache(function ($image) use($img, $width) {
         $image->make($img)->interlace()->resize(null, $width, function ($constraint) {
             $constraint->aspectRatio();
             $constraint->upsize();
         });
     }, 60, true);
     //dd($imgCache->response());
     return $imgCache->response();
 }
Пример #14
0
 public function uploadPhoto($userId, $filePath, $newImage = false)
 {
     $tmpFilePath = storage_path('app') . '/' . $userId . '.png';
     $tmpFilePathThumb = storage_path('app') . '/' . $userId . '-thumb.png';
     try {
         $this->correctImageRotation($filePath);
     } catch (\Exception $e) {
         \Log::error($e);
         //Continue on - this isnt that important
     }
     //Generate the thumbnail and larger image
     Image::make($filePath)->fit(500)->save($tmpFilePath);
     Image::make($filePath)->fit(200)->save($tmpFilePathThumb);
     if ($newImage) {
         $newFilename = \App::environment() . '/user-photo/' . md5($userId) . '-new.png';
         $newThumbFilename = \App::environment() . '/user-photo/' . md5($userId) . '-thumb-new.png';
     } else {
         $newFilename = \App::environment() . '/user-photo/' . md5($userId) . '.png';
         $newThumbFilename = \App::environment() . '/user-photo/' . md5($userId) . '-thumb.png';
     }
     Storage::put($newFilename, file_get_contents($tmpFilePath), 'public');
     Storage::put($newThumbFilename, file_get_contents($tmpFilePathThumb), 'public');
     \File::delete($tmpFilePath);
     \File::delete($tmpFilePathThumb);
 }
Пример #15
0
 public function __toString()
 {
     if ($this->isSkip) {
         return '';
     }
     $methodsHash = md5(serialize($this->methods));
     $hash = md5($this->fileHash . $methodsHash);
     $source = 'storage/cropp/' . $hash . $this->extension;
     if (is_readable(public_path($source))) {
         return $source;
     }
     $image = Image::make($this->source);
     foreach ($this->methods as $method) {
         call_user_func_array(array($image, $method['name']), $method['arguments']);
     }
     $res = $image->save(public_path($source));
     if (!$res) {
         throw new RuntimeException('Do you have writeable [public/storage/cropp/] directory?');
     }
     if (\Config::get('jarboe::cropp.is_optimize')) {
         $optimizer = new \Extlib\ImageOptimizer(array(\Extlib\ImageOptimizer::OPTIMIZER_OPTIPNG => \Config::get('jarboe::cropp.binaries.optipng'), \Extlib\ImageOptimizer::OPTIMIZER_JPEGOPTIM => \Config::get('jarboe::cropp.binaries.jpegoptim'), \Extlib\ImageOptimizer::OPTIMIZER_GIFSICLE => \Config::get('jarboe::cropp.binaries.gifsicle')));
         $optimizer->optimize(public_path($source));
     }
     return $source;
 }
Пример #16
0
 /**
  * Resize function.
  * @param $filename
  * @param $sizeString
  * @return blob image contents.
  * @internal param filename $string
  * @internal param sizeString $string
  *
  */
 public function resize_image($filename, $sizeString)
 {
     // Get the output path from our configuration file.
     $outputDir = Config::get('assets.images.paths.output');
     // Create an output file path from the size and the filename.
     $outputFile = $outputDir . '/' . $sizeString . '_' . $filename;
     // If the resized file already return it.
     if (File::isFile($outputFile)) {
         return File::get($outputFile);
     }
     // File doesn't exist yet - resize the original.
     $inputDir = Config::get('assets.images.paths.input');
     $inputFile = $inputDir . '/' . $filename;
     // Get the width of the chosen size from the Config file.
     $sizeArr = Config::get('assets.images.sizes.' . $sizeString);
     $width = $sizeArr['width'];
     // Create the output directory if it doesn't exist yet.
     if (!File::isDirectory($outputDir)) {
         File::makeDirectory($outputDir, 493, true);
     }
     // Open the file, resize with the ratio it and save it.
     $img = InterventionImg::make($inputFile);
     $img->resize($width, null, function ($constraint) {
         $constraint->aspectRatio();
     })->save($outputFile, 100);
     // Return the resized  file.
     return File::get($outputFile);
 }
Пример #17
0
 /**
  * Store a newly created resource in storage.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return \Illuminate\Http\Response
  */
 public function store(Request $request)
 {
     // register
     // Log::info('register pochetok');
     // Log::info($request);
     // Log::info($request->get('first_name')); // ti dava samo value
     // Log::info($request->only('first_name')); // ti dava cela niza so key value
     $user = new User();
     $user->first_name = $request->get('first_name');
     $user->last_name = $request->get('last_name');
     $user->email = $request->get('email');
     $user->password = bcrypt($request->get('password'));
     $user->skype_id = $request->get('skype_id');
     $user->contact_number = $request->get('contact_number');
     if (Input::hasFile('profile_picture')) {
         Log::info('has file');
         $file = Input::file('profile_picture');
         $extension = pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION);
         $filename = base64_encode($user->email) . "." . $extension;
         $file->move('uploads/profile_pictures', $filename);
         // vistinskata profilna slika
         $image = Image::make('uploads/profile_pictures/' . $filename);
         $image->fit(160, 160);
         $image->save('uploads/profile_pictures/thumbnails/' . $filename);
         // update vo folder
         $user->profile_picture = $filename;
     }
     // proverka za email dali vekje ima (verojatno Eloquent sam kje vrati) imame staveno unique :)
     $user->save();
 }
Пример #18
0
 public function get($source, $options)
 {
     if (!$source) {
         return;
     }
     $this->setOptions($options);
     $source = "/" . ltrim($source, "/");
     $sourceArray = pathinfo($source);
     //create variables $dirname , $basename, $extension, $filename
     extract($sourceArray);
     $this->nameFile = $filename . "_" . $this->quality . "." . $extension;
     $this->pathFolder = $dirname . "/" . $this->size;
     $this->picturePath = $this->pathFolder . "/" . $this->nameFile;
     if (self::checkExistPicture()) {
         return $this->picturePath;
     }
     try {
         $img = Image::make(public_path() . $source);
         $this->createRatioImg($img, $options);
         @mkdir(public_path() . $this->pathFolder);
         $pathSmallImg = public_path() . "/" . $this->picturePath;
         $img->save($pathSmallImg, $this->quality);
         OptmizationImg::run($this->picturePath);
         return $this->picturePath;
     } catch (\Exception $e) {
         return $e->getMessage();
     }
 }
Пример #19
0
 public function preview($mode = 'auto', $size = null, $name = null)
 {
     if (!is_null($mode) && !is_null($size) && !is_null($name)) {
         if (preg_match('/http\\:\\/\\//', $name) || !preg_match('/http\\:\\/\\//', $name) && \File::exists(public_path() . '/' . $name)) {
             $file = pathinfo($name)['basename'];
             $folder = $this->generateFolder($mode, $size, $name);
             $fullname = public_path() . '/' . $folder . $file;
             $size = explode('x', $size);
             $width = isset($size[0]) ? $size[0] : null;
             $height = isset($size[1]) ? $size[1] : null;
             if ($mode == 'crop') {
                 $image = Image::make($name)->fit($width, $height);
             } else {
                 $image = Image::make($name)->resize($width, $height, function ($constraint) {
                     $constraint->aspectRatio();
                     $constraint->upsize();
                 });
             }
             $image->save($fullname, 100);
             $info = getimagesize($fullname);
             return true;
         } else {
             return false;
         }
     } else {
         return false;
     }
 }
Пример #20
0
 private function getBrazzifiedImage($url, $logo_loc)
 {
     $valid_logo_locations = ['top-left', 'top', 'top-right', 'left', 'center', 'right', 'bottom-left', 'bottom', 'bottom-right'];
     try {
         $img = Image::make($url);
     } catch (\Exception $e) {
         return ['error' => 'Image or URL is not valid.'];
     }
     if (!in_array($logo_loc, $valid_logo_locations)) {
         return ['error' => 'Not a valid logo location.'];
     }
     $img->insert(base_path() . '/resources/images/brazzers-logo.png', $logo_loc, 10, 10);
     $finished_image = $img->encode('png');
     $image_hash = hash('sha256', $finished_image . $logo_loc);
     $existing_image = ImageModel::where('hash', $image_hash)->first();
     if ($existing_image) {
         $imgur_id = $existing_image->image_host_id;
     } else {
         $client = new Client(['base_uri' => 'https://api.imgur.com', 'timeout' => 10, 'headers' => ['Authorization' => 'Client-ID ' . env('IMGUR_CLIENT_ID')]]);
         $response = $client->request('POST', '3/image', ['form_params' => ['image' => base64_encode($finished_image), 'type' => 'base64', 'description' => 'Image generated by http://brazzify.me']]);
         if ($response->getStatusCode() != 200) {
             return ['error' => 'Error uploading image to imgur.'];
         }
         $imgur_response = json_decode($response->getBody()->getContents());
         $imgur_id = $imgur_response->data->id;
         $image_model = new ImageModel();
         $image_model->hash = $image_hash;
         $image_model->image_host = 1;
         $image_model->image_host_id = $imgur_id;
         $image_model->save();
     }
     return ['imgur_id' => $imgur_id];
 }
Пример #21
0
 /**
  * User registration
  *
  * @param Request $request
  * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
  */
 public function register(Request $request)
 {
     if ($request->isMethod('post')) {
         $rules = ['first_name' => 'required', 'last_name' => 'required', 'position' => 'required', 'phone' => 'phone:AM', 'username' => 'required|unique:users,username', 'email' => 'required|email|unique:users,email', 'pass' => 'required|min:6|max:12', 'pass_confirmation' => 'required|min:6|max:12|same:pass', 'image' => 'mimes:jpeg,jpg,png'];
         Validator::make($request->all(), $rules)->validate();
         $user = new User();
         $user->first_name = $request->input('first_name');
         $user->last_name = $request->input('last_name');
         $user->position = $request->input('position');
         $user->role_id = 2;
         if ($request->has('phone')) {
             $user->phone = $request->input('phone');
         }
         if (!empty($request->file("image"))) {
             $generated_string = str_random(32);
             $file = $request->file("image")->store('uploads');
             $new_file = $generated_string . '.' . $request->file("image")->getClientOriginalExtension();
             Storage::move($file, 'uploads/' . $new_file);
             $img = Image::make($request->file('image'));
             $img->crop(200, 200);
             $img->save(storage_path('app/public/uploads/' . $new_file));
             $user->image = $new_file;
         }
         $user->username = $request->input('username');
         $user->email = $request->input('email');
         $user->password = Hash::make($request->input('pass'));
         $user->activation_token = str_random(32);
         $user->save();
         return redirect('/');
     } else {
         return view('site.auth.register');
     }
 }
Пример #22
0
 public function get($guid)
 {
     $asset = $this->assetsManager->assetOfGuid($guid);
     $path = $this->realPath($asset->path());
     $image = Image::make($path);
     return $image->response();
 }
Пример #23
0
 /**
  * Save message to Discussion page
  *
  * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
  */
 public function saveDiscussion()
 {
     $input = Input::all();
     $message = new Message();
     $message->body = $input['message'];
     $message->user_id = Auth::user()->id;
     // Storing image file, if it is attached
     if (Input::hasFile('image')) {
         $file = Input::file('image');
         if ($file->isValid()) {
             $filename = rand(111111, 999999) . '-' . $file->getClientOriginalName();
             $destination_path = 'uploads/projects/';
             $file->move($destination_path, $filename);
             $message->attachment = $filename;
             // Make a thumbnail picture
             $thumbnail = Image::make($destination_path . '/' . $filename);
             $thumbnail->resize(55, null, function ($constraint) {
                 $constraint->aspectRatio();
             });
             $thumbnail->save('uploads/projects/thumbnails/' . $filename);
         }
     }
     $message->save();
     return redirect('/projects/discussion');
 }
Пример #24
0
 public function makeCrop($id)
 {
     $image = $this->model($id);
     $source = Input::get('source', 'original');
     $variant = Input::get('variant', '');
     $revariantion = Input::get('revariation', 0);
     $settings = Input::get('settings', 0);
     $width = (int) ceil(Input::get('x2') - Input::get('x1'));
     $height = (int) ceil(Input::get('y2') - Input::get('y1'));
     $x = (int) ceil(Input::get('x1'));
     $y = (int) ceil(Input::get('y1'));
     $img = Img::make($image->filename($source));
     if ($width && $height) {
         $img->crop($width, $height, $x, $y);
     }
     $img->save($image->filename($variant));
     if (!$variant && $revariantion) {
         $image->setFileAttribute($image->filename());
         $image->save();
     }
     if ($settings) {
         $image->saveVariant($img, $variant);
     }
     $this->result['action'] = 'update';
     $this->result['make'] = 'crop';
     $this->result['data']['image'] = subdomainImage($image->src($variant) . '?r=' . rand());
     return $this->result();
 }
Пример #25
0
 public function testPictureWriterWritesTemplateImage()
 {
     $imageToSave = Image::make("./tests/FaceInserterTestData/result.png");
     PictureWriter::saveTemplateImage("filename.png", $imageToSave);
     $retrievedImage = PictureReader::readTemplate("filename.png");
     $this->assertInstanceOf(\Intervention\Image\Image::class, $retrievedImage);
 }
Пример #26
0
 public function src()
 {
     if ($this->isSkip) {
         return '';
     }
     $quality = config('yaro.cropp.cache_quality', 90);
     $cacheStorage = trim(config('yaro.cropp.cache_dir', 'storage/cropp'), '/');
     $methodsHash = md5(serialize($this->methods));
     $hash = md5($this->fileHash . $methodsHash . $quality);
     $source = '/' . $cacheStorage . '/' . $hash . $this->extension;
     if (is_readable(public_path($source))) {
         return $this->isAssetWrap ? asset($source) : $source;
     }
     try {
         $image = Image::make($this->source);
         foreach ($this->methods as $method) {
             call_user_func_array(array($image, $method['name']), $method['arguments']);
         }
         $res = $image->save(public_path($source), $quality);
         if (!$res) {
             throw new \RuntimeException('Unable to save image cache to [' . public_path($source) . ']');
         }
     } catch (\Exception $exception) {
         Log::error($exception);
         return '';
     }
     return $this->isAssetWrap ? asset($source) : $source;
 }
 protected function process(UploadedFile $image, array $imageDimensions = [])
 {
     $this->setHashedName($image);
     try {
         foreach ($imageDimensions as $imageDimension) {
             switch ($imageDimension) {
                 case 'large':
                     Image::make($image->getRealPath())->resize($this->largeImageWidth, $this->largeImageHeight)->save($this->largeImagePath . $this->hashedName);
                     break;
                 case 'medium':
                     Image::make($image->getRealPath())->resize($this->mediumImageWidth, $this->mediumImageHeight)->save($this->mediumImagePath . $this->hashedName);
                     break;
                 case 'thumbnail':
                     Image::make($image->getRealPath())->resize($this->thumbnailImageWidth, $this->thumbnailImageHeight)->save($this->thumbnailImagePath . $this->hashedName);
                     break;
                 default:
                     break;
             }
         }
     } catch (Exception $e) {
         dd($e->getMessage());
         $this->addError($e->getMessage());
         return false;
     }
     return $this;
 }
Пример #28
0
 /**
  * Save Image.
  */
 public function saveImages()
 {
     $imageFields = $this->getImageFields();
     $currentUploadDir = $this->getCurrentUploadDir();
     foreach ($imageFields as $imageFieldName => $options) {
         if (array_get($this->attributes, $imageFieldName) instanceof UploadedFile) {
             $file = Request::file($imageFieldName);
             $filename = $file->getClientOriginalName();
             $file->move($this->getThumbnailPath('original'), $filename);
             foreach ($options['thumbnails'] as $thumbnailName => $thumbnailOptions) {
                 $image = Image::make($this->getThumbnailPath('original') . $filename);
                 $resizeType = array_get($thumbnailOptions, 'type', 'crop');
                 switch ($resizeType) {
                     case 'crop':
                         $image->fit($thumbnailOptions['width'], $thumbnailOptions['height']);
                         break;
                     case 'resize':
                         $image->resize($thumbnailOptions['width'], $thumbnailOptions['height'], function ($constraint) {
                             $constraint->aspectRatio();
                         });
                         break;
                 }
                 $thumbnailPath = $this->getThumbnailPath($thumbnailName);
                 if (!File::isDirectory($thumbnailPath)) {
                     File::makeDirectory($thumbnailPath);
                 }
                 $image->save($thumbnailPath . $filename);
             }
             $this->attributes[$imageFieldName] = $filename;
         } elseif ($this->original) {
             $this->attributes[$imageFieldName] = $this->original[$imageFieldName];
         }
     }
 }
 /**
  * Store a newly created resource in storage.
  *
  * @param  CreatePostRequest $request
  * @return Response
  */
 public function store(CreatePostRequest $request, $category_id)
 {
     // save post
     $post = new Post();
     $post->fill($request->all());
     $post->category_id = $category_id;
     $post->save();
     // if have attachment, create the attachment record
     if ($request->hasFile('attachment')) {
         // generate filename based on UUID
         $filename = Uuid::generate();
         $extension = $request->file('attachment')->getClientOriginalExtension();
         $fullfilename = $filename . '.' . $extension;
         // store the file
         Image::make($request->file('attachment')->getRealPath())->resize(null, 640, function ($constraint) {
             $constraint->aspectRatio();
             $constraint->upsize();
         })->save(public_path() . '/attachments/' . $fullfilename);
         // attachment record
         $attachment = new Attachment();
         $attachment->post_id = $post->id;
         $attachment->original_filename = $request->file('attachment')->getClientOriginalName();
         $attachment->filename = $fullfilename;
         $attachment->mime = $request->file('attachment')->getMimeType();
         $attachment->save();
     }
     return redirect('category/' . $category_id . '/posts');
 }
Пример #30
0
 /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
 public function handle($request, Closure $next)
 {
     dd($request->all());
     $img = Image::make('C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg')->resize(300, 200);
     return $img->response('jpg');
     //        return $next($request);
 }