/** * @param $original * @param $output * @return ImageFactory * @throws ImageGenerationException */ private function initaliseImageFactory($original, $output) { if (file_exists($original)) { $path_parts = pathinfo($output); if (!is_dir($path_parts['dirname'])) { mkdir($path_parts['dirname'], 0777, true); } $imageFactory = ImageFactory::make($original); return $imageFactory; } throw new ImageGenerationException(); }
/** * Save image in filesystem and db and return the image url. * * @param Upload $image * @param boolean $useOriginalName * @return Image */ public function saveImage(Upload $image, $useOriginalName = false) { $path = $this->makePath($image, $useOriginalName); $this->imagine->make($image->getRealPath())->save($path, 80); //save relative path in database instead of absolute so the site //won't get messed up if user changes domains. $relative = str_replace(public_path() . '/', '', $path); $this->model->firstOrNew(array('local' => $relative, 'type' => 'upload'))->save(); return $this->byPath($relative); }
/** * Resize an image * * @param string $image * @param integer $width * @param integer $height * * @return Image */ public function resizeImage($image, $width, $height) { $image = Image::make('public/' . $image); $image->resize($width, $height); $image->save(); return $image; }
/** * @param $path * @param $width * @param $height * @return Illuminate\Http\Response */ public function image($width, $height, $path) { $file = storage_path($path); if (!file_exists($file)) { dd($file); App::abort(404); } return Image::make($file)->resize($width, $height); }
/** * Make a new image * @param MediaPath $path * @param string $filename * @param string null $thumbnail */ private function makeNew(MediaPath $path, $filename, $thumbnail) { $image = $this->image->make($path->getUrl()); foreach ($this->manager->find($thumbnail) as $manipulation => $options) { $image = $this->imageFactory->make($manipulation)->handle($image, $options); } $image = $image->stream(pathinfo($path, PATHINFO_EXTENSION)); $this->writeImage($filename, $image); }
/** * Make a new image * @param string $path * @param string $filename * @param string null $thumbnail */ private function makeNew($path, $filename, $thumbnail) { $image = $this->image->make(public_path() . $path); foreach ($this->manager->find($thumbnail) as $manipulation => $options) { $image = $this->imageFactory->make($manipulation)->handle($image, $options); } $image = $image->encode(pathinfo($path, PATHINFO_EXTENSION)); $this->writeImage($filename, $image); }
public function postUpload() { if (Input::hasFile('upload')) { $destinationPath = public_path() . '/assets/ckeditor/upload/'; $file = Input::file('upload'); $fileName = Str::random(4) . '.' . $file->getClientOriginalExtension(); Image::make($file->getRealPath())->save($destinationPath . 'original/' . $fileName)->grab('100', '100')->save($destinationPath . 'thumbnail/' . $fileName)->resize('280', '255', true)->save($destinationPath . 'resize/' . $fileName)->destroy(); return 'success'; } return App::abort(403, 'Unauthorized action.'); }
public function redactor__upload() { if (!Auth::getCurrentMember()) { exit("Invalid Request"); } $path = Request::get('path'); $is_image = Request::get('is_image'); if (isset($path)) { $dir = Path::tidy(ltrim($path, '/') . '/'); if (isset($_POST['subfolder'])) { $dir .= $_POST['subfolder'] . '/'; } Folder::make($dir); $file_type = strtolower($_FILES['file']['type']); $file_info = pathinfo($_FILES['file']['name']); // pull out the filename bits $filename = $file_info['filename']; $ext = $file_info['extension']; // build filename $file = $dir . $filename . '.' . $ext; // check for dupes if (File::exists($file)) { $file = BASE_PATH . '/' . $dir . $filename . '-' . date('YmdHis') . '.' . $ext; } if (!Folder::isWritable($dir)) { Log::error('Upload failed. Directory "' . $dir . '" is not writable.', 'redactor'); echo json_encode(array('error' => "Redactor: Upload directory not writable.")); die; } if ($is_image && ($_FILES['file']['type'] == 'image/png' || $_FILES['file']['type'] == 'image/jpg' || $_FILES['file']['type'] == 'image/gif' || $_FILES['file']['type'] == 'image/jpeg')) { if (Request::get('resize', false)) { $image = Image::make($_FILES['file']['tmp_name']); $width = Request::get('width', null); $height = Request::get('height', null); $ratio = Request::get('ratio', true); $upsize = Request::get('upsize', false); $quality = Request::get('quality', '75'); $image->resize($width, $height, $ratio, $upsize)->save($file, $quality); } else { move_uploaded_file($_FILES['file']['tmp_name'], $file); } } else { move_uploaded_file($_FILES['file']['tmp_name'], $file); } $return = array('filelink' => Path::toAsset($file)); echo stripslashes(json_encode($return)); } else { echo json_encode(array('error' => "Redactor: Upload directory not set.")); } }
/** * Process an uploaded file and store it in a web-accessible place. * * @param UploadedFile $file * @param $publishFilename */ public function process(UploadedFile $file, $publishFilename) { // Temporary filename to work with. $fileName = uniqid() . '_' . $file->getClientOriginalName(); $file->move($this->publishDir, $fileName); $speakerPhoto = Image::make($this->publishDir . '/' . $fileName); if ($speakerPhoto->height > $speakerPhoto->width) { $speakerPhoto->resize($this->size, null, true); } else { $speakerPhoto->resize(null, $this->size, true); } $speakerPhoto->crop($this->size, $this->size); if ($speakerPhoto->save($this->publishDir . '/' . $publishFilename)) { unlink($this->publishDir . '/' . $fileName); } }
/** * Function that saves a new company * @param array $data, string $logotype * @return Orcamentos\Model\Company $company */ public function save($data, $logotype) { $data = json_decode($data); if (!isset($data->name) || !isset($data->telephone)) { throw new Exception("Invalid Parameters", 1); } $company = $this->getCompany($data); $taxes = 6; if (isset($data->taxes)) { $taxes = $data->taxes; } if (!isset($data->responsable)) { $data->responsable = null; } $company->setName($data->name); $company->setResponsable($data->responsable); $company->setTaxes($taxes); if (isset($data->city)) { $company->setCity($data->city); } if (isset($data->site)) { $company->setSite($data->site); } if (isset($data->telephone)) { $company->setTelephone($data->telephone); } if (isset($data->email)) { $company->setEmail($data->email); } if (isset($logotype)) { $originalName = $logotype->getClientOriginalName(); $components = explode('.', $originalName); $fileName = md5(time()) . '.' . end($components); $file = Image::make($logotype->getPathName())->grab(80); $file->save("public/img/logotypes/" . $fileName); $company->setLogotype($fileName); } try { $this->em->persist($company); $this->em->flush(); return $company; } catch (Exception $e) { echo $e->getMessage(); } }
/** * Function that saves a new client * @param array $data, string $logotype * @return Orcamentos\Model\Client $client */ public function save($data, $logotype = null) { $data = json_decode($data); if (!isset($data->name) || !isset($data->corporateName) || !isset($data->responsable) || !isset($data->email) || !isset($data->companyId)) { throw new Exception("Parâmetros inválidos", 1); } $client = null; if (isset($data->id)) { $client = $this->em->getRepository("Orcamentos\\Model\\Client")->find($data->id); } if (!$client) { $client = new ClientModel(); } $client->setName($data->name); $client->setCorporateName($data->corporateName); $client->setResponsable($data->responsable); $client->setEmail($data->email); if (isset($data->cnpj)) { $client->setCnpj($data->cnpj); } if (isset($data->telephone)) { $client->setTelephone($data->telephone); } $company = $this->em->getRepository('Orcamentos\\Model\\Company')->find($data->companyId); if (!isset($company)) { throw new Exception("Empresa não encontrada", 1); } $client->setCompany($company); if (isset($logotype)) { $originalName = $logotype->getClientOriginalName(); $components = explode('.', $originalName); $fileName = md5(time()) . '.' . end($components); $file = Image::make($logotype->getPathName())->grab(80); $file->save("public/img/logotypes/" . $fileName); $client->setLogotype($fileName); } try { $this->em->persist($client); $this->em->flush(); return $client; } catch (Exception $e) { echo $e->getMessage(); } }
/** * Post an image from the admin * * @return Json */ public function postImage() { $file = Input::file('file'); $imageDir = Config::get('wardrobe.image_dir', 'img'); $destinationPath = public_path() . "/" . $imageDir . "/"; $filename = $file->getClientOriginalName(); $resizeEnabled = Config::get('wardrobe.image_resize.enabled', false); if ($resizeEnabled) { $resizeWidth = Config::get('wardrobe.image_resize.width'); $resizeHeight = Config::get('wardrobe.image_resize.height'); $image = Image::make($file->getRealPath())->resize($resizeWidth, $resizeHeight, true); $image->save($destinationPath . $filename); } else { $file->move($destinationPath, $filename); } if (File::exists($destinationPath . $filename)) { return Response::json(array('filename' => "/{$imageDir}/" . $filename, 'filelink' => "/{$imageDir}/" . $filename)); } return Response::json(array('error' => 'Upload failed. Please ensure your public/' . $imageDir . ' directory is writable.')); }
/** * Resize the image * @return boolean */ private function resize() { $filename = $this->uploadObject->getAbsoluteSrc(); $extension = $this->uploadObject->extension; // Does the original file exist? If not return false if (!File::exists($filename)) { return false; } // Check to see our directory for caching exists, if it doesn't recursively create it if (!File::isDirectory($this->getPath())) { File::makeDirectory($this->getPath(), 0777, true); } $img = Image::make($filename); if ($this->crop) { $img->fit($this->width, $this->height)->save($this->getPathFilename()); } else { $img->resize($this->width, $this->height, true, true)->resizeCanvas($this->width, $this->height, null, false, 'ffffff')->save($this->getPathFilename()); } return true; }
/** * Process an uploaded file and store it in a web-accessible place. * * @param UploadedFile $file * @param string $publishFilename * * @throws \Exception */ public function process(UploadedFile $file, $publishFilename) { // Temporary filename to work with. $tempFilename = $this->generator->generate(40); try { $file->move($this->publishDir, $tempFilename); $speakerPhoto = Image::make($this->publishDir . '/' . $tempFilename); if ($speakerPhoto->height > $speakerPhoto->width) { $speakerPhoto->resize($this->size, null, true); } else { $speakerPhoto->resize(null, $this->size, true); } $speakerPhoto->crop($this->size, $this->size); if ($speakerPhoto->save($this->publishDir . '/' . $publishFilename)) { unlink($this->publishDir . '/' . $tempFilename); } } catch (\Exception $e) { unlink($this->publishDir . '/' . $tempFilename); throw $e; } }
/** * Post an image from the admin * * @return Json */ public function postImage() { $file = Input::file('file'); $imageDir = Config::get('core::wardrobe.image_dir'); $destinationPath = public_path() . "/{$imageDir}/"; $filename = $file->getClientOriginalName(); $resizeEnabled = Config::get('core::wardrobe.image_resize.enabled'); if ($resizeEnabled) { $resizeWidth = Config::get('core::wardrobe.image_resize.width'); $resizeHeight = Config::get('core::wardrobe.image_resize.height'); $image = Image::make($file->getRealPath())->resize($resizeWidth, $resizeHeight, true); $image->save($destinationPath . $filename); } else { $file->move($destinationPath, $filename); } if (File::exists($destinationPath . $filename)) { // @note - Using the absolute url so it loads images when ran in sub folder // this will make exporting less portable and may need to re-address at a later point. return Response::json(array('filename' => url("/{$imageDir}/" . $filename))); } return Response::json(array('error' => 'Upload failed. Please ensure your public/img directory is writable.')); }
public function index() { /* |-------------------------------------------------------------------------- | Check for image |-------------------------------------------------------------------------- | | Transform just needs the path to an image to get started. If it exists, | the fun begins. | */ $image_src = $this->fetchParam('src', null, false, false, false); // Set full system path $image_path = Path::tidy(BASE_PATH . '/' . $image_src); // Check if image exists before doing anything. if (!File::isImage($image_path)) { Log::error("Could not find requested image to transform: " . $image_path, "core", "Transform"); return; } /* |-------------------------------------------------------------------------- | Resizing and cropping options |-------------------------------------------------------------------------- | | The first transformations we want to run is for size to reduce the | memory usage for future effects. | */ $width = $this->fetchParam('width', null, 'is_numeric'); $height = $this->fetchParam('height', null, 'is_numeric'); // resize specific $ratio = $this->fetchParam('ratio', true, false, true); $upsize = $this->fetchParam('upsize', true, false, true); // crop specific $pos_x = $this->fetchParam('pos_x', 0, 'is_numeric'); $pos_y = $this->fetchParam('pos_y', 0, 'is_numeric'); $quality = $this->fetchParam('quality', '75', 'is_numeric'); /* |-------------------------------------------------------------------------- | Action |-------------------------------------------------------------------------- | | Available actions: resize, crop, and guess. | | "Guess" will find the best fitting aspect ratio of your given width and | height on the current image automatically, cut it out and resize it to | the given dimension. | */ $action = $this->fetchParam('action', 'resize'); /* |-------------------------------------------------------------------------- | Extra bits |-------------------------------------------------------------------------- | | Delicious and probably rarely used options. | */ $angle = $this->fetchParam('rotate', false); $flip_side = $this->fetchParam('flip', false); $blur = $this->fetchParam('blur', false, 'is_numeric'); $pixelate = $this->fetchParam('pixelate', false, 'is_numeric'); $grayscale = $this->fetchParam('grayscale', false, false, true); // Silly brits $greyscale = $this->fetchParam('greyscale', $grayscale, false, true); /* |-------------------------------------------------------------------------- | Assemble filename and check for duplicate |-------------------------------------------------------------------------- | | We need to make sure we don't already have this image created, so we | defer any action until we've processed the parameters, which create | a unique filename. | */ // Find .jpg, .png, etc $extension = File::getExtension($image_path); // Filename with the extension removed so we can append our unique filename flags $stripped_image_path = str_replace('.' . $extension, '', $image_path); // The possible filename flags $parameter_flags = array('width' => $width, 'height' => $height, 'quality' => $quality, 'rotate' => $angle, 'flip' => $flip_side, 'pos_x' => $pos_x, 'pos_y' => $pos_y, 'blur' => $blur, 'pixelate' => $pixelate, 'greyscale' => $greyscale); // Start with a 1 character action flag $file_breadcrumbs = '-' . $action[0]; foreach ($parameter_flags as $param => $value) { if ($value) { $flag = is_bool($value) ? '' : $value; // don't show boolean flags $file_breadcrumbs .= '-' . $param[0] . $flag; } } // Allow converting filetypes (jpg, png, gif) $extension = $this->fetchParam('type', $extension); // Allow saving in a different directory $destination = $this->fetchParam('destination', Config::get('transform_destination', false), false, false, false); if ($destination) { $destination = Path::tidy(BASE_PATH . '/' . $destination); // Method checks to see if folder exists before creating it Folder::make($destination); $stripped_image_path = Path::tidy($destination . '/' . basename($stripped_image_path)); } // Reassembled filename with all flags filtered and delimited $new_image_path = $stripped_image_path . $file_breadcrumbs . '.' . $extension; // Check if we've already built this image before if (File::exists($new_image_path)) { return File::cleanURL($new_image_path); } /* |-------------------------------------------------------------------------- | Create Image |-------------------------------------------------------------------------- | | Transform just needs the path to an image to get started. The image is | created in memory so we can start manipulating it. | */ $image = Image::make($image_path); /* |-------------------------------------------------------------------------- | Perform Actions |-------------------------------------------------------------------------- | | This is fresh transformation. Time to work the magic! | */ if ($action === 'resize' && ($width || $height)) { $image->resize($width, $height, $ratio, $upsize); } if ($action === 'crop' && $width && $height) { $image->crop($width, $height, $pos_x, $pos_y); } if ($action === 'smart') { $image->grab($width, $height); } if ($angle) { $image->rotate($angle); } if ($flip_side === 'h' || $flip_side === 'v') { $image->flip($flip_side); } if ($greyscale) { $image->greyscale(); } if ($blur) { $image->blur($blur); } if ($pixelate) { $image->pixelate($pixelate); } /* |-------------------------------------------------------------------------- | Save |-------------------------------------------------------------------------- | | Get out of dodge! | */ $image->save($new_image_path, $quality); return File::cleanURL($new_image_path); }
public function run($params) { try { $dirsStack = array(); $filesStack = array(); $sizeSort = function (SplFileInfo $a, SplFileInfo $b) { $getDirectorySize = function ($path) { $bytes = 0; if (strtolower(substr(PHP_OS, 0, 3)) !== 'win') { $io = popen('/usr/bin/du -sb ' . $path, 'r'); if ($io !== false) { $bytes = intval(fgets($io, 80)); pclose($io); return $bytes; } } else { foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $directory) { $bytes += $directory->getSize(); } } return $bytes; }; $s1 = $a->isDir() ? $getDirectorySize($a->getPathname()) : $a->getSize(); $s2 = $b->isDir() ? $getDirectorySize($b->getPathname()) : $b->getSize(); if (function_exists('gmp_cmp')) { return gmp_cmp($s1, $s2); } else { if ($s1 > $s2) { return 1; } else { if ($s2 < $s2) { return -1; } else { return 0; } } } }; $finfo = new finfo(FILEINFO_MIME_TYPE); $directories = Finder::create()->depth(0)->directories()->in($params['uploads_path'] . '/' . $params['path']); if (isset($params['sort'])) { switch ($params['sort']) { case 'type': $directories->sortByType(); break; case 'size': $directories->sort($sizeSort); break; case 'date': $directories->sortByModifiedTime(); break; default: $directories->sortByName(); } } if (isset($params['search'])) { $directories->name('*' . $params['search'] . '*'); } foreach (iterator_to_array($directories) as $file) { $mime = $finfo->file($file); $data = array('name' => $file->getBasename(), 'type' => current(explode('/', $mime)), 'mime' => $mime, 'path' => ltrim(str_replace(array($params['uploads_path'], '\\'), array('', '/'), $file->getPathname()), '\\/'), 'extension' => ''); $dirsStack[] = $data; } if (isset($params['order'])) { $dirsStack = array_reverse($dirsStack); } $files = Finder::create()->depth(0)->files()->in($params['uploads_path'] . '/' . $params['path']); if (isset($params['sort'])) { switch ($params['sort']) { case 'type': $files->sortByType(); break; case 'size': $files->sort($sizeSort); break; case 'date': $files->sortByModifiedTime(); break; default: $files->sortByName(); } } if (isset($params['search'])) { $files->name('*' . $params['search'] . '*'); } foreach (iterator_to_array($files) as $file) { $mime = $finfo->file($file); $thumbName = md5($file->getRealPath()) . '.' . $file->getExtension(); if (!File::exists($thumb = $params['thumbs_path'] . '/' . $thumbName)) { $img = Image::make($file->getRealPath()); $img->grab(144, 100); $img->save($thumb); } $data = array('name' => $file->getBasename(), 'type' => current(explode('/', $mime)), 'mime' => $mime, 'path' => $params['path'], 'extension' => $file->getExtension(), 'url' => URL::to(ltrim(str_replace(str_replace('\\', '/', public_path()), '', str_replace('\\', '/', $file->getPath())), '\\/') . '/' . $file->getBasename()), 'thumbnail' => Config::get('media-manager::url.thumbnails') . '/' . $thumbName); $filesStack[] = $data; } if (isset($params['order'])) { $filesStack = array_reverse($filesStack); } $stack = array_merge($dirsStack, $filesStack); if (isset($params['filter'])) { $stack = array_values(array_where($stack, function ($key, $value) use($params) { if ($params['filter'] === 'file') { return $value['type'] !== 'directory'; } else { return $value['type'] === $params['filter']; } })); } return self::success('', array('breadcrumb' => array_filter(explode('/', $params['path'])), 'files' => $stack)); } catch (Exception $e) { return self::error($e->getMessage()); } }
public function processAction(Request $req, Application $app) { if (!$app['sentry']->check()) { return $app->redirect($app['url'] . '/login'); } $user = $app['sentry']->getUser(); if ($user->getId() !== $req->get('id')) { $app['session']->set('flash', array('type' => 'error', 'short' => 'Error', 'ext' => "You cannot edit someone else's profile")); return $app->redirect($app['url'] . '/dashboard'); } $form_data = array('email' => $req->get('email'), 'user_id' => $req->get('id'), 'first_name' => $req->get('first_name'), 'last_name' => $req->get('last_name'), 'company' => $req->get('company'), 'twitter' => $req->get('twitter'), 'airport' => $req->get('airport'), 'transportation' => $req->get('transportation'), 'hotel' => $req->get('hotel'), 'speaker_info' => $req->get('speaker_info') ?: null, 'speaker_bio' => $req->get('speaker_bio') ?: null); if ($req->files->get('speaker_photo') != null) { // Upload Image $form_data['speaker_photo'] = $req->files->get('speaker_photo'); } $form = new SignupForm($form_data, $app['purifier']); $isValid = $form->validateAll('update'); if ($isValid) { $sanitized_data = $form->getCleanData(); // Remove leading @ for twitter $sanitized_data['twitter'] = preg_replace('/^@/', '', $sanitized_data['twitter']); if (isset($form_data['speaker_photo'])) { // Move file into uploads directory $fileName = uniqid() . '_' . $form_data['speaker_photo']->getClientOriginalName(); $form_data['speaker_photo']->move(APP_DIR . '/web/' . $app['uploadPath'], $fileName); // Resize Photo $speakerPhoto = Image::make(APP_DIR . '/web/' . $app['uploadPath'] . '/' . $fileName); if ($speakerPhoto->height > $speakerPhoto->width) { $speakerPhoto->resize(250, null, true); } else { $speakerPhoto->resize(null, 250, true); } $speakerPhoto->crop(250, 250); // Give photo a unique name $sanitized_data['speaker_photo'] = $form_data['first_name'] . '.' . $form_data['last_name'] . uniqid() . '.' . $speakerPhoto->extension; // Resize image and destroy original if ($speakerPhoto->save(APP_DIR . '/web/' . $app['uploadPath'] . $sanitized_data['speaker_photo'])) { unlink(APP_DIR . '/web/' . $app['uploadPath'] . $fileName); } } $mapper = $app['spot']->mapper('\\OpenCFP\\Entity\\User'); $user = $mapper->get($user->getId()); $user->email = $sanitized_data['email']; $user->first_name = $sanitized_data['first_name']; $user->last_name = $sanitized_data['last_name']; $user->company = $sanitized_data['company']; $user->twitter = $sanitized_data['twitter']; $user->airport = $sanitized_data['airport']; $user->transportation = $sanitized_data['transportation']; $user->hotel = $sanitized_data['hotel']; $user->info = $sanitized_data['speaker_info']; $user->bio = $sanitized_data['speaker_bio']; $response = $mapper->save($user); if ($response == true) { $app['session']->set('flash', array('type' => 'success', 'short' => 'Success', 'ext' => "Successfully updated your information!")); return $app->redirect($app['url'] . '/profile/edit/' . $form_data['user_id']); } if ($response == false) { $app['session']->set('flash', array('type' => 'error', 'short' => 'Error', 'ext' => "We were unable to update your information. Please try again.")); } } else { $app['session']->set('flash', array('type' => 'error', 'short' => 'Error', 'ext' => implode('<br>', $form->getErrorMessages()))); } $form_data['formAction'] = '/profile/edit'; $form_data['buttonInfo'] = 'Update Profile'; $form_data['id'] = $user->getId(); $form_data['user'] = $user; $form_data['flash'] = $this->getFlash($app); $template = $app['twig']->loadTemplate('user/edit.twig'); return $template->render($form_data); }
/** * Process any speaker photos that we might have * * @param array $form_data * @param Application $app */ protected function processSpeakerPhoto($form_data, Application $app) { if (!isset($form_data['speaker_photo'])) { return false; } // Move file into uploads directory $fileName = uniqid() . '_' . $form_data['speaker_photo']->getClientOriginalName(); $form_data['speaker_photo']->move(APP_DIR . '/web/' . $app['uploadPath'], $fileName); // Resize Photo $speakerPhoto = Image::make(APP_DIR . '/web/' . $app['uploadPath'] . '/' . $fileName); if ($speakerPhoto->height > $speakerPhoto->width) { $speakerPhoto->resize(250, null, true); } else { $speakerPhoto->resize(null, 250, true); } $speakerPhoto->crop(250, 250); // Give photo a unique name $sanitized_data['speaker_photo'] = $form_data['first_name'] . '.' . $form_data['last_name'] . uniqid() . '.' . $speakerPhoto->extension; // Resize image, save, and destroy original if (!$speakerPhoto->save(APP_DIR . '/web/' . $app['uploadPath'] . $sanitized_data['speaker_photo'])) { return false; } unlink(APP_DIR . '/web/' . $app['uploadPath'] . $fileName); return true; }
/** * Upload file(s) * * @param string $destination Where the file is going * @param string $id The field took look at in the files array * @return array */ public static function uploadBatch($destination = null, $id = null) { $destination = $destination ?: Request::get('destination'); $id = $id ?: Request::get('id'); $files = self::standardizeFileUploads($_FILES); $results = array(); // Resizing configuration if ($resize = Request::get('resize')) { $width = Request::get('width', null); $height = Request::get('height', null); $ratio = Request::get('ratio', true); $upsize = Request::get('upsize', false); $quality = Request::get('quality', '75'); } // If $files[$id][0] exists, it means there's an array of images. // If there's not, there's just one. We want to change this to an array. if ( ! isset($files[$id][0])) { $tmp = $files[$id]; unset($files[$id]); $files[$id][] = $tmp; } // Process each image foreach ($files[$id] as $file) { // Image data $path = File::upload($file, $destination); $name = basename($path); // Resize if ($resize) { $image = \Intervention\Image\Image::make(Path::assemble(BASE_PATH, $path)); $resize_folder = Path::assemble($image->dirname, 'resized'); if ( ! Folder::exists($resize_folder)) { Folder::make($resize_folder); } $resize_path = Path::assemble($resize_folder, $image->basename); $path = Path::toAsset($resize_path); $name = basename($path); $image->resize($width, $height, $ratio, $upsize)->save($resize_path, $quality); } $results[] = compact('path', 'name'); } return $results; }
/** * Construct from image with text * @param string $sourceImage Path to source image * @api */ public function __construct($sourceImage) { $this->image = \Intervention\Image\Image::make($sourceImage); }
/** * Handle the file upload. Returns the response body on success, or false * on failure. * * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file * * @return array|bool */ public function handle(UploadedFile $file) { $mime = $file->getMimeType(); $filename = $this->makeFilename(); $path = $this->getFullPath($this->directory . '/' . $filename); $success = Image::make($file->getRealPath())->resize($this->size, $this->size, true, false)->save($path, $this->quality); if (!$success) { return false; } return $this->getJsonBody($filename, $mime, $path); }
public function testEncoded() { $img = Image::make('public/test.jpg'); $img->encode(); $this->assertEquals($img->encoded, $img->encode()); }
/** * Open a new image resource from image file * * @param mixed $source * @return \Intervention\Image\Image * @static */ public static function make($source) { return \Intervention\Image\Image::make($source); }
public function testEncode() { // default encoding $data = Image::make('public/circle.png')->encode(); $this->assertInternalType('resource', @imagecreatefromstring($data)); // jpg encoding $data = Image::make('public/circle.png')->encode('jpg'); $this->assertInternalType('resource', @imagecreatefromstring($data)); // gif encoding $data = Image::make('public/circle.png')->encode('gif'); $this->assertInternalType('resource', @imagecreatefromstring($data)); // data-url encoding $data = Image::make('public/circle.png')->encode('data-url'); $encoded = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAChklEQVRo3uXavUscQRjH8c+t2MhhcUhiKolYiDFXCIKFNkoqrYL/gyT/UV4sTZ3CgI2SIhBBsJBwWKjEYCEptLmzSpFi5ny56Hm+nLdjvt3e7t4+v52ZnWee3xTcHyMYxiAG0I8SivF8FUc4xD72sI3KfTy8cMf7y5jAOMZu+R+b2MA6th5ayCSmMXPujd+VKlaxhm/tFjKKOcyiR3s4wRcs40erN3Xd4AHzeIMpdGsf3XiBl/G4cl9CnmABb+PgfShK8aUVsYvaXYQMxlZ4rXOU0YefOL6NkLqIVzrPUBSze5WYribdKS8i6jxHb/wA1FoVstDh7tSsZQr43oqQ+Tiw80pZyBAqzYSMxi5VyrEQeCakN7/rP2QNF8zF5ss7QzFWlwmZFGbsVJiNMf8jZFr70o520BNjviCkLCSAqTETYz8VMuH+stiHpBhjPxUynqAI52PPhJXdWMJCxjCSCcvT1BnOhOQwdQYzoVCQOgOZUO1Inf5M/vOqVihl0pw/Gilmj0AEwjxSfQQ6qpmwSEmdo0yoxabOYSYUlFNnPxOq4qmzlwlr39TZzoRqxGbCIjZRqc8jGwkL2eBsYbUuzfmkGmM/FbIlmCypsRpjv1BFWRNMllQ4iTHjYqXxF54KJksKfMan+kFj0riMnQRE7MRYXdYinNVSp3Iu5B2+NhNCmFeKYuErhyxhsfHHq/yRXcEhyltBewUf3MDoqQmeXZ/gFOWBNbzHwWUnm3mIx7FlenPQMitRxJUJ7nWu7rHg2RU6OGaWYnc6aHZRKz57TfDsjgSn6KGqLjvC12nRNR57q0LqVISU/08cN+3a/XAiTHYfNXxim/HfbqppJPltTpfR0Y1nfwGRl30LQuetpgAAAABJRU5ErkJggg=='; $this->assertEquals($data, $encoded); }
public function testExifRead() { // read all data $data = Image::make('public/exif.jpg')->exif(); $this->assertInternalType('array', $data); $this->assertEquals(count($data), 19); // read key $data = Image::make('public/exif.jpg')->exif('Artist'); $this->assertInternalType('string', $data); $this->assertEquals($data, 'Oliver Vogel'); // read image with no exif data $data = Image::make('public/test.jpg')->exif(); $this->assertEquals($data, null); // read key that doesn't exist $data = Image::make('public/exif.jpg')->exif('xxx'); $this->assertEquals($data, null); }
/** * Scale an image according to specified * width and height. * * @param string $file * @param integer $width * @param integer $height * @return Intervention\Image\Image */ public function scale($file, $width, $height) { return Image::make($file)->resize($width, $height, true, false); }
public function index() { /* |-------------------------------------------------------------------------- | Check for image |-------------------------------------------------------------------------- | | Transform just needs the path to an image to get started. If it exists, | the fun begins. | | The way to do this changes depending on whether its an internal or | external file. | */ $image_src = $this->fetchParam('src', null, false, false, false); // External URL if ($is_external = URL::isExternalUrl($image_src)) { $image_path = $image_src; // Check if file is an image before doing anything. // @TODO: Maybe check that the file exists. $img_info = pathinfo($image_src); $is_image = in_array($img_info['extension'], array('jpg', 'jpeg', 'png', 'gif')); if ( ! $is_image) { Log::error("Requested file is not an image: " . $image_path, "core", "Transform"); return; } } // Internal URL else { // Set full system path $image_path = Path::standardize(Path::fromAsset($image_src)); // Check if image exists before doing anything. if ( ! File::isImage($image_path)) { Log::error("Could not find requested image to transform: " . $image_path, "core", "Transform"); return; } } /* |-------------------------------------------------------------------------- | Resizing and cropping options |-------------------------------------------------------------------------- | | The first transformations we want to run is for size to reduce the | memory usage for future effects. | */ $width = $this->fetchParam('width', null, 'is_numeric'); $height = $this->fetchParam('height', null, 'is_numeric'); // resize specific $ratio = $this->fetchParam('ratio', true, false, true); $upsize = $this->fetchParam('upsize', true, false, true); // crop specific $pos_x = $this->fetchParam('pos_x', 0, 'is_numeric'); $pos_y = $this->fetchParam('pos_y', 0, 'is_numeric'); $quality = $this->fetchParam('quality', '75', 'is_numeric'); /* |-------------------------------------------------------------------------- | Action |-------------------------------------------------------------------------- | | Available actions: resize, crop, and guess. | | "Guess" will find the best fitting aspect ratio of your given width and | height on the current image automatically, cut it out and resize it to | the given dimension. | */ $action = $this->fetchParam('action', 'resize'); /* |-------------------------------------------------------------------------- | Extra bits |-------------------------------------------------------------------------- | | Delicious and probably rarely used options. | */ $angle = $this->fetchParam('rotate', false); $flip_side = $this->fetchParam('flip' , false); $blur = $this->fetchParam('blur', false, 'is_numeric'); $pixelate = $this->fetchParam('pixelate', false, 'is_numeric'); $greyscale = $this->fetchParam(array('greyscale', 'grayscale'), false, false, true); $watermark = $this->fetchParam('watermark', false, false, false, false); /* |-------------------------------------------------------------------------- | Assemble filename and check for duplicate |-------------------------------------------------------------------------- | | We need to make sure we don't already have this image created, so we | defer any action until we've processed the parameters, which create | a unique filename. | */ // Late modified time of original image $last_modified = ($is_external) ? false : File::getLastModified($image_path); // Find .jpg, .png, etc $extension = File::getExtension($image_path); // Filename with the extension removed so we can append our unique filename flags $stripped_image_path = str_replace('.' . $extension, '', $image_path); // The possible filename flags $parameter_flags = array( 'width' => $width, 'height' => $height, 'quality' => $quality, 'rotate' => $angle, 'flip' => $flip_side, 'pos_x' => $pos_x, 'pos_y' => $pos_y, 'blur' => $blur, 'pixelate' => $pixelate, 'greyscale' => $greyscale, 'modified' => $last_modified ); // Start with a 1 character action flag $file_breadcrumbs = '-'.$action[0]; foreach ($parameter_flags as $param => $value) { if ($value) { $flag = is_bool($value) ? '' : $value; // don't show boolean flags $file_breadcrumbs .= '-' . $param[0] . $flag; } } // Allow converting filetypes (jpg, png, gif) $extension = $this->fetchParam('type', $extension); // Allow saving in a different directory $destination = $this->fetchParam('destination', Config::get('transform_destination', false), false, false, false); if ($destination) { $destination = Path::tidy(BASE_PATH . '/' . $destination); // Method checks to see if folder exists before creating it Folder::make($destination); $stripped_image_path = Path::tidy($destination . '/' . basename($stripped_image_path)); } // Reassembled filename with all flags filtered and delimited $new_image_path = $stripped_image_path . $file_breadcrumbs . '.' . $extension; // Check if we've already built this image before if (File::exists($new_image_path)) { return Path::toAsset($new_image_path); } /* |-------------------------------------------------------------------------- | Create Image |-------------------------------------------------------------------------- | | Transform just needs the path to an image to get started. The image is | created in memory so we can start manipulating it. | */ $image = Image::make($image_path); /* |-------------------------------------------------------------------------- | Perform Actions |-------------------------------------------------------------------------- | | This is fresh transformation. Time to work the magic! | */ if ($action === 'resize' && ($width || $height) ) { $image->resize($width, $height, $ratio, $upsize); } if ($action === 'crop' && $width && $height) { $image->crop($width, $height, $pos_x, $pos_y); } if ($action === 'smart') { $image->grab($width, $height); } $resize = $this->fetchParam('resize', null); if ($resize) { $resize_options = Helper::explodeOptions($resize, true); $image->resize( array_get($resize_options, 'width'), array_get($resize_options, 'height'), array_get($resize_options, 'ratio', true), array_get($resize_options, 'upsize', true) ); } $crop = $this->fetchParam('crop', null); if ($crop) { $crop_options = Helper::explodeOptions($crop, true); $image->crop( array_get($crop_options, 'width'), array_get($crop_options, 'height'), array_get($crop_options, 'x'), array_get($crop_options, 'y') ); } if ($angle) { $image->rotate($angle); } if ($flip_side === 'h' || $flip_side === 'v') { $image->flip($flip_side); } if ($greyscale) { $image->greyscale(); } if ($blur) { $image->blur($blur); } if ($pixelate) { $image->pixelate($pixelate); } // Positioning options via ordered pipe settings: // source|position|x offset|y offset if ($watermark) { $watermark_options = Helper::explodeOptions($watermark); $source = Path::tidy(BASE_PATH . '/' . array_get($watermark_options, 0, null)); $anchor = array_get($watermark_options, 1, null); $pos_x = array_get($watermark_options, 2, 0); $pos_y = array_get($watermark_options, 3, 0); $image->insert($source, $pos_x, $pos_y, $anchor); } /* |-------------------------------------------------------------------------- | Save |-------------------------------------------------------------------------- | | Get out of dodge! | */ try { $image->save($new_image_path, $quality); } catch(Exception $e) { Log::fatal('Could not write new images. Try checking your file permissions.', 'core', 'Transform'); throw new Exception('Could not write new images. Try checking your file permissions.'); } return File::cleanURL($new_image_path); }