Esempio n. 1
0
 /**
  * Sends response to output.
  * @param \Nette\Http\IRequest $httpRequest
  * @param \Nette\Http\IResponse $httpResponse
  */
 public function send(\Nette\Http\IRequest $httpRequest, \Nette\Http\IResponse $httpResponse)
 {
     if ($this->image instanceof \Nette\Image) {
         echo $this->image->send($this->type, 100);
     } else {
         readfile($this->file);
     }
 }
Esempio n. 2
0
 /**
  * Get thumb file
  *
  * @param string $path File path
  *
  * @return Nette\Image
  */
 public function getThumbFile($path)
 {
     $thumbPath = $this->getThumbPath($path);
     if (file_exists($thumbPath)) {
         return Image::fromFile($thumbPath);
     } else {
         $status = true;
         if (function_exists("exec")) {
             exec("convert -version", $results, $status);
         }
         if (class_exists("\\Nette\\ImageMagick") && !$status) {
             $image = new ImageMagick($path);
         } elseif (class_exists("\\Imagick")) {
             $thumb = new Imagick($path);
             $thumb->resizeImage(96, null, Imagick::FILTER_LANCZOS, 1);
             $thumb->writeImage($thumbPath);
             $thumb->destroy();
             return Image::fromFile($path);
         } else {
             $image = Image::fromFile($path);
         }
         $image->resize(96, null, Image::SHRINK_ONLY);
         $image->save($thumbPath, 80);
         return $image;
     }
 }
Esempio n. 3
0
 public function createThumbnail()
 {
     $args = array_merge($this->defaults, func_get_args()[0]);
     $args = ArrayHash::from($args);
     $storage = $this->media->getStorage($args->storage);
     if (isset($args->namespace)) {
         $storage->setNamespace($args->namespace);
     }
     $image = $storage->load($args->file);
     $width = $args->width;
     $height = $args->height;
     if ($image !== NULL) {
         if ($width && $width != $image->width) {
             $name = $this->createThumbnailName($image, $width, $height);
             $thumb = $storage->absolutePath . '/' . $name;
             $src = NULL;
             if (!file_exists($thumb)) {
                 $image = Image::fromFile($image->absolutePath);
                 if (empty($height)) {
                     $height = $width;
                 }
                 $image->resize($width, $height, constant('Nette\\Image::' . strtoupper($args->flag)));
                 $image->save($thumb);
             }
             $image = $storage->load($name);
         }
         $src = $storage->getBaseUrl() . '/' . $image->filename;
         return $src;
     }
 }
Esempio n. 4
0
 /**
  * Validates image dimensions
  * @param ImageUpload $control
  * @param array $dimensions array of desired width and height
  * @param int $operation exact|minimal|maximal
  * @return boolean
  */
 private static function validateDimensions(ImageUpload $control, $dimensions, $operation)
 {
     if (count($dimensions) !== 2 || count(array_filter($dimensions)) === 0) {
         throw new \LogicException('Image dimensions must be array containing 2 integer|NULL values!');
     }
     list($width, $height) = $dimensions;
     $image = Image::fromFile($control->value);
     switch ($operation) {
         case static::DIMENSIONS_EXACT:
             if ($width !== NULL && $image->getWidth() != $width) {
                 return FALSE;
             }
             if ($height !== NULL && $image->getHeight() != $height) {
                 return FALSE;
             }
             break;
         case static::DIMENSIONS_MINIMAL:
             if ($width !== NULL && $image->getWidth() < $width) {
                 return FALSE;
             }
             if ($height !== NULL && $image->getHeight() < $height) {
                 return FALSE;
             }
             break;
         case static::DIMENSIONS_MAXIMAL:
             if ($width !== NULL && $image->getWidth() > $width) {
                 return FALSE;
             }
             if ($height !== NULL && $image->getHeight() > $height) {
                 return FALSE;
             }
             break;
     }
     return TRUE;
 }
Esempio n. 5
0
 public function actionImage()
 {
     if (substr($this->url, 0, 7) === '_cache/') {
         $this->cached = TRUE;
         $this->url = substr($this->url, 7);
     }
     if (($entity = $this->fileRepository->findOneBy(array('path' => $this->url))) === NULL) {
         throw new \Nette\Application\BadRequestException("File '{$this->url}' does not exist.");
     }
     $image = Image::fromFile($entity->getFilePath());
     // resize
     if ($this->size && $this->size !== 'default') {
         if (strpos($this->size, 'x') !== FALSE) {
             $format = explode('x', $this->size);
             $width = $format[0] !== '?' ? $format[0] : NULL;
             $height = $format[1] !== '?' ? $format[1] : NULL;
             $image->resize($width, $height, $this->format !== 'default' ? $this->format : Image::FIT);
         }
     }
     if (!$this->type) {
         $this->type = substr($entity->getName(), strrpos($entity->getName(), '.'));
     }
     $type = $this->type === 'jpg' ? Image::JPEG : $this->type === 'gif' ? Image::GIF : Image::PNG;
     $file = $this->context->parameters['wwwDir'] . "/public/media/_cache/{$this->size}/{$this->format}/{$this->type}/{$entity->getPath()}";
     $dir = dirname($file);
     umask(00);
     @mkdir($dir, 0777, TRUE);
     $image->save($file, 90, $type);
     $image->send($type, 90);
 }
Esempio n. 6
0
	/**
	 * Outputs image to browser.
	 * @param  int  image type
	 * @param  int  quality 0..100 (for JPEG and PNG)
	 * @return bool TRUE on success or FALSE on failure.
	 */
	public function send($type = self::JPEG, $quality = NULL)
	{
		if (is_string($type)) {
			$type = self::extToType($type);
		}

		return parent::send($type, $quality);
	}
Esempio n. 7
0
 protected function render($code, $x, $y, $method)
 {
     $file = $this->items->where('code', $code)->fetch();
     $this->sourcepath = FILESTORAGE_DIR . '/' . $file->filepath;
     $this->cachepath = TEMP_DIR . '/imagecache/' . $file->id;
     $this->imagepath = $this->cachepath . '/' . $method . "-" . $x . "x" . $y . '.' . $file->filename;
     $expires = 60 * 60 * 24 * 31;
     $etag = '"' . md5($this->imagepath) . '"';
     if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == $etag) {
         header('HTTP/1.1 304 Not Modified');
         header('Content-Length: 0');
         exit;
     }
     header('ETag: ' . $etag);
     header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
     header("Pragma: public");
     // required
     header("Cache-Control: maxage=" . $expires);
     header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT');
     header("Cache-Control: cache");
     header("Cache-Control: private", false);
     // required for certain browsers
     header("Content-Transfer-Encoding: binary");
     if (!file_exists($this->imagepath) || $file->changed > $file->created) {
         try {
             if (file_exists($this->sourcepath)) {
                 $image = Image::fromFile($this->sourcepath);
             } else {
                 $image = Image::fromBlank($x, $y, array('red' => 240, 'green' => 240, 'blue' => 240));
             }
             @$image->resize($x, $y, $method);
             $image->sharpen();
             if ($method == 5) {
                 $image->crop(0, 0, $x, $y);
             }
             if (!file_exists($this->cachepath)) {
                 mkdir($this->cachepath, 0777, true);
                 chmod($this->cachepath, 0777);
             }
             if (file_exists($this->sourcepath)) {
                 $image->save($this->imagepath, 66, Image::JPEG);
             } else {
                 $image->string(2, 5, $y / 2 - 7, 'No image found', 1);
             }
             $image->send();
         } catch (Exception $e) {
         }
     } else {
         header('Content-Disposition: inline; filename="' . $this->imagepath . '"');
         header("Content-Type: image/jpeg");
         header("Content-Length: " . @filesize($this->imagepath));
         readfile($this->imagepath);
     }
 }
Esempio n. 8
0
 public function __construct($parent, $name)
 {
     parent::__construct($parent, $name);
     $this->media = $this->lookup('Bubo\\Media');
     $dimensions = $this->addContainer('dimensions');
     //        $fileDirPath = $this->presenter->mediaManagerService->getOriginalFileDirPath($this->parent->id);
     //        $filePath = $this->presenter->mediaManagerService->getBaseDir() . '/' . $fileDirPath;
     //        $im = Image::fromFile($filePath);
     $file = $this->presenter->mediaManagerService->loadFile($this->parent->id);
     $paths = $file->getPaths();
     $im = Image::fromFile($paths['dirPaths'][0]);
     $dimensions->addText('width')->setDefaultValue($im->getWidth());
     $dimensions->addText('height')->setDefaultValue($im->getHeight());
     $insertionMethods = $this->getInsertionMethods();
     $this->addSelect('insertionMethod', 'Vložit jako', $insertionMethods);
     $subForms = $this->getSubformsData();
     foreach ($subForms as $key => $subForm) {
         if ($subForm !== NULL) {
             $_subForm[$key] = $this->addContainer('subform_' . $key);
             foreach ($subForm as $subFormComponentName => $subFormComponent) {
                 switch ($subFormComponent['control']) {
                     case 'text':
                         $_subForm[$key]->addText($subFormComponentName, $subFormComponent['title']);
                         break;
                     case 'checkbox':
                         $_subForm[$key]->addCheckbox($subFormComponentName, $subFormComponent['title']);
                         if (isset($subFormComponent['default'])) {
                             $_subForm[$key][$subFormComponentName]->setDefaultValue($subFormComponent['default']);
                         }
                         break;
                 }
             }
         }
     }
     $this->addHidden('fileId', $this->parent->id);
     $dimensions['width']->getControlPrototype()->class = 'itemWidth';
     $dimensions['height']->getControlPrototype()->class = 'itemHeight';
     $this->addSubmit('send', 'Uložit');
     //        $this->addHidden('editor_id', $editorId);
     //        $this->addHidden('parent', $fid);
     //        $this->addHidden('id', false);
     $this->onSuccess[] = array($this, 'formSubmited');
     $this->getElementPrototype()->class = 'ajax media-image-setting-form';
     if ($this->media->getParam('formValues') !== NULL) {
         $defaults = json_decode($this->media->getParam('formValues'), TRUE);
         if ($defaults) {
             $this->setDefaults($defaults);
         }
     }
     //$this['send']->getControlPrototype()->class = "submit";
 }
Esempio n. 9
0
 public function createThumbnail($path, $width, $height, $type = 'normal')
 {
     $key = md5($path . "|" . filemtime($path) . "|" . $width . "|" . $height . "|" . $type) . ".jpg";
     if (!$this->repository->exist($key)) {
         $image = Image::fromFile($path);
         if ($type == 'normal') {
             $image = $image->resize($width, $height);
         } else {
             $image = $image->resize($width, $height, Image::FILL)->crop("50%", "25%", $width, $height);
         }
         $this->repository->save((string) $image, $key);
     }
     return $this->repository->getPath($key);
 }
Esempio n. 10
0
 /**
  * @param $text
  * @return string
  */
 public function run($file, $width, $height = NULL, $flags = NULL, $crop = NULL)
 {
     if (!$width && !$height) {
         return $file;
     }
     if (!$width) {
         $width = NULL;
     }
     if (!$height) {
         $height = NULL;
     }
     // paths
     $filePath = $this->container->parameters["wwwDir"] . "/" . $file;
     $thumbName = self::getThumbName($file, $width, $height, filemtime($filePath), $flags, $crop);
     $cacheDir = $this->container->parameters["wwwCacheDir"] . "/thumbs";
     $relativeCacheDir = str_replace($this->container->parameters["wwwDir"], "", $cacheDir);
     $relativeFilePath = substr($relativeCacheDir, 1) . "/" . $thumbName;
     $thumbPath = $cacheDir . "/" . $thumbName;
     // image exists
     if (file_exists($thumbPath)) {
         return $relativeFilePath;
     }
     // resize
     try {
         $image = Image::fromFile($filePath);
         // Transparency
         $image->alphaBlending(FALSE);
         $image->saveAlpha(TRUE);
         $origWidth = $image->getWidth();
         $origHeight = $image->getHeight();
         $image->resize($width, $height, $flags);
         $image->sharpen();
         $newWidth = $image->getWidth();
         $newHeight = $image->getHeight();
         if ($crop) {
             $image->crop('50%', '50%', $width, $height);
         }
         if ($newWidth !== $origWidth || $newHeight !== $origHeight) {
             $image->save($thumbPath);
             if (is_file($thumbPath)) {
                 return $relativeFilePath;
             }
         }
     } catch (\Exception $e) {
     }
     return $file;
 }
Esempio n. 11
0
	public static function createThumbnail(HtmlImage $image, $width, $height, $flags = Image::FIT)
	{
		$root = self::$thumbnailDir ?: TEMP_DIR . "/webtemp";

		$path = $image->getFilePath();
		$fileName = "thumb-" . md5($path . filemtime($path) . $flags) . "-" . $width . "x" . $height . ".jpg";
		$thumbPath = $root . "/" . $fileName;

		if (!file_exists($thumbPath)) {
			Image::fromFile($path)->resize($width, $height, $flags)->save($thumbPath);
		}

		$thumb = new HtmlImage($thumbPath);
		$thumb->setAlt($image->getAlt());

		return $thumb;
	}
 public function renderSave($id)
 {
     $files = $this->request->getFiles();
     $post = $this->request->getPost();
     foreach ($files['img'] as $file) {
         if ($file->isImage() && $file->isOk()) {
             $file_ext = strtolower(mb_substr($file->getSanitizedName(), strrpos($file->getSanitizedName(), ".")));
             $file_name = uniqid(rand(0, 20), TRUE);
             $whole_path = $this->getImageDirectory($this->params['parent_page_id']) . $file_name . $file_ext;
             $file->move($whole_path);
             // main image:
             $image = \Nette\Image::fromFile($whole_path);
             if ($image->getWidth() > $this->main_img_max_width) {
                 $image->resize($this->main_img_max_width, $this->main_img_max_height);
             }
             $image->sharpen();
             $image->save($whole_path);
             // thumb image:
             $image_thumb = \Nette\Image::fromFile($whole_path);
             // resize image to be smaller:
             if ($image_thumb->getWidth() > $this->thumb_img_max_width) {
                 $image_thumb->resize($this->thumb_img_max_width, NULL);
             }
             // resize to square:
             if ($image_thumb->getHeight() > $this->thumb_img_max_height) {
                 // calculate TOP coordinate to fit square to the middle of the image
                 $top = ($image_thumb->getHeight() - $this->thumb_img_max_height) / 2;
                 $image_thumb->crop(0, $top, $this->thumb_img_max_width, $this->thumb_img_max_height);
             }
             $image_thumb->sharpen();
             $image_thumb->save($this->getImageDirectory($this->params['parent_page_id']) . $file_name . "_t" . $file_ext);
             $data['page_page_modules_id'] = $id;
             $data['name'] = $file_name;
             $data['extension'] = ltrim($file_ext, ".");
             $data['description'] = $post['description'];
             $data['enabled'] = 1;
             $data['order'] = $this->context->moduleImageGaleryModel->findBy(array("page_page_modules_id" => $id))->count() + 1;
             $this->context->moduleImageGaleryModel->insert($data);
             $this->flashMessage('Soubor \'' . $file->name . '\' byl nahrán.');
         } else {
             $this->flashMessage('Soubor \'' . $file->name . '\' se nepodařilo nahrát, error: ' . $file->error, 'danger');
         }
     }
     $this->redirect('Page:edit', array('id' => $this->params['parent_page_id']));
 }
 private function uploadOneImage()
 {
     $files = $this->request->getFiles();
     $file = $files['img'];
     $file_name = NULL;
     if (isset($file) && $file->isImage() && $file->isOk()) {
         $file_ext = strtolower(mb_substr($file->getSanitizedName(), strrpos($file->getSanitizedName(), ".")));
         $file_name = uniqid(rand(0, 20), TRUE) . $file_ext;
         $file->move($this->getImageDirectory($this->module->id) . $file_name);
         $image = \Nette\Image::fromFile($this->getImageDirectory($this->module->id) . $file_name);
         if ($image->getWidth() > 1200) {
             $image->resize(1200, NULL);
         }
         $image->sharpen();
         $image->save($this->getImageDirectory($this->module->id) . $file_name);
     }
     return $file_name;
 }
Esempio n. 14
0
 public function processImageForm(Form $form)
 {
     // uklada fotky
     if ($form->isSubmitted()) {
         $uploaded = 0;
         $dirPath = $this->dirPath;
         for ($i = 1; $i <= $this->uploadCount; $i++) {
             $file = $form['file' . $i]->getValue();
             if (empty($file)) {
                 $this->flashMessage('Nebyl vybrán žádný soubor nebo byl datově příliš velký.', 'warning');
             } elseif ($file->isOK()) {
                 if ($file->getContentType() == 'image/jpeg' || $file->getContentType() == 'image/jpg' || $file->getContentType() == 'image/png') {
                     $tmp = WWW_DIR . '/images/tmp/img.jpg';
                     $file->move($tmp);
                     $filename = $this->uploadingHelper();
                     $image = Image::fromFile($tmp);
                     if ($this->imageSizes['x']) {
                         $image->resize($this->imageSizes['x'], $this->imageSizes['y'], Image::SHRINK_ONLY);
                     }
                     $image->save($dirPath . $filename, 85, Image::JPEG);
                     $imageBig = Image::fromFile($tmp);
                     if ($this->imageSizes['xBig']) {
                         $imageBig->resize($this->imageSizes['xBig'], $this->imageSizes['yBig'], Image::SHRINK_ONLY);
                     }
                     $imageBig->save($dirPath . 'big/' . $filename, 85, Image::JPEG);
                     $uploaded++;
                 } else {
                     $this->flashMessage('Soubor není v požadovaném formátu.', 'warning');
                 }
             }
         }
     }
     if ($uploaded > 0) {
         $this->flashMessage($uploaded . ' obrázků bylo úspěšně nahráno.', 'success');
     } else {
         $this->flashMessage('Nahráno 0 souborů.');
     }
     $this->redirect('this');
 }
Esempio n. 15
0
 /**
  * @param array $report See ScreenshotMaker::$report
  */
 public function generate(array $report)
 {
     foreach (Finder::findFiles('*.png')->in($this->outDir) as $image) {
         /** @var \SplFileInfo $image */
         $blank = Image::fromBlank(120, 120, array('green' => 255, 'blue' => 255, 'red' => 255));
         $blank->place(Image::fromFile($image->getPathname())->resize(120, 120));
         $blank->save(dirname($image->getPathname()) . '/' . $image->getBasename('.png') . '.thumb.png');
     }
     $tpl = new Nette\Templating\FileTemplate(__DIR__ . '/../templates/report.latte');
     $tpl->registerFilter(new Nette\Latte\Engine());
     $tpl->registerHelperLoader('Nette\\Templating\\Helpers::loader');
     $tpl->registerHelper('resultName', function ($result) {
         static $names = array(StepEvent::PASSED => 'passed', StepEvent::SKIPPED => 'skipped', StepEvent::PENDING => 'pending', StepEvent::UNDEFINED => 'undefined', StepEvent::FAILED => 'failed');
         return isset($names[$result]) ? $names[$result] : '[unknown]';
     });
     $tpl->registerHelper('resultClass', function ($result) {
         static $names = array(StepEvent::PASSED => 'passed', StepEvent::SKIPPED => 'skipped', StepEvent::PENDING => 'pending', StepEvent::UNDEFINED => 'undefined', StepEvent::FAILED => 'failed');
         return isset($names[$result]) ? $names[$result] : '[unknown]';
     });
     // render
     $tpl->report = $report;
     file_put_contents($this->outDir . '/index.html', $tpl->__toString());
 }
Esempio n. 16
0
 /**
  * Pre-processing HTML obtained from CKEditor
  *
  * @param Form $form
  */
 public function save(Form $form)
 {
     $values = $form->getValues();
     $html = new Html();
     $html->setHtml($values['editor']);
     foreach ($html->getImages() as $image) {
         list($width, $height) = $image->getDimensionsFromStyle();
         $newFilename = substr($image->getSrc()->getFilename(), 0, strrpos($image->getSrc()->getFilename(), '.')) . "[{$width}x{$height}]" . substr($image->getSrc()->getFilename(), strrpos($image->getSrc()->getFilename(), '.'));
         $newSrc = $image->getSrc()->getPathinfo()->getPath() . '/' . self::TEMP_DIR_NAME . '/' . $newFilename;
         $imFile = realpath($this->publicDir . DIRECTORY_SEPARATOR . $image->getSrc()->getFilename());
         if ($imFile !== FALSE) {
             $im = Image::fromFile($imFile);
             // TODO: resize only if image is larger than real dimensions
             $im->resize($width, $height);
             if ($im->save($this->tempDir . DIRECTORY_SEPARATOR . $newFilename)) {
                 $image->setSrc($newSrc);
             }
         }
     }
     $values['editor'] = $html->getHtml();
     $form->setValues($values, TRUE);
     $this->onSuccess($form);
 }
Esempio n. 17
0
 public function createComponentRegisterForm($name)
 {
     $form = new Form($this, $name);
     $form->onSuccess[] = callback($this, $name . 'Submitted');
     $login = $this->getContext()->config->get('user.login');
     $form->addText('name', 'Jméno')->setRequired('Prosím vyplňte své jméno');
     $form->addText('surname', 'Přijímení')->setRequired('Prosím vyplňte své přijímení');
     if ($login === 'username') {
         $form->addText('username', 'Uživatelské jméno:')->setRequired('Prosím vyplňte své uživatelské jméno.');
     }
     // we want the email anyway...
     $form->addText('email', 'E-mail:')->addRule(Form::EMAIL, 'Prosím vyplňte validní emailovou adresu.')->setRequired('Prosím vyplňte svou emailovou adresu.');
     $form->addPassword('password', 'Heslo:')->setRequired('Prosím vyplňte své heslo')->addRule(Form::MIN_LENGTH, 'Vaše heslo musí být dlouhé nejméně %d znaků.', $this->context->config->get('security.password.minLength', 6));
     $form->addPassword('passwordCheck', 'Heslo znovu pro kontrolu:')->setRequired('Prosím vyplňte své druhé helso pro kontrolu.')->addRule(Form::EQUAL, 'Vyplněná hesla se neshodují', $form['password']);
     $form->addCheckbox('newsletter', 'Mám zájem o pravidelné zasílání novinek')->setDefaultValue(true);
     \PavelMaca\Captcha\CaptchaControl::register();
     $form['captcha'] = new \PavelMaca\Captcha\CaptchaControl();
     $form['captcha']->caption = 'Security code:';
     $form['captcha']->setTextColor(Nette\Image::rgb(48, 48, 48));
     $form['captcha']->setBackgroundColor(Nette\Image::rgb(232, 234, 236));
     $form['captcha']->setRequired('Prosím opište bezpečnostní kód z obrázku');
     $form['captcha']->addRule($form["captcha"]->getValidator(), 'Bezpečnostní kód se neshoduje. Prosím zkuste to znovu.');
     $form->addSubmit('s', 'Registrovat!');
 }
Esempio n. 18
0
 public function loadImages($folderBasePath, $images, $mode)
 {
     $modes = $this->parseModes($mode);
     foreach ($modes as $_mode) {
         $thumbDir = $this->mediaManager->getBaseDir() . '/' . $folderBasePath . '/' . $_mode;
         $this->createFolder($folderBasePath . '/' . $_mode);
         foreach ($images as $image) {
             $filepath = $thumbDir . '/' . $image['filename'];
             if (!is_file($filepath)) {
                 // try to create thumbnail
                 $originalImagePath = $this->mediaManager->getBaseDir() . '/' . $folderBasePath . '/originals/' . $image['filename'];
                 $params = $this->_parseMode($_mode);
                 $_image = Image::fromFile($originalImagePath);
                 $this->createThumbnail($_image, $originalImagePath, $params);
                 $_image->save($filepath);
             }
         }
     }
     return TRUE;
 }
Esempio n. 19
0
 /**
  * Puts another image into this image.
  * @param  Image
  * @param  mixed  x-coordinate in pixels or percent
  * @param  mixed  y-coordinate in pixels or percent
  * @param  int  opacity 0..100
  * @return Image  provides a fluent interface
  */
 public function place(Image $image, $left = 0, $top = 0, $opacity = 100)
 {
     $opacity = max(0, min(100, (int) $opacity));
     if (substr($left, -1) === '%') {
         $left = round(($this->getWidth() - $image->getWidth()) / 100 * $left);
     }
     if (substr($top, -1) === '%') {
         $top = round(($this->getHeight() - $image->getHeight()) / 100 * $top);
     }
     if ($opacity === 100) {
         imagecopy($this->getImageResource(), $image->getImageResource(), $left, $top, 0, 0, $image->getWidth(), $image->getHeight());
     } elseif ($opacity != 0) {
         imagecopymerge($this->getImageResource(), $image->getImageResource(), $left, $top, 0, 0, $image->getWidth(), $image->getHeight(), $opacity);
     }
     return $this;
 }
Esempio n. 20
0
	/**
	 * Saves image to the file.
	 * @param  string  filename
	 * @param  int  quality 0..100 (for JPEG and PNG)
	 * @param  int  optional image type
	 * @return bool TRUE on success or FALSE on failure.
	 */
	public function save($file = NULL, $quality = NULL, $type = NULL)
	{
		if ($this->file === NULL) {
			return parent::save($file, $quality, $type);
		}

		$quality = $quality === NULL ? '' : '-quality ' . max(0, min(100, (int) $quality));
		if ($file === NULL) {
			$this->execute("convert $quality -strip %input %output", $type === NULL ? self::PNG : $type);
			readfile($this->file);

		} else {
			$this->execute("convert $quality -strip %input %output", (string) $file);
		}
		return TRUE;
	}
Esempio n. 21
0
 private function upload($files)
 {
     foreach ($files as $file) {
         if ($file->isImage() && $file->isOk()) {
             $fileExtension = strtolower(mb_substr($file->getSanitizedName(), strrpos($file->getSanitizedName(), ".")));
             if (NULL === $this->newFileName) {
                 $this->newFileName = uniqid(rand(0, 20), TRUE);
             }
             $wholePath = $this->baseDir . $this->newFileName . $fileExtension;
             $file->move($wholePath);
             // resize main image:
             if ($this->resize) {
                 $image = \Nette\Image::fromFile($wholePath);
                 if ($image->getWidth() > $this->maxWidth) {
                     $image->resize($this->maxWidth, $this->maxHeight);
                 }
                 $image->sharpen();
                 $image->save($wholePath);
             }
             // thumbnail image if needed:
             if (true === $this->createThumbnails) {
                 $this->createThumbnail($wholePath, $this->baseDir . $this->newFileName . "_t" . $fileExtension, $this->thumbnailMaxWidth, $this->thumbnailMaxHeight, true);
             }
             $this->result[] = array("name" => $this->newFileName, "extension" => $fileExtension, "original" => $file->name);
             $this->newFileName = NULL;
         } else {
             $this->result[] = array("error" => $file->error, "original" => $file->name);
         }
     }
 }
Esempio n. 22
0
 function toImage()
 {
     return Nette\Image::fromFile($this->tmpName);
 }
 public function renderDefault($id, $width = "", $height = "", $format = null, $crop = null)
 {
     if (!empty($width) && !preg_match('/^\\d+$/', $width)) {
         $this->terminate();
     }
     if (!empty($height) && !preg_match('/^\\d+$/', $height)) {
         $this->terminate();
     }
     if ($width > 2000 || $height > 2000) {
         $this->reminate();
     }
     if (!in_array($format, array("jpg", "jpeg", "png"))) {
         $this->terminate();
     }
     if (!empty($crop)) {
         $crop = true;
     } else {
         $crop = false;
     }
     $image = $this->upload->get($id);
     $filename = THUMBS_DIR;
     if (!empty($width)) {
         $filename .= "/w" . $width;
     }
     if (!empty($height)) {
         $filename .= "/h" . $height;
     }
     if ($crop) {
         $filename .= "/crop";
     }
     if (!file_exists($filename)) {
         mkdir($filename, 0755, true);
     }
     $filename .= "/" . $id . "." . $format;
     $inputfile = UPLOAD_DIR . "/" . $image['id'] . "." . $image["extension"];
     if (!file_exists($inputfile)) {
         throw new \Nette\Application\BadRequestException();
     }
     try {
         $img = \Nette\Image::fromFile($inputfile);
     } catch (\Nette\Utils\UnknownImageFileException $e) {
         throw new \Nette\Application\BadRequestException();
     }
     if (!empty($width) && !empty($height)) {
         if (!empty($crop)) {
             if ($img->getHeight() / $img->getWidth() > $height / $width) {
                 $img->resize($width, null);
                 $img->crop(0, ($img->getHeight() - $height) / 2, $width, $height);
             } else {
                 $img->resize(null, $height);
                 $img->crop(($img->getWidth() - $width) / 2, 0, $width, $height);
             }
         } else {
             $img->resize($width, $height);
         }
     } elseif (!empty($width)) {
         $img->resize($width, null);
     } elseif (!empty($height)) {
         $img->resize(null, $height);
     }
     $img->save($filename);
     $img->send();
     $this->terminate();
 }
Esempio n. 24
0
 /**
  * @return void
  */
 protected function createThumb()
 {
     $image = Nette\Image::fromFile($this->src);
     $image->resize($this->width, $this->height, $this->crop ? Nette\Image::EXACT : Nette\Image::FIT);
     $image->save($this->desc);
 }
Esempio n. 25
0
        $this["produktEditForm"]->setDefaults(array("id_lang" => 1));
        $this->setView("edit");
    }
    /** Akcia pre editaciu produktu.
   * @param int $id Id produktu
   * @param int $id_hlavne_menu Id hlavneho menu
   * @param string $back_edit_link Nazov presentera pre presmerovanie po editacii
   */
    public function actionEdit($id, $id_hlavne_menu, $back_edit_link)
    {
        if (isset($id) && $id) {
            $produkt = $this->produkt_lang->find($id)->toArray();
            $produkt["heating_time"] = ($produkt["heating_time"]->h < 10 ? "0" : "") . $produkt["heating_time"]->h . ":" . ($produkt["heating_time"]->i < 10 ? "0" : "") . $produkt["heating_time"]->i;
            $this["produktEditForm"]->setDefaults($produkt);
            $this->id_hlavne_menu = isset($id_hlavne_menu) ? (int) $id_hlavne_menu : 0;
            if (isset($back_edit_link)) {
                $this->back_edit_link = $back_edit_link;
            }
        }
    }
    /** Formular pre editaciu hodnot produktu.
	 * @return Nette\Application\UI\Form
	 */
    public function createComponentProduktEditForm()
    {
        $outDir = 'http://' . $this->nazov_stranky . '/www/images/icon_';
        for ($i = 1; $i <= 3; $i++) {
            $iko[$i] = Html::el('img', array('class' => 'ikonkySmall'))->src($outDir . $i . '_s.jpg');
        }
        $form = $this->formProdukt->create($iko, $this->upload_size);
        $form->onSuccess[] = $this->produktEditFormSubmitted;
        return $form;
    }
    /** Spracovanie formulara pre editaciu hodnot produktu.
   * @param Nette\Application\UI\Form $form Hodnoty formulara
   */
    public function produktEditFormSubmitted($form)
    {
        $values = $form->getValues();
        //Nacitanie hodnot formulara
        $id_pol = (int) $values->id;
        // Ak je == 0 tak sa pridava
        unset($values->id);
        if ($id_pol == 0) {
            //Ak sa pridava
            if ($this->produkt_lang->findOneBy(array("nazov" => $values->nazov)) !== FALSE) {
                //kontroluj existenciu názvu
                $this->flashMessage('Zadali ste už existujúci názov produktu! Prosím, zvolte iný!', 'danger');
                return;
            } else {
                $values->spec_nazov = $this->_najdiSpecNazov($values->nazov, 'produkt_lang');
                //tak nastav specificky nazov
            }
        }
        //Uprav vystupy pre ulozenie
        //1. pre int a tiny int
        foreach (array("bottom_plinth_weight", "forewood_lenght", "firewood_lenght", "efficiency") as $k) {
            if (isset($values->{$k}) && (int) $values->{$k} == 0) {
                $values->{$k} = NULL;
            }
        }
        //2. pre time
        if (isset($values->heating_time) && $values->heating_time == "00:00") {
            $values->heating_time = NULL;
        }
        //3. pre float
        foreach (array("heating_occasion", "nominal_heat_output", "nominal_heat_time", "heat_release_time100", "heat_release_time50", "heat_release_time25") as $k) {
            if (isset($values->{$k})) {
                $values->{$k} = (double) $values->{$k} == 0 ? NULL : str_replace(",", ".", $values->{$k});
            }
        }
        if ($values->title_image && $values->title_image->name != "") {
            if ($values->title_image->isImage()) {
                $pi = pathinfo($values->title_image->getSanitizedName());
                $image_name = $this->produkt_path . "/thumbs/" . $values->spec_nazov . "." . $pi['extension'];
Esempio n. 26
0
 /**
  * Get min size
  *
  * @param Newscoop\Image\ImageInterface $image
  * @return array
  */
 public function getMinSize(ImageInterface $image)
 {
     list($width, $height) = NetteImage::calculateSize($image->getWidth(), $image->getHeight(), $this->width, $this->height, $this->getFlags());
     $ratio = max($width / (double) $image->getWidth(), $height / (double) $image->getHeight());
     return array($this->width, $this->height);
 }
Esempio n. 27
0
in_array($this->getContentType(),array('image/gif','image/png','image/jpeg'),TRUE);}function
toImage(){return
Nette\Image::fromFile($this->tmpName);}function
Esempio n. 28
0
 /**
  * Returns the image.
  * @return \Nette\Image
  */
 public function toImage()
 {
     return Nette\Image::fromFile($this->file);
 }
Esempio n. 29
0
<?php

use Nette\Image;
require_once dirname(__FILE__) . '/../../libs/nette.php';
require_once dirname(__FILE__) . '/paths.php';
try {
    $src = get_magic_quotes_gpc() ? stripslashes($_POST["image"]) : $_POST["image"];
    $image = Image::fromFile(FILES_BASE_PATH . "/" . $src);
    $image->resize(60, 40);
    $image->send();
} catch (Exception $e) {
    header('Content-Type: image/gif');
    echo Image::EMPTY_GIF;
}
Esempio n. 30
0
 public function resizeAndSaveImage($imagePath, $dimensions, $cutToFit = false)
 {
     // first check on s3 service
     if (!$this->awsService->isFile($imagePath)) {
         return array($imagePath, null, null);
     }
     $info = pathinfo($imagePath);
     $imageDir = $info['dirname'] . '/';
     $imageName = basename($imagePath);
     ////////////////////////////////////////
     // read dimensions
     ////////////////////////////////////////
     $dim = explode('x', $dimensions);
     $newWidth = isset($dim[0]) ? $dim[0] : null;
     $newHeight = isset($dim[1]) ? $dim[1] : null;
     try {
         $resizedImageName = Strings::webalize(basename($imagePath, '.' . $info['extension'])) . '-' . $newWidth . 'x' . $newHeight . '.' . $info['extension'];
         $resizedImagePath = $imageDir . $resizedImageName;
         // check if resized image is already on s3, if yes, return, if not, generate and save
         if ($this->awsService->isFile($resizedImagePath)) {
             $resizedImagePath = $this->baseUrl . $resizedImagePath;
             $result = array($resizedImagePath, $newWidth, $newHeight);
             return $result;
         }
         // need to download the original image and convert the sizes
         $tempImagePath = $this->tempDir . $imageName;
         // download image from s3 to temporary directory
         $this->awsService->downloadFile($imagePath, $tempImagePath);
         // load and resize image
         $image = Image::fromFile($tempImagePath);
         if ($cutToFit) {
             if ($image->height > $image->width) {
                 $image->resize($newWidth, $newHeight, Image::FILL);
                 $image->sharpen();
                 $blank = Image::fromBlank($newWidth, $newHeight, Image::rgb(255, 255, 255));
                 $blank->place($image, 0, '20%');
                 $image = $blank;
             } else {
                 $image->resize($newWidth, $newHeight, Image::FILL | Image::EXACT);
                 $image->sharpen();
             }
         } else {
             $image->resize((int) $newWidth, (int) $newHeight, Image::SHRINK_ONLY);
             $image->sharpen();
         }
         // generate new image
         $image->save($tempImagePath, 85);
         // 85% quality
         // upload file to s3 storage
         $this->awsService->uploadFile($tempImagePath, $resizedImagePath);
         $result = array($this->baseUrl . $resizedImagePath, $image->width, $image->height);
         // free memory
         $image = null;
         unset($image);
         // remove temporary file
         if (file_exists($tempImagePath)) {
             unlink($tempImagePath);
         }
         return $result;
     } catch (\Exception $e) {
         //$this->logger->logError($e);
         return array($this->baseUrl . $imagePath, null, null);
     }
 }