/** * Resize user avatar from uploaded picture * @param \Symfony\Component\HttpFoundation\File\UploadedFile|\Symfony\Component\HttpFoundation\File\File $original * @param int $user_id * @param string $size * @throws \Exception * @return null */ public function resizeAndSave($original, $user_id, $size = 'small') { $sizeConvert = ['big' => [400, 400], 'medium' => [200, 200], 'small' => [100, 100]]; if (!array_key_exists($size, $sizeConvert)) { return null; } $image = new Image(); $image->setCacheDir(root . '/Private/Cache/images'); $image->open($original->getPathname())->cropResize($sizeConvert[$size][0], $sizeConvert[$size][1])->save(root . '/upload/user/avatar/' . $size . '/' . $user_id . '.jpg', 'jpg', static::COMPRESS_QUALITY); return null; }
public function register() { $di = $this->getContainer(); $config = []; if (isset($di->get('config')['gregwarImage']) && is_array($di->get('config')['gregwarImage'])) { $config = $di->get('config')['gregwarImage']; } $di->add('Gregwar\\Image\\Image', function ($filepath = null, $w = null, $h = null) use($config) { $image = new Image($filepath, $w, $h); if (isset($config['cache_dir'])) { $image->setCacheDir($config['cache_dir']); } return $image; }); }
/** * Редактирование категории * @param \Psr\Http\Message\ServerRequestInterface $request * @param \Psr\Http\Message\ResponseInterface $response */ public function edit($request, $response) { $id = $request->getAttribute('id'); if (!isset($id)) { return $response->withRedirect('/categories'); } $id = (int) $id; $category = Model::factory('Models\\Category')->find_one($id); if (!isset($category->id)) { return $response->withRedirect('/categories'); } if (isset($_POST['submit'])) { $data = \Ohanzee\Helper\Arr::extract($_POST, ['title'], ''); if (!empty($_FILES['image']['name'])) { $image = Image::open($_FILES['image']['tmp_name']); $image->scaleResize($this->image_width, $this->image_height, '0xffffff'); $filename = md5(base64_encode($image->get('png', 100))) . '.png'; $image->save(DOCROOT . '/../aleksandr-sazhin.myjino.ru/_/' . $filename); $data['image'] = $filename; } $category->values($data); $category->save(); return $response->withRedirect('/categories/edit/' . $category->id); } return $this->render('categories/edit.html', ['category' => $category]); }
public function resizeFilter($pathToImage, $width = null, $height = null) { if (!$width && !$height) { $width = $this->params['width']; $height = $this->params['height']; } $path = '/' . Image::open($this->rootDir . '/../web' . $pathToImage)->zoomCrop($width, $height, 'transparent', 'top', 'left')->guess(); return $path; }
public function resize($fullSize = "", $filename = "") { $this->autoRender = false; $cacheFilename = 'resize' . DS . $fullSize . DS . $filename; $size = $this->_checkSize($fullSize); if ($this->_checkFile($cacheFilename)) { $cacheFilename = Image::open($filename)->zoomCrop($size[0], $size[1], 'transparent', 'center', 'center')->save($cacheFilename); $this->redirect('/' . $cacheFilename); } }
/** * @param string|null $destiny * @return string */ public function save($destiny = null) { if ($destiny === null) { $destiny = $this->generateFilename(); } if (isset(static::$config['default_extension'])) { $extension = static::$config['default_extension']; } else { $extension = strtolower(pathinfo($destiny, PATHINFO_EXTENSION)); } $this->prepareDestiny($destiny); GregwarImage::open($this->image)->resize($this->width, $this->height, 0xffffff, true)->save($destiny, $extension); return $destiny; }
public static function getThumbnail($fileName, $dimension) { $PathInfo = pathinfo($fileName); $thumbnailName = str_replace(' ', '_', "{$PathInfo['dirname']}/{$PathInfo['filename']}.thu{$Dim[0]}.{$PathInfo['extension']}"); $thumbnailName = str_replace('_(Custom)', '', $thumbnailName); if (!is_file($_SERVER['DOCUMENT_ROOT'] . $thumbnailName)) { //Effettuo il resize delle immagini al fine di creare le thumbneil //$thumb = PhpThumbFactory::create($_SERVER['DOCUMENT_ROOT'].$fileName); //$thumb->adaptiveResize($Dim[0], $Dim[1])->save($_SERVER['DOCUMENT_ROOT'].$ThuNam); $thumb = Image::make($_SERVER['DOCUMENT_ROOT'] . $fileName); $thumb->resize($dimension[0], $dimension[1]); $thumb->save($_SERVER['DOCUMENT_ROOT'] . $thumbnailName); } return $thumbnailName; }
/** * @param string|null $photo * @param string $path * @param string|null $sex * @return string * @throws UserAvatarException */ public static function create($photo, $path, $sex = null) { if ($filename = FS::makeFilename($path, 'jpg')) { if ($photo) { $image = Image::open($photo); $image->save($path . DIRECTORY_SEPARATOR . $filename); } else { $eightBitIcon = new EightBitIcon(); $eightBitIcon->generate($path . DIRECTORY_SEPARATOR . $filename, $sex); } } else { throw new UserAvatarException(); } return $filename; }
/** * @param Request $request * @param Form $articleForm * @return mixed * @throws \Exception */ protected function upload(Request $request, Form $form, $width, $height) { $files = $request->files->get($form->getName()); if (!empty($files['image'])) { $path = __DIR__ . self::UPLOAD_DIR; $filename = $files['image']->getClientOriginalName(); $filepath = $path . $filename; $files['image']->move($path, $filename); chmod($filepath, 0755); //ToDo: renommer les images en ajoutant uniqid() Image::open($filepath)->zoomCrop($width, $height, "#346A85", "center", "center")->save($filepath); return $filename; } else { return false; } }
/** * Get files in same dir */ protected function getFilesSameDirectory() { $files = (array) glob($this->absoluteStorageDir . '*'); $files = array_filter($files, 'is_file'); foreach ($files as $file) { $file = pathinfo($file); $path = $this->relativeStorageDir . $file['basename']; if (substr($path, 0, 1) == '/' || substr($path, 0, 1) == '\\') { $path = substr($path, 1); } $this->existing[$file['basename']] = '/' . Image::open($path)->zoomCrop(100, 100)->jpeg(); } if (!$this->existing) { $this->existing = ['']; } }
/** * Save the image with cache. * * @return mixed|string */ protected function saveImage() { if (!$this->image) { return parent::path(false); } if ($this->get('debug') && !$this->debug_watermarked) { $ratio = $this->get('ratio'); if (!$ratio) { $ratio = 1; } $locator = self::$grav['locator']; $overlay = $locator->findResource("system://assets/responsive-overlays/{$ratio}x.png") ?: $locator->findResource('system://assets/responsive-overlays/unknown.png'); $this->image->merge(ImageFile::open($overlay)); } $result = $this->image->cacheFile($this->format, $this->quality); return $result; }
public function resizeAndCrop($fileinfo, $toDir, $size, $output) { $from = $fileinfo->getPathname(); $to = $toDir . '/' . $fileinfo->getFilename(); try { $image = Image::open($from); $width = $height = $size; if ($image->width() > $image->height()) { $width = null; } else { $height = null; } $image->resize($width, $height)->crop(0, 0, $size, $size)->save($to); } catch (\Exception $e) { $output->writeln($e->getMessage()); } $output->writeln($from); $output->writeln($to); }
/** * Listen for events */ protected static function boot() { parent::boot(); static::saved(function ($image) { $image->processThumbnails(function ($image, $thumbnail, $method) { $thumbnailPath = $image->getImage($thumbnail); $imagePath = Input::file('file') ? Input::file('file') : $image->path; ImageLib::open($imagePath)->{$method}($thumbnail[0], $thumbnail[1])->save($thumbnailPath); }); }); static::deleted(function ($image) { $image->processThumbnails(function ($image, $thumbnail, $method) { $thumbnailPath = $image->getImage($thumbnail); if (file_exists($thumbnailPath)) { unlink($thumbnailPath); } }); }); }
/** * @param string $filename * @param string|null $sex * @param bool $unfiltered */ public function generate($filename, $sex = null, $unfiltered = false) { $DS = DIRECTORY_SEPARATOR; $parts = array('background', 'face', 'clothes', 'hair', 'eyes', 'mouth'); if (!in_array($sex, array('male', 'female'))) { $sex = 1 === mt_rand(1, 2) ? 'male' : 'female'; } $img = Image::create($this->size, $this->size); foreach ($parts as $part) { $images = glob(__DIR__ . $DS . 'img' . $DS . $sex . $DS . $part . $DS . '*.{jpg,jpeg,png,gif}', GLOB_BRACE); if (!$unfiltered) { $images = array_filter($images, function ($image) { $path_parts = pathinfo($image); return false === stristr($path_parts['filename'], 'unfiltered-'); }); } $img->merge(Image::open($images[array_rand($images)])); } $img->save($filename); }
protected function process($folder, $source, $target, $size, $output) { $dir = new \DirectoryIterator($folder); foreach ($dir as $fileinfo) { try { if ($fileinfo->isDir() && !$fileinfo->isDot()) { $output->writeln('<info>' . 'Folder : ' . $fileinfo->getPathname() . '</info>'); $this->process($fileinfo->getPathname(), $source, $target, $size, $output); } else { if ($fileinfo->isFile() && !$fileinfo->isDot() && $this->isImage($fileinfo->getPathname())) { $output->writeln('File : ' . $fileinfo->getPathname()); $from = $fileinfo->getPathname(); $to = str_replace($source, $target, $fileinfo->getPathname()); $to = str_replace(" ", "_", $to); $dir = dirname($to); if (!file_exists($dir)) { mkdir($dir, 0777, true); } $image = Image::open($from); $width = $size[0]; $height = $size[1]; if ($image->width() > $image->height()) { $height = null; } else { $width = null; } $image->resize($width, $height)->save($to); //$image->cropResize(200) //->save($to); unset($image); } else { $output->writeln('<error>' . 'File not n image : ' . $fileinfo->getPathname() . '</error>'); } } } catch (\Exception $e) { $output->writeln('<error>' . $e->getMessage() . '</error>'); } } }
$success = true; } } return $app['twig']->render('admin.html.twig', array('success' => $success)); })->bind('admin'); $app->match('/logout', function () use($app) { $app['session']->remove('admin'); return $app->redirect($app['url_generator']->generate('admin')); })->bind('logout'); $app->match('/addBook', function () use($app) { if (!$app['session']->has('admin')) { return $app['twig']->render('shouldBeAdmin.html.twig'); } $request = $app['request']; if ($request->getMethod() == 'POST') { $post = $request->request; if ($post->has('title') && $post->has('author') && $post->has('synopsis') && $post->has('copies')) { $files = $request->files; $image = ''; // Resizing image if ($files->has('image') && $files->get('image')) { $image = sha1(mt_rand() . time()); Image::open($files->get('image')->getPathName())->resize(240, 300)->save('uploads/' . $image . '.jpg'); Image::open($files->get('image')->getPathName())->resize(120, 150)->save('uploads/' . $image . '_small.jpg'); } // Saving the book to database $app['model']->insertBook($post->get('title'), $post->get('author'), $post->get('synopsis'), $image, (int) $post->get('copies')); } } return $app['twig']->render('addBook.html.twig'); })->bind('addBook');
<?php require_once '../autoload.php'; use Gregwar\Image\Image; // Note: create a "cache" directory before try this echo Image::open('img/test.png')->sepia()->setPrettyName('Some FanCY TestING!')->jpeg(); echo "\n";
<?php require_once '../autoload.php'; use Gregwar\Image\Image; /* * Use the cache with a from-scratch image */ echo Image::create(300, 350)->fill('rgb(255, 150, 150)')->circle(150, 150, 200, 'red', true)->write('./fonts/CaviarDreams.ttf', 'Hello world!', 150, 150, 20, 0, 'white', 'center')->jpeg(); echo "\n";
/** * Gets medium image, resets image manipulation operations. * * @param string $variable * @return $this */ public function image($variable = 'thumb') { // TODO: add default file $file = $this->get($variable); $this->image = ImageFile::open($file)->setCacheDir(basename(IMAGES_DIR))->setActualCacheDir(IMAGES_DIR)->setPrettyName(basename($this->get('basename'))); $this->filter(); return $this; }
<?php require_once '../autoload.php'; use Gregwar\Image\Image; Image::open('in.gif')->resize(500, 500)->save('out.png', 'png');
<?php require_once '../autoload.php'; use Gregwar\Image\Image; ?> <img src="<?php echo Image::open('img/test.png')->resize('50%')->inline(); ?> " />
public function testSaveImage() { $imagePathToSave = __DIR__ . '/' . uniqid() . '.png'; $imageUrl = 'http://upload.wikimedia.org/wikipedia/commons/3/31/Red-dot-5px.png'; // $imageRawBase64 = base64_encode(file_get_contents($imageUrl)); $imageRawBase64 = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='; if (!is_writable(dirname($imagePathToSave))) { $this->markTestSkipped('Directory not writable'); } /** * @var \OAuth\Common\Service\ServiceInterface|\PHPUnit_Framework_MockObject_MockObject $service */ $service = $this->getMock('\\OAuth\\Common\\Service\\AbstractService', ['httpRequest', 'request', 'getAuthorizationUri'], [], '', false); $service->expects($this->any())->method('httpRequest')->willReturn(base64_decode($imageRawBase64)); $extractor = new Extractor(FieldsValues::construct([Extractor::FIELD_IMAGE_URL => $imageUrl])); $extractor->setService($service); $this->assertFalse(is_file($imagePathToSave)); $extractor->saveImage($imagePathToSave, 10, 10); $this->assertTrue(is_file($imagePathToSave)); $fileContents = file_get_contents($imagePathToSave); unlink($imagePathToSave); /** @noinspection PhpUndefinedMethodInspection */ $this->assertEquals(base64_encode(Image::fromData(Image::fromData(base64_decode($imageRawBase64))->resize(10, 10)->get())->get('png')), base64_encode($fileContents)); }
<?php require_once '../autoload.php'; use Gregwar\Image\Image; // resize() will never enlarge the image Image::open('mona.jpg')->resize(250, 250, 'red')->save('resize.jpg'); // scaleResize() will also preserve the scale, but won't // enlage the image Image::open('mona.jpg')->scaleResize(250, 250, 'red')->save('scaleResize.jpg'); // forceResize() will resize matching the *exact* given size Image::open('mona.jpg')->forceResize(250, 250)->save('forceResize.jpg'); // cropResize() preserves scale just like resize() but will // trim the whitespace (if any) in the resulting image Image::open('mona.jpg')->cropResize(250, 250)->save('cropResize.jpg'); // zoomCrop() resizes the image so that a part of it appear in // the given area Image::open('mona.jpg')->zoomCrop(200, 200)->save('zoomCrop.jpg'); // You can specify the position using the xPos and yPos arguments Image::open('mona.jpg')->zoomCrop(200, 200, 'transparent', 'center', 'top')->save('zoomCropTop.jpg');
<?php require_once '../autoload.php'; use Gregwar\Image\Image; Image::open('img/test.png')->resize('26%')->negate()->save('out.jpg', 'jpg');
public function postImages() { try { $data = Input::get('data'); if ($data) { $data = json_decode($data); } if (is_object($data) && isset($data->id)) { $id = $data->id; } else { $id = 0; } $image = new Image(['class' => $this->_resource, 'id_element' => $id, 'extension' => strtolower(Input::file('file')->getClientOriginalExtension())]); if (!$image->save()) { throw new Exception('Error inserting image.'); } if ($image->extension == 'gif') { copy(Input::file('file'), $image->path); } else { ImageLib::open(Input::file('file'))->save($image->path); } ImageLib::open($image->path)->resize(100, 100)->save($image->thumbnail); return response()->json(['id' => $image->id, 'image' => '/' . $image->path, 'thumbnail' => '/' . $image->thumbnail]); } catch (Exception $e) { return response()->json(['error' => $e->getMessage()]); } }
<?php require_once '../Image.php'; use Gregwar\Image\Image; Image::open('img/test.png')->resize(100, 100)->negate()->guess(55);
/** * Test that dependencies are well generated. */ public function testDependencies() { $this->assertSame(array(), Image::create(100, 100)->getDependencies()); $this->assertSame(array(), Image::create(100, 100)->merge(Image::create(100, 50))->getDependencies()); $this->assertSame(array('toto.jpg'), Image::open('toto.jpg')->merge(Image::create(100, 50))->getDependencies()); $this->assertSame(array('toto.jpg', 'titi.jpg'), Image::open('toto.jpg')->merge(Image::open('titi.jpg'))->getDependencies()); $this->assertSame(array('toto.jpg', 'titi.jpg', 'tata.jpg'), Image::open('toto.jpg')->merge(Image::open('titi.jpg')->merge(Image::open('tata.jpg')))->getDependencies()); }
<?php require_once '../autoload.php'; use Gregwar\Image\Image; Image::open('img/test.png')->merge(Image::open('img/test2.jpg')->cropResize(100, 100))->save('out.jpg', 'jpg');
<?php $data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl' . 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr' . 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r' . '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg=='; $data = base64_decode($data); require_once '../Image.php'; use Gregwar\Image\Image; Image::fromData($data)->save('out.jpg');
<?php require_once '../autoload.php'; use Gregwar\Image\Image; // Note: create a "cache" directory before try this echo Image::open('img/test.png')->sepia(); echo "\n";