open() публичный статический Метод

Creates an instance, usefull for one-line chaining.
public static open ( $file = '' )
Пример #1
0
 /**
  * Редактирование категории 
  * @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]);
 }
Пример #2
0
 public static function loadImage($file)
 {
     try {
         return Image::open($file);
     } catch (Exception $e) {
         self::$err = $e->getMessage();
         return false;
     }
 }
Пример #3
0
 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);
     }
 }
Пример #5
0
 /**
  * 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;
 }
Пример #6
0
 /**
  * @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;
 }
Пример #7
0
 /**
  * @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;
 }
 /**
  * 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 = [''];
     }
 }
Пример #9
0
 /**
  * @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;
     }
 }
Пример #10
0
 /**
  * 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);
             }
         });
     });
 }
Пример #11
0
 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);
 }
Пример #12
0
 /**
  * @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);
 }
Пример #13
0
 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>');
         }
     }
 }
Пример #14
0
<?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');
Пример #15
0
<?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');
Пример #16
0
<?php

require_once '../autoload.php';
use Gregwar\Image\Image;
Image::open('img/test.png')->resize('26%')->negate()->save('out.jpg', 'jpg');
Пример #17
0
 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()]);
     }
 }
Пример #18
0
<?php

require_once '../Image.php';
use Gregwar\Image\Image;
Image::open('img/test.png')->resize(100, 100)->negate()->guess(55);
Пример #19
0
<?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";
Пример #20
0
            $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');
Пример #21
0
 /**
  * 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;
 }
Пример #22
0
 /**
  * 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;
 }
Пример #23
0
    protected function processImages(&$data, $width, $title = null)
    {
        $found = preg_match_all('{
			(				# wrap whole match in $1
			  !\\[(\\w+)?\\]
			  \\(			# literal paren
				(
					\\S*	# src url = $3
				)
			  \\)
			)
			}xm', $data, $matches);
        if (!$found) {
            return false;
        }
        for ($i = 0; $i < $found; $i++) {
            $tag = $matches[0][$i];
            $additionalClasses = $matches[2][$i];
            $imageFile = $matches[3][$i];
            $imagePath = $this->path . '/' . $imageFile;
            $url = '';
            if (file_exists($imagePath)) {
                // @todo check if it's an image (jpg, gif, png)
                $contentType = explode('/', mime_content_type($imagePath));
                if ($contentType[0] == 'image' && in_array($contentType[1], Image::$types)) {
                    $image = Image::open($imagePath);
                    //->setName($title);
                    if ($title) {
                        $image->setPrettyName($title);
                    }
                    try {
                        $url = '![](/' . $image->cropResize($width, PHP_INT_MAX)->guess(100) . ')';
                    } catch (Exception $e) {
                        echo $image;
                        echo $e->getMessage();
                    }
                } else {
                    $url = '![](/' . $imageFile . ')';
                }
            } else {
                $url = "<strong style=\"color:red;display:block\">Couldn't process {$imageFile}</strong>";
            }
            if ($additionalClasses == 'screenshot') {
                $url = '<span class="screen_header"></span>' . $url . '<span class="screen_footer"></span>';
            }
            $data = str_replace($tag, $url, $data);
        }
    }
Пример #24
0
<?php

require_once '../autoload.php';
use Gregwar\Image\Image;
Image::open('in.gif')->resize(500, 500)->save('out.png', 'png');
Пример #25
0
    <div class="col-md-3 pull-right view">
        <span>Nézet</span>
        <?php 
echo Html::a("Rács", Yii::$app->urlManager->createAbsoluteUrl(["/category/view", "justcategory" => $categoryData["slug"], "tipus" => 'racs']), ['class' => 'racs ' . ($type == "racs" ? "active" : "")]);
echo Html::a("Lista", Yii::$app->urlManager->createAbsoluteUrl(["/category/view", "justcategory" => $categoryData["slug"], "tipus" => 'lista']), ['class' => 'lista ' . ($type == "lista" ? "active" : "")]);
?>
    </div>
    <div class="clearfix"></div>
</div>

<div class="product-categories-index">

    <?php 
echo GridView::widget(['dataProvider' => $dataProvider, 'options' => ['class' => 'product-grid'], 'columns' => [['contentOptions' => ['class' => 'image'], 'format' => 'html', 'value' => function ($model, $index, $dataColumn) {
    $image = Html::img("/" . Image::open(Yii::getAlias("@webroot") . DIRECTORY_SEPARATOR . $model["productImages"]["thumb"])->cropResize(95, 95)->jpeg(), ["alt" => $model["title"], "class" => "product-image"]);
    return Html::a($image, Yii::$app->urlManager->createAbsoluteUrl(["/products/view", "categoryslug" => $model["productCategory"]["slug"], "productslug" => $model["slug"]]));
}], ['format' => 'raw', 'value' => function ($model, $index, $dataColumn) {
    $out = Html::a($model["title"], Yii::$app->urlManager->createAbsoluteUrl(["/products/view", "categoryslug" => $model["productCategory"]["slug"], "productslug" => $model["slug"]]), ["class" => "product-title"]);
    $out .= '<br>';
    $out .= Html::tag("span", $model["defaulttoppings"], ["class" => "product-toppings"]);
    $basket = Html::textInput("amount[{$model["id"]}]", 1);
    $toppings = "";
    foreach ($model["productToppings"] as $top) {
        $toppings .= '<div class="toprow">';
        $toppings .= '<div class="col-xs-2"><input type="checkbox" data-price="' . $top["price"] . '" id="topping-' . $model["id"] . '-' . $top["id"] . '" name="topping[' . $model["id"] . '][' . $top["id"] . ']" /></div>';
        $toppings .= '<div class="col-xs-6">' . Html::label($top["name"], 'topping-' . $model["id"] . '-' . $top["id"]) . '</div>';
        $toppings .= '<div class="col-xs-4">' . Html::label("+{$top["price"]}.- Ft", 'topping-' . $model["id"] . '-' . $top["id"]) . '</div>';
        $toppings .= '</div>';
        $toppings .= Html::tag('div', '', ['class' => 'clearfix']);
    }
Пример #26
0
<?php

require_once '../autoload.php';
use Gregwar\Image\Image;
?>
<img src="<?php 
echo Image::open('img/test.png')->resize('50%')->inline();
?>
" />
Пример #27
0
<?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";
Пример #28
0
<?php

require_once '../autoload.php';
use Gregwar\Image\Image;
$image = Image::open('img/test.png')->resize(100, 100)->negate()->get('jpeg');
echo $image;
Пример #29
0
 /**
  * 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());
 }
Пример #30
0
<?php

require_once '../autoload.php';
use Gregwar\Image\Image;
// Opening mona.jpg
$img = Image::open('img/mona.jpg');
// Opening vinci.png
$watermark = Image::open('img/vinci.png');
// Mergine vinci text into mona in the top-right corner
$img->merge($watermark, $img->width() - $watermark->width(), $img->height() - $watermark->height())->save('out.jpg', 'jpg');