public static function upload(UploadedFile $file, $user) { $userId = $user; if ($user instanceof User) { $userId = $user->id; } $hash = md5_file($file->getPathname()); $image = Image::whereHash($hash)->whereUploadedBy($userId)->first(); if ($image) { return $image; } $image = new Image(); try { $image->uploaded_by = $userId; $image->size = $file->getSize(); $image->filename = $file->getClientOriginalName(); $image->extension = $file->getClientOriginalExtension(); $image->mime = $file->getMimeType(); $image->hash = $hash; $image->save(); $image->ensureDirectoryExists(); foreach (self::$ImageTypes as $coverType) { if ($coverType['id'] === self::ORIGINAL && $image->mime === 'image/jpeg') { $command = 'cp ' . $file->getPathname() . ' ' . $image->getFile($coverType['id']); } else { // ImageMagick options reference: http://www.imagemagick.org/script/command-line-options.php $command = 'convert 2>&1 "' . $file->getPathname() . '" -background white -alpha remove -alpha off -strip'; if ($image->mime === 'image/jpeg') { $command .= ' -quality 100 -format jpeg'; } else { $command .= ' -quality 95 -format png'; } if (isset($coverType['width']) && isset($coverType['height'])) { $command .= " -thumbnail {$coverType['width']}x{$coverType['height']}^ -gravity center -extent {$coverType['width']}x{$coverType['height']}"; } $command .= ' "' . $image->getFile($coverType['id']) . '"'; } External::execute($command); chmod($image->getFile($coverType['id']), 0644); } return $image; } catch (\Exception $e) { $image->delete(); throw $e; } }