Ejemplo n.º 1
1
 /**
  * Perform image manipulations.
  * @param  string $source Source image binary data.
  * @param  array  $params The manipulation params.
  * @return string Manipulated image binary data.
  */
 public function run($source, array $params)
 {
     $image = $this->imageManager->make($source);
     foreach ($this->manipulators as $manipulator) {
         $manipulator->setParams($params);
         $image = $manipulator->run($image);
     }
     return $image->getEncoded();
 }
Ejemplo n.º 2
1
 public function processAvatar($path)
 {
     $manager = $this->imgManager->make($path);
     $manager->orientate();
     $manager->fit($this->width);
     $name = $this->getFileName();
     $manager->save($this->getUploadPath($name));
     return $name;
 }
 /**
  * Proccess image and write the text
  * Verify if the image needs to be downloaded
  * @param Request $request
  */
 public function store(Request $request)
 {
     $validator = Validator::make($request->all(), ['top' => 'max:' . Image::$maxCharCount, 'bottom' => 'required|max:' . Image::$maxCharCount, 'image' => 'required']);
     if ($validator->fails()) {
         $errors = '';
         foreach ($validator->errors()->all() as $error) {
             $errors .= "<br/>" . $error;
         }
         return response('Erro(s) de validação: ' . $errors, 500);
     }
     $image = $request->get('image');
     if (substr($image, -4) !== '.jpg') {
         $image .= '.jpg';
     }
     $imageObject = $this->manager->make(public_path() . '/images/' . $image);
     $token = Image::generateImageToken();
     $path = public_path() . '/images/' . $token . '.jpg';
     $imageObject = $this->write($imageObject, $request->get('bottom'));
     if ($request->get('top')) {
         $imageObject = $this->write($imageObject, $request->get('top'), 'top');
     }
     $result = $imageObject->save($path);
     if ($result) {
         return ['message' => 'Your image was saved successfully', 'token' => $token, 'image_src' => asset('images/' . $token . '.jpg')];
     }
 }
Ejemplo n.º 4
0
 public function resize($image)
 {
     $width = config('medias.max_size.width');
     $height = config('medias.max_size.height');
     // this orientate method needs to be called because sometimes
     // images uploaded came rotated, but need to be ajusted
     $img = $this->image->make(Storage::disk(config('medias.disk'))->get($image))->orientate();
     if ($img->width() <= $width && $img->height() <= $height) {
         return;
     }
     if ($img->width() > $width && $img->height() > $height) {
         $img->resize($width, $height, function ($constraint) {
             $constraint->aspectRatio();
         });
         Storage::disk(config('medias.disk'))->put($image, $img->stream());
         return;
     }
     if ($img->width() > $width) {
         $height = null;
     } elseif ($img->height() > $height) {
         $width = null;
     }
     $img->resize($width, $height, function ($constraint) {
         $constraint->aspectRatio();
     });
     Storage::disk(config('medias.disk'))->put($image, $img->stream());
 }
Ejemplo n.º 5
0
 /**
  * {@inheritdoc}
  */
 public function execute(CommandParams $params, CommandExecutionContext $executionContext)
 {
     $fileName = $params->getFirstArgument();
     if (!$executionContext->hasFileInWorkingDirectory($fileName)) {
         throw new ExecutionFailedException("File '{$fileName}' does not exist.");
     }
     $img = $this->imageManager->make($executionContext->getPathOfFileInWorkingDirectory($fileName));
     if (!$params->hasSecondArgument()) {
         return $this->returnImage($img, $params);
     }
     list($width, $height) = $this->parseDimension($params->getSecondArgument());
     switch ($params->getThirdArgument()) {
         case 'stretch':
             $img->resize($width, $height);
             break;
         case 'fit':
             $img->fit($width, $height);
             break;
         case 'crop':
             $x = $this->filterIntOrNullArgument($params->getArgument(3));
             $y = $this->filterIntOrNullArgument($params->getArgument(4));
             $img->crop($width, $height, $x, $y);
             break;
         default:
             $img->resize($width, $height, function (Constraint $constraint) {
                 $constraint->aspectRatio();
             });
             break;
     }
     return $this->returnImage($img, $params);
 }
Ejemplo n.º 6
0
 /**
  * {@inheritdoc}
  */
 public function apply($source, $options)
 {
     $options = $this->parseOptions($options);
     $image = $this->imageManager->make($source);
     $image->crop($options['width'], $options['height'], $options['x'], $options['y']);
     return $image->encode($image->mime())->getEncoded();
 }
Ejemplo n.º 7
0
 /**
  * Perform image manipulations.
  * @param  Request $request The request object.
  * @param  string  $source  Source image binary data.
  * @return string  Manipulated image binary data.
  */
 public function run(Request $request, $source)
 {
     $image = $this->imageManager->make($source);
     foreach ($this->manipulators as $manipulator) {
         $image = $manipulator->run($request, $image);
     }
     return $image->getEncoded();
 }
Ejemplo n.º 8
0
 public function apply($source, $options)
 {
     $options = $this->parseOptions($options);
     $image = $this->imageManager->make($source);
     $image->fit($options['width'], $options['height'], function ($constraint) {
         $constraint->upsize();
     }, $options['position']);
     return $image->encode($image->mime())->getEncoded();
 }
Ejemplo n.º 9
0
 /**
  * Make an image object from uploaded image
  *
  * @param string $image
  * @return \Intervention\Image\ImageManager|null
  */
 public function makeImage($image = '')
 {
     try {
         //Make image object and return
         return $this->image->make($image);
     } catch (Exception $e) {
         //Unexpected error
         return null;
     }
 }
Ejemplo n.º 10
0
 /**
  * Make and save image to filesystem from base64 encoded string.
  * 
  * @param  string  $string
  * @param  string  $path
  * 
  * @return Intervention\Image\Image
  */
 public function saveFromString($string, $path, $aspectRatio = false, $width = 320, $height = 200)
 {
     $string = preg_replace('/data:image\\/.+?;base64,/', '', $string);
     $img = imagecreatefromstring(base64_decode($string));
     if ($aspectRatio) {
         return $this->manager->make($img)->resize($width, $height, function ($contstraint) {
             $contstraint->aspectRatio();
         })->save($path);
     } else {
         return $this->manager->make($img)->resize($width, $height)->save($path);
     }
 }
Ejemplo n.º 11
0
 /**
  * Run the named template against the image
  * @param  String $template          The template to run
  * @return Intervention\Image\Image  The processed image
  */
 public function process(TemplateInterface $template)
 {
     // Create a new intervention image object
     $image = $this->imageManager->make($this->image);
     $image = $template->process($image);
     // Encode the image if it hasn't
     // been encoded in the template.
     if (!$image->isEncoded()) {
         $image->encode();
     }
     return $image;
 }
Ejemplo n.º 12
0
 private function validateFile(BackdropUploadStrategy $strategy, string $tmpFile)
 {
     if (filesize($tmpFile) > $strategy->getMaxFileSize()) {
         throw new TooBigFileException(sprintf('File is too big'));
     }
     $image = $this->imageManager->make($tmpFile);
     if ($image->getWidth() < $strategy->getMinImageWidth() || $image->getHeight() < $strategy->getMinImageHeight()) {
         throw new InvalidSizeException('Image is too small');
     }
     if ($image->getWidth() > $strategy->getMaxImageWidth() || $image->getHeight() > $strategy->getMaxImageHeight()) {
         throw new InvalidSizeException('Image is too big');
     }
 }
Ejemplo n.º 13
0
 public function thumb($width = null, $height = null)
 {
     $manager = new ImageManager();
     $thumb = new PdfThumbnail($this->asset);
     if ($width && $height) {
         $image = $manager->cache(function ($manager) use($width, $height, $thumb) {
             return $manager->make($thumb->getAndMakeFilename())->fit($width, $height);
         });
     } else {
         $image = $manager->make($thumb->getAndMakeFilename())->encode();
     }
     return $this->response->header('content-type', 'image/png')->setContent($image);
 }
Ejemplo n.º 14
0
 public function view($width = null, $height = null)
 {
     $filename = $this->asset->exists() ? $this->asset->getFilename() : __DIR__ . '/../../../../vendor/boomcms/boom-core/img/placeholder.png';
     if ($width || $height) {
         $image = $this->manager->cache(function ($manager) use($width, $height, $filename) {
             return $manager->make($filename)->resize($width != 0 ? $width : null, $height != 0 ? $height : null, function ($constraint) {
                 $constraint->aspectRatio();
                 $constraint->upsize();
             })->encode($this->encoding);
         });
     } else {
         $image = $this->manager->make($this->asset->getFilename())->encode();
     }
     return $this->response->header('content-type', $this->asset->getMimetype())->setContent($image);
 }
Ejemplo n.º 15
0
 /**
  * Performs image processing
  *
  * @param ModelContract $model
  * @param array         $styleGuides
  * @param string        $path
  */
 public function process(ModelContract &$model, array $styleGuides, $path)
 {
     // load styles
     $styles = $this->getStyles($model, $styleGuides);
     $originalClosure = array_get($styles, 'original', null);
     // get Image object
     $image = $this->imageManager->make($model->getSourceFile()->getFileInfo());
     // apply original style
     $original = $this->processStyle($model, $image, 'original', $originalClosure);
     array_forget($styles, 'original');
     // apply styles
     foreach ($styles as $styleName => $closure) {
         $this->processStyle($model, $original, $styleName, $closure);
     }
 }
Ejemplo n.º 16
0
 /**
  * {@inheritdoc}
  */
 public function data(ServerRequestInterface $request, Document $document)
 {
     $this->assertAdmin($request->getAttribute('actor'));
     $file = array_get($request->getUploadedFiles(), 'favicon');
     $tmpFile = tempnam($this->app->storagePath() . '/tmp', 'favicon');
     $file->moveTo($tmpFile);
     $extension = pathinfo($file->getClientFilename(), PATHINFO_EXTENSION);
     if ($extension !== 'ico') {
         $manager = new ImageManager();
         $encodedImage = $manager->make($tmpFile)->resize(64, 64, function ($constraint) {
             $constraint->aspectRatio();
             $constraint->upsize();
         })->encode('png');
         file_put_contents($tmpFile, $encodedImage);
         $extension = 'png';
     }
     $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => new Filesystem(new Local($this->app->publicPath() . '/assets'))]);
     if (($path = $this->settings->get('favicon_path')) && $mount->has($file = "target://{$path}")) {
         $mount->delete($file);
     }
     $uploadName = 'favicon-' . Str::lower(Str::quickRandom(8)) . '.' . $extension;
     $mount->move('source://' . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}");
     $this->settings->set('favicon_path', $uploadName);
     return parent::data($request, $document);
 }
Ejemplo n.º 17
0
 public function image($filename)
 {
     $mediaArchivePath = str_replace('\\', '\\\\', storage_path('app/media-archive/' . Auth::user()->id . '/'));
     // return Storage::disk('local')->get('media-archive/'. Auth::user()->id  .  '/' . $filename );
     $manager = new ImageManager();
     return $manager->make($mediaArchivePath . $filename)->response();
 }
Ejemplo n.º 18
0
 /**
  * @param UploadAvatar $command
  * @return \Flarum\Core\Users\User
  * @throws \Flarum\Core\Exceptions\PermissionDeniedException
  */
 public function handle(UploadAvatar $command)
 {
     $actor = $command->actor;
     $user = $this->users->findOrFail($command->userId);
     // Make sure the current user is allowed to edit the user profile.
     // This will let admins and the user themselves pass through, and
     // throw an exception otherwise.
     if ($actor->id !== $user->id) {
         $user->assertCan($actor, 'edit');
     }
     $tmpFile = tempnam(sys_get_temp_dir(), 'avatar');
     $command->file->moveTo($tmpFile);
     $manager = new ImageManager();
     $manager->make($tmpFile)->fit(100, 100)->save();
     event(new AvatarWillBeSaved($user, $actor, $tmpFile));
     $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => $this->uploadDir]);
     if ($user->avatar_path && $mount->has($file = "target://{$user->avatar_path}")) {
         $mount->delete($file);
     }
     $uploadName = Str::lower(Str::quickRandom()) . '.jpg';
     $user->changeAvatarPath($uploadName);
     $mount->move("source://" . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}");
     $user->save();
     $this->dispatchEventsFor($user);
     return $user;
 }
Ejemplo n.º 19
0
 /**
  * Create captcha image
  *
  * @param string $config
  * @return ImageManager->response
  */
 public function create($config = 'default')
 {
     $this->backgrounds = $this->files->files(__DIR__ . '/../assets/backgrounds');
     $this->fonts = $this->files->files(__DIR__ . '/../assets/fonts');
     $this->fonts = array_values($this->fonts);
     //reset fonts array index
     $this->configure($config);
     $this->text = $this->generate();
     session_start();
     $_SESSION['text'] = $this->text;
     $this->canvas = $this->imageManager->canvas($this->width, $this->height, $this->bgColor);
     if ($this->bgImage) {
         $this->image = $this->imageManager->make($this->background())->resize($this->width, $this->height);
         $this->canvas->insert($this->image);
     } else {
         $this->image = $this->canvas;
     }
     if ($this->contrast != 0) {
         $this->image->contrast($this->contrast);
     }
     $this->text();
     $this->lines();
     if ($this->sharpen) {
         $this->image->sharpen($this->sharpen);
     }
     if ($this->invert) {
         $this->image->invert($this->invert);
     }
     if ($this->blur) {
         $this->image->blur($this->blur);
     }
     return $this->image->response('png', $this->quality);
 }
Ejemplo n.º 20
0
 public function thumbAction(Request $request, Application $app)
 {
     $source = $request->get('src', false);
     $width = $request->get('width', 250);
     // Do requested thumbnail in correct format already exists ?
     if ($app['flysystems']['thumbs']->has($width . "/" . $source)) {
         return $app->redirect($request->getBasePath() . '/thumbs/' . $width . '/' . $source, 301);
     }
     // Do requested file exists ?
     if (!$source || !$app['flysystems']['local']->has($source)) {
         return new Response("Source file not found.", 404);
     }
     try {
         $contents = $app['flysystems']['local']->read($source);
         $imageManager = new ImageManager();
         $image = $imageManager->make($contents);
         $image->resize($width, null, function ($constraint) {
             $constraint->aspectRatio();
         });
         $info = $app['flysystems']['local']->getWithMetadata($source, ['mimetype']);
         $image->encode($info['mimetype']);
         $app['flysystems']['thumbs']->put($width . "/" . $source, $image);
         return $app->redirect($request->getBasePath() . '/thumbs/' . $width . '/' . $source, 301);
     } catch (\Exception $e) {
         return new Response("Erreur !", 500);
     }
     // Should not happen, everything failed. Display not found image :(
     return $app->redirect($request->getBasePath() . '/assets/img/' . $width . '_not-found.png', 302);
 }
Ejemplo n.º 21
0
 /**
  * @param \Onyx\Destiny\Objects\Hash $hash
  * @param string $index
  * @return bool
  */
 public static function saveImageLocally($hash, $index = 'extra')
 {
     // BUG: Can't use variable object indexes implicitly
     // $hash->{$index} should work but doesn't
     // map the index explicitly with the attributes dumped into $bug
     $bug = $hash->getAttributes();
     $url = "https://bungie.net" . $bug[$index];
     $name = $index != 'extra' ? '_bg' : null;
     $name = $hash->hash . $name;
     // Make sure we aren't trying to save something that isn't an image
     // We only need this check because we cheat and store all hash related objects
     // in one table. This means we have crazy cheats to get things done.
     if (strlen($bug[$index]) < 5) {
         return false;
     }
     $location = public_path('uploads/thumbs/');
     $filename = $name . "." . pathinfo($bug[$index], PATHINFO_EXTENSION);
     if (File::isFile($location . $filename)) {
         return true;
     }
     if ($hash instanceof Hash) {
         $manager = new ImageManager();
         try {
             $img = $manager->make($url);
             $img->save($location . $filename);
         } catch (NotReadableException $e) {
             Log::error('Could not download: ' . $url);
         }
         return true;
     }
 }
Ejemplo n.º 22
0
 /**
  * Create the database entry for an image.
  *
  * @param File $image
  * @param array $attributes
  * @return Image
  */
 protected function createImageRecord(File $image, array $attributes = [])
 {
     // Obtain image metadata and save the record to the database.
     $imageData = new ImageData($image, $this->intervention->make($image->getRealPath()));
     $attributes = array_merge($attributes, ['width' => $imageData->getWidth(), 'height' => $imageData->getHeight(), 'average_color' => $imageData->getAveragePixelColor(), 'mime_type' => $image->getMimeType()]);
     return $this->imageRepository->create($attributes);
 }
Ejemplo n.º 23
0
 /**
  * Resize image (save to disk)
  *
  * @param string $type Type of resize: fit, crop and resize
  * @param integer $quality Thumb quality
  * @return mixed String to thumb file or false
  */
 public function save($type = 'resize', $quality = 80)
 {
     $pathInfo = pathinfo($this->imagePath);
     $fileName = $pathInfo['basename'];
     if ($this->fileName) {
         $fileName = $this->fileName;
     }
     $destPath = sprintf('%s/%s', trim($this->destPath, '/'), $fileName);
     $thumbImage = $this->imageManager->make($this->imagePath);
     switch ($type) {
         case 'fit':
             $thumbImage->fit($this->thumbWidth, $this->thumbHeight, null, $this->fitPosition);
             break;
         case 'crop':
             $thumbImage->crop($this->thumbWidth, $this->thumbHeight, $this->xCoordinate, $this->yCoordinate);
             break;
         default:
             $thumbImage->resize($this->thumbWidth, $this->thumbHeight);
     }
     try {
         $thumbImage->save($destPath, $quality);
     } catch (\Exception $e) {
         \Log::error($e->getMessage());
         return false;
     }
     return $destPath;
 }
Ejemplo n.º 24
0
 /**
  * Perform image manipulations.
  * @param  string $url Source URL
  * @param  array $params The manipulation params.
  * @throws NotReadableException if the provided file can not be read
  * @throws ImageTooLargeException if the provided image is too large for processing.
  * @throws RequestException for errors that occur during a transfer or during the on_headers event
  * @return \Intervention\Image\Image
  */
 public function run($url, array $params)
 {
     $tmpFileName = $this->client->get($url);
     try {
         $image = $this->imageManager->make($tmpFileName);
     } catch (NotReadableException $e) {
         @unlink($tmpFileName);
         trigger_error($e->getMessage() . ' URL: ' . $url, E_USER_WARNING);
         throw $e;
     }
     unlink($tmpFileName);
     foreach ($this->manipulators as $manipulator) {
         $manipulator->setParams($params);
         try {
             $image = $manipulator->run($image);
         } catch (ImageTooLargeException $e) {
             trigger_error($e->getMessage() . ' URL: ' . $url, E_USER_WARNING);
             throw $e;
         } catch (RuntimeException $e) {
             trigger_error($e->getMessage() . ' URL: ' . $url . ' Params: ' . implode(', ', $params), E_USER_WARNING);
             throw $e;
         }
     }
     return $image;
 }
 /**
  * @param AttachableModel $model
  * @return boolean
  * @throws OnlyImagesException
  */
 public function store(AttachableModel $model)
 {
     $this->setDisk($model);
     try {
         $image = $this->imageManager->make($model->getUploadedFile()->getFileInfo());
         $this->processTemplates($model, $image);
     } catch (NotReadableException $e) {
         //Intervention Image says its not an image, ok, lets process as a File so
         //wait, unless $only_images propriety is true
         if ($model->onlyImages) {
             throw new OnlyImagesException();
         }
         return app(FileProcessorContract::class)->store($model);
     }
     return true;
 }
Ejemplo n.º 26
0
 public function postCrop()
 {
     $form_data = Input::all();
     $image_url = $form_data['imgUrl'];
     // resized sizes
     $imgW = $form_data['imgW'];
     $imgH = $form_data['imgH'];
     // offsets
     $imgY1 = $form_data['imgY1'];
     $imgX1 = $form_data['imgX1'];
     // crop box
     $cropW = $form_data['width'];
     $cropH = $form_data['height'];
     // rotation angle
     $angle = $form_data['rotation'];
     $filename_array = explode('/', $image_url);
     $filename = $filename_array[sizeof($filename_array) - 1];
     $manager = new ImageManager();
     $image = $manager->make($image_url);
     $image->resize($imgW, $imgH)->rotate(-$angle)->crop($cropW, $cropH, $imgX1, $imgY1)->save(env('UPLOAD_PATH') . 'cropped-' . $filename);
     if (!$image) {
         return Response::json(['status' => 'error', 'message' => 'Server error while uploading'], 200);
     }
     return Response::json(['status' => 'success', 'url' => env('URL') . 'uploads/cropped-' . $filename], 200);
 }
Ejemplo n.º 27
0
 /**
  * @param UploadAvatar $command
  * @return \Flarum\Core\User
  * @throws \Flarum\Core\Exception\PermissionDeniedException
  */
 public function handle(UploadAvatar $command)
 {
     $actor = $command->actor;
     $user = $this->users->findOrFail($command->userId);
     if ($actor->id !== $user->id) {
         $this->assertCan($actor, 'edit', $user);
     }
     $tmpFile = tempnam($this->app->storagePath() . '/tmp', 'avatar');
     $command->file->moveTo($tmpFile);
     $file = new UploadedFile($tmpFile, $command->file->getClientFilename(), $command->file->getClientMediaType(), $command->file->getSize(), $command->file->getError(), true);
     $this->validator->assertValid(['avatar' => $file]);
     $manager = new ImageManager();
     $manager->make($tmpFile)->fit(100, 100)->save();
     $this->events->fire(new AvatarWillBeSaved($user, $actor, $tmpFile));
     $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => $this->uploadDir]);
     if ($user->avatar_path && $mount->has($file = "target://{$user->avatar_path}")) {
         $mount->delete($file);
     }
     $uploadName = Str::lower(Str::quickRandom()) . '.jpg';
     $user->changeAvatarPath($uploadName);
     $mount->move("source://" . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}");
     $user->save();
     $this->dispatchEventsFor($user, $actor);
     return $user;
 }
Ejemplo n.º 28
0
 public function generate()
 {
     $image_manager = new ImageManager();
     $this->image = $image_manager->make($this->source_path);
     if ($this->width() && $this->height()) {
         $this->image->fit($this->width(), $this->height(), function ($constraint) {
             $constraint->aspectRatio();
             $constraint->upsize();
         });
     } else {
         if ($this->width() || $this->height()) {
             $this->image->resize($this->width(), $this->height(), function ($constraint) {
                 $constraint->aspectRatio();
                 $constraint->upsize();
             });
         }
     }
     if ($this->cropWidth() || $this->cropHeight()) {
         $cw = $this->cropWidth() ?: $this->width() ?: $this->image->width();
         $ch = $this->cropHeight() ?: $this->height() ?: $this->image->height();
         if (!is_null($this->cropX()) || !is_null($this->cropY())) {
             $cx = is_null($this->cropX()) ? $cw / 2 - $this->image->width() / 2 : $this->cropX();
             $cy = is_null($this->cropY()) ? $ch / 2 - $this->image->height() / 2 : $this->cropY();
             $this->image->crop($cw, $ch, round($cx), round($cy));
         } else {
             $this->image->resizeCanvas($cw, $ch, 'center', false, 'ffffff');
         }
     }
     if ($this->rotation) {
         $this->image->rotate($this->rotation);
     }
     $this->image->save($this->dest_path);
     return $this;
 }
Ejemplo n.º 29
0
 /**
  * Create an array of resized images
  *
  * @param  string $image
  * @param  int    $id
  */
 protected function createImageSet($path, $file)
 {
     $manager = new ImageManager(['driver' => 'imagick']);
     $image = $manager->make($path . $file);
     $image->resize(768, null, function ($constraint) {
         $constraint->aspectRatio();
     })->sharpen(6)->save($path . '768_' . $file);
     $image->resize(600, null, function ($constraint) {
         $constraint->aspectRatio();
     })->sharpen(6)->save($path . '600_' . $file);
     $image->resize(523, null, function ($constraint) {
         $constraint->aspectRatio();
     })->sharpen(6)->save($path . '523_' . $file);
     $image->resize(480, null, function ($constraint) {
         $constraint->aspectRatio();
     })->sharpen(6)->save($path . '480_' . $file);
     $image->resize(423, null, function ($constraint) {
         $constraint->aspectRatio();
     })->sharpen(6)->save($path . '423_' . $file);
     $image->resize(313, null, function ($constraint) {
         $constraint->aspectRatio();
     })->sharpen(6)->save($path . '313_' . $file);
     $image->destroy();
     unlink($path . $file);
 }
Ejemplo n.º 30
0
 /**
  * @param UploadAvatar $command
  * @return \Flarum\Core\User
  * @throws \Flarum\Core\Exception\PermissionDeniedException
  */
 public function handle(UploadAvatar $command)
 {
     $actor = $command->actor;
     $user = $this->users->findOrFail($command->userId);
     if ($actor->id !== $user->id) {
         $this->assertCan($actor, 'edit', $user);
     }
     $tmpFile = tempnam($this->app->storagePath() . '/tmp', 'avatar');
     $command->file->moveTo($tmpFile);
     try {
         $file = new UploadedFile($tmpFile, $command->file->getClientFilename(), $command->file->getClientMediaType(), $command->file->getSize(), $command->file->getError(), true);
         $this->validator->assertValid(['avatar' => $file]);
         $manager = new ImageManager();
         // Explicitly tell Intervention to encode the image as JSON (instead of having to guess from the extension)
         $encodedImage = $manager->make($tmpFile)->fit(100, 100)->encode('jpg', 100);
         file_put_contents($tmpFile, $encodedImage);
         $this->events->fire(new AvatarWillBeSaved($user, $actor, $tmpFile));
         $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => $this->uploadDir]);
         if ($user->avatar_path && $mount->has($file = "target://{$user->avatar_path}")) {
             $mount->delete($file);
         }
         $uploadName = Str::lower(Str::quickRandom()) . '.jpg';
         $user->changeAvatarPath($uploadName);
         $mount->move('source://' . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}");
         $user->save();
         $this->dispatchEventsFor($user, $actor);
         return $user;
     } catch (Exception $e) {
         @unlink($tmpFile);
         throw $e;
     }
 }