本文整理汇总了PHP中yii\imagine\Image::getImagine方法的典型用法代码示例。如果您正苦于以下问题:PHP Image::getImagine方法的具体用法?PHP Image::getImagine怎么用?PHP Image::getImagine使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类yii\imagine\Image
的用法示例。
在下文中一共展示了Image::getImagine方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: run
/**
* @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]);
}
示例2: getImage
/**
* 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 <mjafaripur@yahoo.com>
*
* @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;
}
示例3: cropImage
/**
* Скропать изображения и вернуть объет для работы с ним.
*
* Если исходное изображение меньше по размерам - сначала его ресайзит до нужных размеров.
*
* @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;
}
示例4: createThumbnails
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;
}
示例5: createWatermark
/**
* 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;
}
}
示例6: saveImage
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');
}
}
示例7: thumbnailFile
/**
* 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;
}
示例8: upload
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];
}
}
示例9: run
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!']]);
}
}
}
示例10: afterSave
/**
* @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']);
}
}
}
示例11: upload
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]);
}
}
示例12: resize
/**
* 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;
}
示例13: createAvatar
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;
}
示例14: createPoster
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;
}
示例15: resize
/**
* @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);
}