/** * 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; } }
/** * 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; }
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); }
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; } }
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); } }
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"; }
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); }
/** * @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; }
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; }
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'); }
/** * @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()); }
/** * 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); }
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; }
private function createThumb($originalFile, $targetPath, $type) { $resizeType = false; if (!Strings::contains($type, '_')) { $sizes = $type; } else { list($sizes, $resizeType) = explode('_', $type); } list($width, $height) = explode('x', $sizes); $image = Image::fromFile($originalFile); $image->resize($width, $height, $this->getResizeType($resizeType)); $image->save($targetPath, $this->imageQuality, Image::JPEG); return $targetPath; }
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(); }
/** * @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); }
public function copyAndResize($from, $to, $name, $resize) { //$this->copy($from.$name, $to.$name); if (is_array($resize) && (isset($resize['width']) || isset($resize['height'])) && file_exists($from . $name)) { if ($resize['method'] == 'MAX_WIDTH') { $resize['height'] = NULL; $resize['method'] = Image::FIT; } if ($resize['method'] == 'MAX_HEIGHT') { $resize['width'] = NULL; $resize['method'] = Image::FIT; } $crop = false; switch (strtoupper($resize['method'])) { case 'FILL': $resize['method'] = Image::FILL; break; case 'STRETCH': $resize['method'] = Image::STRETCH; break; case 'SHRINK_ONLY': $resize['method'] = Image::SHRINK_ONLY; break; case 'ENLARGE': $resize['method'] = Image::ENLARGE; break; case 'EXACT': $resize['method'] = Image::EXACT; break; case 'CROP': $crop = true; break; default: $resize['method'] = Image::FIT; } $img = Image::fromFile($from . $name); if ($crop) { list($w, $h) = getimagesize($from . $name); if ($w > $resize['width'] && $h > $resize['height']) { $img->resize($resize['width'], $resize['height'], Image::FILL); $img->crop('50%', '50%', $resize['width'], $resize['height']); } } else { $img->resize($resize['width'], $resize['height'], $resize['method']); $img->sharpen(); } $img->save($to . $name, 90); } }
/** * Generate image * * @param string $imagePath * @return Nette\Image */ public function generateImage($imagePath) { $path = is_file(APPLICATION_PATH . '/../' . $imagePath) ? APPLICATION_PATH . '/../' . $imagePath : $imagePath; $image = NetteImage::fromFile($path); $image->alphaBlending(false); $image->saveAlpha(true); if ($this->isCrop()) { $cropSpecs = explode('_', $this->getSpecs()); if (count($cropSpecs) === 1) { $image->resize($this->width, $this->height, $this->getFlags()); $image->crop('50%', '50%', $this->width, $this->height); } else { list(, $x0, $y0, $x1, $y1) = $cropSpecs; $image->crop($x0, $y0, $x1 - $x0, $y1 - $y0); $image->resize($this->width, $this->height, $this->getFlags()); } } else { $image->resize($this->width, $this->height, $this->getFlags()); } return $image; }
/** * Genarate and show preview of the image in file browser * @param string $key */ public function actionThumbnail($key) { try { $path = $this->baseFolderPath . "/" . $key; $image = Image::fromFile($path)->resize(60, 40); $image->save($this->tempDir . "/" . $this->thumbnailFileName($path)); @chmod($path, 0666); $image->send(); } catch (Exception $e) { Image::fromString(Image::EMPTY_GIF)->send(Image::GIF); } $this->terminate(); }
in_array($this->getContentType(),array('image/gif','image/png','image/jpeg'),TRUE);}function toImage(){return Nette\Image::fromFile($this->tmpName);}function
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); } }
private function _createTinyPlaceholderForGallery($galleryId, $fontFile, $fontSize) { $config = $this->getConfig(); $pattern = $config['tinyPlaceholderPattern']; $placeholderFilename = sprintf($pattern, $galleryId); $placeholderFilePath = $this->getTempDir() . '/' . $placeholderFilename; if (!is_file($placeholderFilePath)) { // create placeholder $folder = $this->getFolder($galleryId); $filename = $this->getGalleryIconPath($galleryId); $image = Nette\Image::fromFile($filename); $blank = Nette\Image::fromBlank(350, 100, Nette\Image::rgb(220, 220, 220)); $blank->place($image, 8, 8); $rgb = $blank->rgb(0, 0, 0); $imageResource = $blank->getImageResource(); $color = imagecolorallocatealpha($imageResource, $rgb['red'], $rgb['green'], $rgb['blue'], $rgb['alpha']); $x = 100; $y = 8 + $fontSize; $text = 'Galerie'; imagettftext($imageResource, $fontSize, 0, $x, $y, $color, $fontFile, $text); $x = 100; $y = 8 + 3 * $fontSize; $text = $folder['name']; imagettftext($imageResource, $fontSize, 0, $x, $y, $color, $fontFile, $text); $resultImage = new Nette\Image($imageResource); $resultImage->save($placeholderFilePath); } return $this->getTempPath() . '/' . $placeholderFilename; }
/** * Returns the image. * @return \Nette\Image */ public function toImage() { return Nette\Image::fromFile($this->file); }
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); } } }
<?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; }
$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'];