logoSourcePath(); $disk = Storage::disk('public'); if ($source === null || ! $disk->exists($source)) { throw ValidationException::withMessages(['logo' => __('Upload a logo before cropping it.')]); } $absolute = $disk->path($source); $size = @getimagesize($absolute); if ($size === false) { throw ValidationException::withMessages(['logo' => __('This logo cannot be cropped. Upload it again.')]); } [$width, $height] = $size; if ($width * $height > self::MAX_PIXELS) { throw ValidationException::withMessages(['logo' => __('This image is too large to crop. Upload a smaller one.')]); } if ($box['x'] + $box['width'] > $width || $box['y'] + $box['height'] > $height) { throw ValidationException::withMessages(['width' => __('The crop must stay inside the image.')]); } // The whole picture is the upload itself: no second copy of it. if ($box['x'] === 0 && $box['y'] === 0 && $box['width'] === $width && $box['height'] === $height) { $this->restore($setting); return; } // Same extension as the upload, which took it from the content // when it was stored (see BrandingController::storeImage). $cropped = 'branding/'.Str::uuid().'.'.pathinfo($source, PATHINFO_EXTENSION); (new SimpleImage($absolute)) ->crop($box['x'], $box['y'], $box['x'] + $box['width'], $box['y'] + $box['height']) ->toFile($disk->path($cropped), $size['mime']); $previous = $setting->logoIsCropped() ? $setting->logo_path : null; $setting->update([ 'logo_original_path' => $source, 'logo_path' => $cropped, 'logo_crop' => $box, ]); if ($previous !== null) { $disk->delete($previous); } } public function restore(BrandingSetting $setting): void { if (! $setting->logoIsCropped()) { return; } $cropped = $setting->logo_path; $setting->update([ 'logo_path' => $setting->logo_original_path, 'logo_original_path' => null, 'logo_crop' => null, ]); if ($cropped !== null) { Storage::disk('public')->delete($cropped); } } /** * Every file the logo occupies: the one shown, and the upload behind it. * * @return list */ public function files(BrandingSetting $setting): array { return array_values(array_filter([$setting->logo_path, $setting->logo_original_path])); } }