/** * @inheritdoc */ public function run() { if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); if (!empty($post['method'])) { $file = basename($post['file']); if (file_exists($this->getPath() . $file)) { unlink($this->getPath() . $file); } } else { $image = \yii\web\UploadedFile::getInstanceByName('upload'); if (!empty($image)) { $imageFileType = strtolower(pathinfo($image->name, PATHINFO_EXTENSION)); $allowed = ['png', 'jpg', 'gif', 'jpeg']; if (!empty($image) and in_array($imageFileType, $allowed)) { $fileName = $this->getFileName($image); $image->saveAs($this->getPath() . $fileName); $imagine = Image::getImagine(); $photo = $imagine->open($this->getPath() . $fileName); $photo->thumbnail(new Box($this->maxWidth, $this->maxHeight))->save($this->getPath() . $fileName, ['quality' => 90]); } } } } $data['url'] = $this->getUrl(); $data['path'] = $this->getPath(); $data['ext'] = $this->getFileExt(); BrowseAssets::register($this->controller->view); $this->controller->layout = '@vendor/bajadev/yii2-ckeditor/views/layout/image'; return $this->controller->render('@vendor/bajadev/yii2-ckeditor/views/browse', ['data' => $data]); }
/** * fetch image from protected location and manipulate it and copy to public folder to show in front-end * This function cache the fetched image with same width and height before * * @author A.Jafaripur <*****@*****.**> * * @param integer $id image id number to seprate the folder in public folder * @param string $path original image path * @param float $width width of image for resize * @param float $heigh height of image for resize * @param integer $quality quality of output image * @return string fetched image url */ public function getImage($id, $path, $width, $heigh, $quality = 70) { $fileName = $this->getFileName(Yii::getAlias($path)); $fileNameWithoutExt = $this->getFileNameWithoutExtension($fileName); $ext = $this->getFileExtension($fileName); if ($width == 0 && $heigh == 0) { $size = Image::getImagine()->open($path)->getSize(); $width = $size->getWidth(); $heigh = $size->getHeight(); } $newFileName = $fileNameWithoutExt . 'x' . $width . 'w' . $heigh . 'h' . '.' . $ext; $upload_number = (int) ($id / 2000) + 1; $savePath = Yii::getAlias('@webroot/images/' . $upload_number); $baseImageUrl = Yii::$app->getRequest()->getBaseUrl() . '/images/' . $upload_number; FileHelper::createDirectory($savePath); $savePath .= DIRECTORY_SEPARATOR . $newFileName; if ($width == 0 && $heigh == 0) { copy($path, $savePath); } else { if (!file_exists($savePath)) { Image::thumbnail($path, $width, $heigh)->interlace(\Imagine\Image\ImageInterface::INTERLACE_PLANE)->save($savePath, ['quality' => $quality]); } } return $baseImageUrl . '/' . $newFileName; }
/** * Скропать изображения и вернуть объет для работы с ним. * * Если исходное изображение меньше по размерам - сначала его ресайзит до нужных размеров. * * @param string $tmpFileName Путь к исходному файлу * @param integer $paramWidth Ширина для кропа * @param integer $paramHeight Высота для кропа * * @return ImageInterface */ public static function cropImage($tmpFileName, $paramWidth, $paramHeight) { $newImage = Image::getImagine()->open($tmpFileName); $imageSizes = $newImage->getSize(); $width = $imageSizes->getWidth(); $height = $imageSizes->getHeight(); //Если меньше нужных размеров, то сначала пропорционально ресайзим if ($width < $paramWidth || $height < $paramHeight) { $newHeight = $height; $newWidth = $width; if ($width / $height > $paramWidth / $paramHeight) { $newHeight = $paramHeight; $newWidth = round($newHeight * $width / $height); } elseif ($width / $height <= $paramWidth / $paramHeight) { $newWidth = $paramWidth; $newHeight = round($newWidth * $height / $width); } $newImage->resize(new Box($newWidth, $newHeight))->save($tmpFileName, ['quality' => 80]); } $box = new Box($paramWidth, $paramHeight); if ($newImage->getSize()->getWidth() <= $box->getWidth() && $newImage->getSize()->getHeight() <= $box->getHeight() || !$box->getWidth() && !$box->getHeight()) { return $newImage->copy(); } $newImage = $newImage->thumbnail($box, ManipulatorInterface::THUMBNAIL_OUTBOUND); // create empty image to preserve aspect ratio of thumbnail $thumb = Image::getImagine()->create(new Box($newImage->getSize()->getWidth(), $newImage->getSize()->getHeight()), new Color('FFF', 100)); $thumb->paste($newImage, new Point(0, 0)); return $thumb; }
public function createThumbnails() { $thumbs = []; $data = []; $image_sizes = SettingsHelper::getField('media.image_sizes'); $filePath = Yii::getAlias('@uploads'); $_width = Image::getImagine()->open($filePath . '/' . $this->folder . '/' . $this->file)->getSize()->getWidth(); $_height = Image::getImagine()->open($filePath . '/' . $this->folder . '/' . $this->file)->getSize()->getHeight(); $data['width'] = $_width; $data['height'] = $_height; if ($image_sizes) { $fileinfo = pathinfo($filePath . '/' . $this->folder . '/' . $this->file); foreach ($image_sizes as $size) { $fileName = $fileinfo['filename'] . '-' . $size['width'] . 'x' . $size['height'] . '.' . $fileinfo['extension']; if ($size['width'] > $_width || $size['height'] > $_height) { continue; } $thumb = $filePath . '/' . $this->folder . '/' . $fileName; Image::thumbnail($filePath . '/' . $this->folder . '/' . $this->file, $size['width'], $size['height'], ImageInterface::THUMBNAIL_OUTBOUND)->save($thumb); $thumbs[$size['name']] = ['width' => $size['width'], 'height' => $size['height'], 'file' => $fileName]; } $data['sizes'] = $thumbs; } return $data; }
/** * Create watermark in fs * @param $thumb Thumbnail * @param $water Watermark * @return string */ public static function createWatermark($thumb, $water) { try { $thumbImagine = Imagine::getImagine()->read(Yii::$app->getModule('image')->fsComponent->readStream($thumb->thumb_path)); $waterImagine = Imagine::getImagine()->read(Yii::$app->getModule('image')->fsComponent->readStream($water->watermark_path)); $thumbSize = $thumbImagine->getSize(); $waterSize = $waterImagine->getSize(); // Resize watermark if it to large if ($thumbSize->getWidth() < $waterSize->getWidth() || $thumbSize->getHeight() < $waterSize->getHeight()) { $t = $thumbSize->getHeight() / $waterSize->getHeight(); if (round($t * $waterSize->getWidth()) <= $thumbSize->getWidth()) { $waterImagine->resize(new Box(round($t * $waterSize->getWidth()), $thumbSize->getHeight())); } else { $t = $thumbSize->getWidth() / $waterSize->getWidth(); $waterImagine->resize(new Box($thumbSize->getWidth(), round($t * $waterSize->getHeight()))); } } $position = [0, 0]; if ($water->position == Watermark::POSITION_CENTER) { $position = [round(($thumbImagine->getSize()->getWidth() - $waterImagine->getSize()->getWidth()) / 2), round(($thumbImagine->getSize()->getHeight() - $waterImagine->getSize()->getHeight()) / 2)]; } else { $posStr = explode(' ', $water->position); switch ($posStr[0]) { case 'TOP': $position[0] = 0; break; case 'BOTTOM': $position[0] = $thumbImagine->getSize()->getWidth() - $waterImagine->getSize()->getWidth(); break; } switch ($posStr[1]) { case 'LEFT': $position[1] = 0; break; case 'RIGHT': $position[1] = $thumbImagine->getSize()->getHeight() - $waterImagine->getSize()->getHeight(); break; } } $tmpThumbFilePath = Yii::getAlias('@runtime/' . str_replace(Yii::$app->getModule('image')->thumbnailsDirectory, '', $thumb->thumb_path)); $tmpWaterFilePath = Yii::getAlias('@runtime/' . str_replace(Yii::$app->getModule('image')->watermarkDirectory, '', $water->watermark_path)); $thumbImagine->save($tmpThumbFilePath); $waterImagine->save($tmpWaterFilePath); $watermark = Imagine::watermark($tmpThumbFilePath, $tmpWaterFilePath, $position); $path = Yii::$app->getModule('image')->thumbnailsDirectory; $fileInfo = pathinfo($thumb->thumb_path); $watermarkInfo = pathinfo($water->watermark_path); $fileName = "{$fileInfo['filename']}-{$watermarkInfo['filename']}.{$fileInfo['extension']}"; $watermark->save(Yii::getAlias('@runtime/') . $fileName); $stream = fopen(Yii::getAlias('@runtime/') . $fileName, 'r+'); Yii::$app->getModule('image')->fsComponent->putStream("{$path}/{$fileName}", $stream); fclose($stream); unlink($tmpThumbFilePath); unlink($tmpWaterFilePath); unlink(Yii::getAlias('@runtime/' . $fileName)); return "{$path}/{$fileName}"; } catch (Exception $e) { return false; } }
public static function saveImage($model) { $model->date = date('Y-m-d'); $maxId = Products::find()->select('max(id)')->scalar(); $imageName = $maxId + 1; // (uniqid('img_')-как вариант, без нагрузки на бд)лучше вариант чем с датой, primary key всегда будет // уникальным + запрос вроде не сложный на выборку поскольку primary индексированый и взять максимальное // не составит большую нагрузку на бд $model->photo = UploadedFile::getInstance($model, 'photo'); $fullName = Yii::getAlias('@webroot') . '/photos/' . $imageName . '.' . $model->photo->extension; $model->photo->saveAs($fullName); $img = Image::getImagine()->open($fullName); $size = $img->getSize(); $ratio = $size->getWidth() / $size->getHeight(); $height = round(Products::IMAGE_WIDTH / $ratio); $box = new Box(Products::IMAGE_WIDTH, $height); $img->resize($box)->save(Yii::getAlias('@webroot') . '/thumbnails/' . $imageName . '.' . $model->photo->extension); $model->thumbnail = '/thumbnails/' . $imageName . '.' . $model->photo->extension; $model->photo = '/photos/' . $imageName . '.' . $model->photo->extension; $save = $model->save(); if ($save) { return true; } else { die('product model was not save'); } }
/** * Creates and caches the image thumbnail and returns full path from thumbnail file. * * @param string $filename * @param integer $width * @param integer $height * @param string $mode * @return string * @throws FileNotFoundException */ public static function thumbnailFile($filename, $width, $height, $mode = self::THUMBNAIL_OUTBOUND) { $filename = FileHelper::normalizePath(Yii::getAlias($filename)); if (!is_file($filename)) { throw new FileNotFoundException("File {$filename} doesn't exist"); } $cachePath = Yii::getAlias('@webroot/' . self::$cacheAlias); $thumbnailFileExt = strrchr($filename, '.'); $thumbnailFileName = md5($filename . $width . $height . $mode . filemtime($filename)); $thumbnailFilePath = $cachePath . DIRECTORY_SEPARATOR . substr($thumbnailFileName, 0, 2); $thumbnailFile = $thumbnailFilePath . DIRECTORY_SEPARATOR . $thumbnailFileName . $thumbnailFileExt; if (file_exists($thumbnailFile)) { if (self::$cacheExpire !== 0 && time() - filemtime($thumbnailFile) > self::$cacheExpire) { unlink($thumbnailFile); } else { return $thumbnailFile; } } if (!is_dir($thumbnailFilePath)) { mkdir($thumbnailFilePath, 0755, true); } $box = new Box($width, $height); $image = Image::getImagine()->open($filename); $image = $image->thumbnail($box, $mode); $image->save($thumbnailFile); return $thumbnailFile; }
public function upload($attribute) { if ($uploadImage = UploadedFile::getInstance($this->owner, $attribute)) { if (!$this->owner->isNewRecord) { $this->delete($attribute); } $croppingFileName = md5($uploadImage->name . $this->quality . filemtime($uploadImage->tempName)); $croppingFileExt = strrchr($uploadImage->name, '.'); $croppingFileDir = substr($croppingFileName, 0, 2); $croppingFileBasePath = Yii::getAlias($this->basePath) . $this->baseDir; if (!is_dir($croppingFileBasePath)) { mkdir($croppingFileBasePath, 0755, true); } $croppingFilePath = Yii::getAlias($this->basePath) . $this->baseDir . DIRECTORY_SEPARATOR . $croppingFileDir; if (!is_dir($croppingFilePath)) { mkdir($croppingFilePath, 0755, true); } $croppingFile = $croppingFilePath . DIRECTORY_SEPARATOR . $croppingFileName . $croppingFileExt; $cropping = $_POST[$attribute . '-cropping']; $imageTmp = Image::getImagine()->open($uploadImage->tempName); $imageTmp->rotate($cropping['dataRotate']); $image = Image::getImagine()->create($imageTmp->getSize()); $image->paste($imageTmp, new Point(0, 0)); $point = new Point($cropping['dataX'], $cropping['dataY']); $box = new Box($cropping['dataWidth'], $cropping['dataHeight']); $image->crop($point, $box); $image->save($croppingFile, ['quality' => $this->quality]); $this->owner->{$attribute} = $this->baseDir . DIRECTORY_SEPARATOR . $croppingFileDir . DIRECTORY_SEPARATOR . $croppingFileName . $croppingFileExt; } elseif (isset($_POST[$attribute . '-remove']) && $_POST[$attribute . '-remove']) { $this->delete($attribute); } elseif (isset($this->owner->oldAttributes[$attribute])) { $this->owner->{$attribute} = $this->owner->oldAttributes[$attribute]; } }
public function run() { if (Yii::$app->request->isPost) { $data = Yii::$app->request->post(); if (!empty($data['url']) && in_array($data['direction'], ['CW', 'CCW'])) { try { $url = $data['url']; $url = str_replace(Yii::$app->request->baseUrl, '', $url); if (substr($url, 0, 1) == '/') { $url = substr($url, 1); } if (strpos($url, '?_ignore=') !== false) { $url = substr($url, 0, strpos($url, '?_ignore=')); } Image::getImagine()->open($url)->copy()->rotate($data['direction'] == 'CW' ? 90 : -90)->save($url); list($width, $height) = getimagesize($url); return Json::encode(['size' => [$width, $height], 'url' => Yii::$app->request->baseUrl . '/' . $url]); } catch (Exception $e) { return Json::encode(['errors' => [$e->getMessage()]]); } } else { return Json::encode(['errors' => ['Invalid rotate options!']]); } } }
/** * @param $oldModel FileUploadBehavior */ public function afterSave($oldModel) { parent::afterSave($oldModel); if ($this->_file instanceof UploadedFile) { foreach ($this->options['thumbs'] as $id => $options) { if (isset($options['imagine']) || $options['saveOptions']) { if (empty($options['saveOptions'])) { $options['saveOptions'] = []; } if (empty($options['imagine'])) { $options['imagine'] = function ($filename) { return Image::getImagine()->open($filename); }; } $this->processImage($options['imagine'], $options['saveOptions'], $id); } } if (isset($this->options['imagine']) || $this->options['saveOptions']) { if (empty($this->options['saveOptions'])) { $this->options['saveOptions'] = []; } if (empty($this->options['imagine'])) { $this->options['imagine'] = function ($filename) { return Image::getImagine()->open($filename); }; } $this->processImage($this->options['imagine'], $this->options['saveOptions']); } } }
public function upload() { if ($this->usua_imagem instanceof \yii\web\UploadedFile) { //Image::frame($this->usua_imagem->tempName)->save(); $imagem = 'uploads/' . $this->usua_codigo . '.png'; $imagine = Image::getImagine()->open($this->usua_imagem->tempName)->thumbnail(new Box(140, 140))->save($imagem, ['quality' => 90]); } }
/** * Sets up the box for the uploaded image as a boundary * * @param int | int[] $dimension One or two dimensions of the box. In case of integer it will make a square box * @param bool $crop Determines if the image need to be cropped * * @return $this */ public function resize($dimension, $crop = true) { $this->initContentFile(); /** @var ImageInterface $imagine */ $imagine = Image::getImagine()->open($this->contentFile); $this->performResize($imagine, $dimension, $crop); $imagine->save($this->contentFile); return $this; }
public function createAvatar($uploadedAvatar) { $fileName = $this->avatar ? $this->avatar : Yii::$app->security->generateRandomString(16); $uploadedAvatar->saveAs(User::avatarPath() . '/' . $fileName); foreach (User::getAvatarSizes() as $size) { Image::thumbnail(User::avatarPath() . '/' . $fileName, $size[0], $size[1])->save(User::avatarPath() . "/{$fileName}_{$size[0]}_{$size[1]}.png"); } Image::getImagine()->open(User::avatarPath() . '/' . $fileName)->save(User::avatarPath() . '/' . $fileName . '.png'); unlink(User::avatarPath() . '/' . $fileName); $this->avatar = $fileName; }
public function createPoster($uploadedPoster) { $fileName = $this->poster ? $this->poster : Yii::$app->security->generateRandomString(16); $uploadedPoster->saveAs(Competition::posterPath() . '/' . $fileName); foreach (Competition::getPosterSizes() as $size) { Image::thumbnail(Competition::posterPath() . '/' . $fileName, $size[0], $size[1])->save(Competition::posterPath() . "/{$fileName}_{$size[0]}_{$size[1]}.png"); } Image::getImagine()->open(Competition::posterPath() . '/' . $fileName)->save(Competition::posterPath() . '/' . $fileName . '.png'); unlink(Competition::posterPath() . '/' . $fileName); $this->poster = $fileName; }
/** * @param $image \pavlinter\display2\objects\Image * @param $originalImage \Imagine\Gd\Image * @return mixed */ public function resize($image, $originalImage) { $Box = new Box($image->width, $image->height); $newImage = $originalImage->thumbnail($Box); $boxNew = $newImage->getSize(); $x = ($Box->getWidth() - $boxNew->getWidth()) / 2; $y = ($Box->getHeight() - $boxNew->getHeight()) / 2; $point = new \Imagine\Image\Point($x, $y); $palette = new \Imagine\Image\Palette\RGB(); $color = $palette->color($image->bgColor, $image->bgAlpha); return \yii\imagine\Image::getImagine()->create($Box, $color)->paste($newImage, $point); }
/** * 保存头像 * @return [type] [description] * @version 1.0 2015-12-28T16:14:11+0800 * @author cnzhangxl@foxmail.com */ private function saveAvatar(&$model) { if ($_FILES['Manager']['tmp_name']['avatar']) { $rel_path = date('Ym') . '/' . date('d') . '/'; $save_path = Yii::getAlias('@upload_path/' . $rel_path); !is_dir($save_path) ? mkdir($save_path, 0777, true) : null; $image = Image::getImagine(); $file_name = uniqid() . '.jpg'; Image::thumbnail($_FILES['Manager']['tmp_name']['avatar'], 160, 160)->save($save_path . $file_name); //$image->open($_FILES['Manager']['tmp_name']['avatar'])->save($save_path.$file_name); $model->avatar = $rel_path . $file_name; } }
/** * Creates thumbnail function callback for [[url]] function. Example: * ```php * (new Thumbnail())->url($image, Thumbnail::thumb(100, 100), '100x100'); * ``` * @param integer $width * @param integer $height * @param string $sizeMode * @return callable */ public static function thumb($width, $height, $sizeMode = self::SIZE_MODE_ORIGINAL) { if ($sizeMode == self::SIZE_MODE_DESIRED) { return function ($image) use($width, $height) { return Image::thumbnail($image, $width, $height, ManipulatorInterface::THUMBNAIL_INSET); }; } if ($sizeMode == self::SIZE_MODE_ORIGINAL) { return function ($image) use($width, $height) { return Image::getImagine()->open($image)->thumbnail(new Box($width, $height)); }; } throw new InvalidParamException('Unknown $sizeMode'); }
public function resize($filename, $type, $width, $type_model, $folder) { $img = Image::getImagine()->open(Yii::getAlias('uploads/' . $type_model . 'original/' . $filename . "." . $type)); $size = $img->getSize(); if ($width < $size->getWidth()) { $ratio = $size->getWidth() / $size->getHeight(); $height = round($width / $ratio); } else { $width = $size->getWidth(); $height = $size->getHeight(); } $box = new Box($width, $height); $img->resize($box)->save('uploads/' . $type_model . $folder . $filename . "." . $type); }
public function uploadFile() { $image = UploadedFile::getInstance($this->owner, $this->inAttributeUploadImage); if ($image && $this->owner->validate()) { $oldNameFile = $this->owner->{$this->inAttribute}; $savePath = $this->owner->getSavePath(); $saveName = md5($image->getBaseName()) . rand(1, 500) . '.' . $image->getExtension(); $this->owner->{$this->inAttribute} = $saveName; $path = $savePath . $saveName; $photo = Image::getImagine()->open($image->tempName); $photo->thumbnail(new Box(500, 600))->resize(new Box(500, 600))->save($path, ['quality' => 100]); @unlink($savePath . $oldNameFile); } }
protected static function generateThumbnail($file, $width, $height, $options) { $thumbName = self::getThumbFileName($file, $width, $height); $thumbDir = self::getThumbCachePath($thumbName); $thumbPath = "{$thumbDir}/{$thumbName}"; if (file_exists($thumbPath)) { return $thumbPath; } FileHelper::createDirectory($thumbDir); $mode = ArrayHelper::getValue($options, 'mode', ManipulatorInterface::THUMBNAIL_OUTBOUND); $box = new Box($width, $height); $image = Image::getImagine()->open($file); $image = $image->thumbnail($box, $mode); $image->save($thumbPath); return $thumbPath; }
/** * @inheritdoc */ public function run() { Yii::$app->response->format = Response::FORMAT_JSON; if (Yii::$app->request->isPost) { $params = Yii::$app->request->post(); $srcImage = $this->getImagePath($params['image']['src']); $image = Image::getImagine()->open(Yii::getAlias($this->uploadRootPath . $srcImage)); $size = $image->getSize()->heighten($params['image']['height']); $image->resize($size); $image->crop(new \Imagine\Image\Point($params['crop']['x'], $params['crop']['y']), new \Imagine\Image\Box($params['crop']['width'], $params['crop']['height'])); $destImage = $this->getNewName($srcImage); $image->save(Yii::getAlias($this->uploadRootPath . $destImage)); return ['file' => $destImage]; } return ['error' => 'It should be POST request.']; }
protected function thumb($mode, $in, $width, $height, $out = null) { $imagine = Image::getImagine(); $path = Yii::getAlias($in); $img = $imagine->open($path); $thumb = $img->thumbnail(new Box($width, $height), $mode); if ($out) { if (false !== strpos('/', $out)) { $thumb->save(Yii::getAlias($out)); } else { $thumb->save(dirname($path) . '/' . $out); } } else { $thumb->save($path); } }
public function actionIndex() { // echo '1111'; echo Yii::$app->hydra->getCacheUrl('/news/1.jpg', '100x100p'); // Yii::$app->hydra->parseCachePath('/data/cache/path/anydir/file-300x200p.jpg'); die; $imagine = Image::getImagine(); $image = $imagine->open('https://pp.vk.me/c625231/v625231488/6207f/ZdXVkWDteFk.jpg'); // $image = $image->thumbnail(new Box(300, 100), ImageInterface::THUMBNAIL_OUTBOUND); $image = $image->thumbnail(new \Imagine\Image\Box(300, 100), ImageInterface::THUMBNAIL_INSET); // $image = $image->crop(new Point(0, 0), new Box(300, 200)); // Yii::$app->response->headers->add('Content-Type', 'image/jpeg'); $image->show('png'); // Yii::$app->response->send(); Yii::$app->end(); }
public static function thumbnailFile($filename, $width, $height, $mode = self::THUMBNAIL_OUTBOUND, $isWatermark = false) { $filename = FileHelper::normalizePath(Yii::getAlias($filename)); if (!is_file($filename)) { throw new FileNotFoundException("File {$filename} doesn't exist"); } $cachePath = Yii::getAlias(self::$cashBaseAlias . '/' . self::$cacheAlias); $thumbnailFileExt = strrchr($filename, '.'); $thumbnailFileName = md5($filename . $width . $height . $mode . filemtime($filename)); $thumbnailFilePath = $cachePath . DIRECTORY_SEPARATOR . substr($thumbnailFileName, 0, 2); $thumbnailFile = $thumbnailFilePath . DIRECTORY_SEPARATOR . $thumbnailFileName . $thumbnailFileExt; if (file_exists($thumbnailFile)) { if (self::$cacheExpire !== 0 && time() - filemtime($thumbnailFile) > self::$cacheExpire) { unlink($thumbnailFile); } else { return $thumbnailFile; } } if (!is_dir($thumbnailFilePath)) { mkdir($thumbnailFilePath, 0755, true); } $box = new Box($width, $height); $imagine = Image::getImagine(); $image = $imagine->open($filename)->thumbnail($box, $mode); $image->save($thumbnailFile); if ($isWatermark) { if (file_exists(Yii::getAlias(self::$watermark))) { $watermark = Image::getImagine()->open(Yii::getAlias(self::$watermark)); $image = Image::getImagine()->open($thumbnailFile); $size = $image->getSize(); $wSize = $watermark->getSize(); $bottomRight = new Point($size->getWidth() - $wSize->getWidth() - 30, $size->getHeight() - $wSize->getHeight() - 12); $image->paste($watermark, $bottomRight); $image->save($thumbnailFile); } else { if (self::$watermark) { $point = new Point(self::$watermarkConfig['fontStart'][0], self::$watermarkConfig['fontStart'][1]); $color = new Color(self::$watermarkConfig['fontColor'], self::$watermarkConfig['fontSize']); $font = Image::getImagine()->font(Yii::getAlias(self::$watermarkConfig['fontFile']), Yii::getAlias(self::$watermarkConfig['fontSize']), $color); $image = Image::getImagine()->open($thumbnailFile); $image->draw()->text(self::$watermark, $font, $point, self::$watermarkConfig['fontAngle']); $image->save($thumbnailFile); } } } return $thumbnailFile; }
public function actionFileUpload() { session_start(); $this->enableCsrfValidation = false; $uploaddir = Yii::getAlias('@frontend/web/uploads/services/'); $tmp_image_name = $_FILES['service_img']['tmp_name']; $image_name = substr(sha1(basename($_FILES['service_img']['name']) . time() . rand(1000, 9999)), 0, 7) . basename($_FILES['service_img']['name']); move_uploaded_file($tmp_image_name, $uploaddir . $image_name); Image::getImagine()->open(Yii::getAlias('@frontend/web/uploads/services/' . $image_name))->thumbnail(new Box(500, 500))->save(Yii::getAlias('@frontend/web/uploads/services/min/' . $image_name), ['quality' => 90]); $model = new Media(); $model->service_id = $_SESSION['Service']['id']; $model->img = $image_name; $model->type = 'img'; $model->created_date = date('Y-m-d h:m:s'); $model->status = '1'; $model->save(); return $model->getPrimaryKey(); }
public function actionCrop() { $imageConfig = ['id_row' => Yii::$app->request->get('id_row'), 'width' => Yii::$app->request->get('width'), 'height' => Yii::$app->request->get('height'), 'image' => Yii::$app->request->get('image'), 'category' => Yii::$app->request->get('category'), 'bgColor' => Yii::$app->request->get('bgColor'), 'bgAlpha' => Yii::$app->request->get('bgAlpha'), 'mode' => Yii::$app->request->get('mode')]; foreach ($imageConfig as $k => $v) { if ($v === null) { unset($imageConfig[$k]); } } /* @var $display \pavlinter\display2\components\Display */ $display = Yii::$app->get(Module::getInstance()->componentId); $image = $display->getImage($imageConfig); $img = \yii\imagine\Image::getImagine()->open($image->rootSrc); Yii::$app->response->format = \yii\web\Response::FORMAT_RAW; $headers = Yii::$app->response->headers; $headers->add('Content-Type', 'image/jpeg'); $img->show('jpg'); return; }
/** * Создает уменьшенную и обрезанную копию изображения * * Обрезка производится до 200 пикселей * * @param string $sourceFilePath * @param string $thumbImagePath * @return bool */ public function createThumb($sourceFilePath) { $imageWidth = 200; $imageRatio = 1.5; $img = Image::getImagine()->open($sourceFilePath); $size = $img->getSize(); // Если высота больше ширины if ($size->getHeight() > $size->getWidth()) { //$img = BwImage::thumbnail($sourceFilePath, $imageWidth, $imageWidth, ManipulatorInterface::THUMBNAIL_INSET)->save($sourceFilePath); $imageHeight = round($imageWidth * $imageRatio); $box = new Box($size->getWidth(), $size->getWidth() * $imageRatio); $start = new StartPoint($box); $img->crop($start, $box); $img->resize(new Box($imageWidth, $imageHeight))->save($sourceFilePath); } else { $imageHeight = round($imageWidth / $imageRatio); $img = BwImage::thumbnail($sourceFilePath, $imageWidth, $imageHeight)->save($sourceFilePath); } }
public function actionServeImage() { $preset = $_GET['preset']; list($width, $height) = $this->resolvePreset($preset); $image = File::getByName($_GET['name']); if (isset($image) && is_file($image->path)) { $presetFolder = $image->getPresetFolder($preset); $fileCachePath = $presetFolder . $image->filename; FileHelper::createDirectory($presetFolder); if ($preset == 'editor') { copy($image->path, $fileCachePath); } else { Image::getImagine()->open($image->path)->thumbnail(new \Imagine\Image\Box($width, $height))->save($fileCachePath); } header('Content-type: ' . mime_content_type($fileCachePath)); readfile($fileCachePath); exit; } }
/** * [[@doctodo method_description:followResizeInstructions]]. * * @param [[@doctodo param_type:imagePath]] $imagePath [[@doctodo param_description:imagePath]] * @param [[@doctodo param_type:resize]] $resize [[@doctodo param_description:resize]] * * @return [[@doctodo return_type:followResizeInstructions]] [[@doctodo return_description:followResizeInstructions]] */ protected function followResizeInstructions($imagePath, $resize) { if (is_object($imagePath)) { $image = $imagePath; } else { $imagine = Image::getImagine(); $image = $imagine->open($imagePath); } if (!$image) { return false; } $size = $image->getSize(); if (isset($resize['width']) && $resize['width'] < $size->getWidth()) { $image->resize($size->widen($resize['width'])); } if (isset($resize['height']) && $resize['height'] < $size->getHeight()) { $image->resize($size->heighten($resize['height'])); } return $image; }
/** * Create thumbnail in fs * @param $image Image * @param $size ThumbnailSize * @return string|false */ public static function createThumbnail($image, $size) { try { /** @var Filesystem $fs */ $fs = Yii::$app->getModule('image')->fsComponent; $file = Imagine::getImagine()->read($fs->readStream($image->filename)); /** @var ImageInterface $thumb */ $thumb = $file->thumbnail(new Box($size->width, $size->height), $size->resize_mode); $path = Yii::$app->getModule('image')->thumbnailsDirectory; if (!preg_match('#^(?<name>.+)\\.(?<ext>[^\\.]+)$#', $image->filename, $fileInfo)) { return false; } $stream = $thumb->get($fileInfo['ext'], ['quality' => $size->quality]); $src = "{$path}/{$fileInfo['name']}-{$size->width}x{$size->height}.{$fileInfo['ext']}"; $fs->put($src, $stream); return $src; } catch (\Exception $e) { return false; } }