本文整理汇总了PHP中yii\imagine\Image类的典型用法代码示例。如果您正苦于以下问题:PHP Image类的具体用法?PHP Image怎么用?PHP Image使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Image类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: run
/**
* @inheritdoc
*/
public function run()
{
if (Yii::$app->request->isPost) {
$file = UploadedFile::getInstanceByName($this->uploadParam);
$model = new DynamicModel(compact($this->uploadParam));
$model->addRule($this->uploadParam, 'file', ['maxSize' => $this->maxSize, 'tooBig' => Yii::t('upload', 'TOO_BIG_ERROR', ['size' => $this->maxSize / (1024 * 1024)]), 'extensions' => explode(', ', $this->extensions), 'checkExtensionByMimeType' => false, 'wrongExtension' => Yii::t('upload', 'EXTENSION_ERROR', ['formats' => $this->extensions])])->validate();
if ($model->hasErrors()) {
$result = ['error' => $model->getFirstError($this->uploadParam)];
} else {
$model->{$this->uploadParam}->name = uniqid() . '.' . $model->{$this->uploadParam}->extension;
$request = Yii::$app->request;
$image_name = $this->temp_path . $model->{$this->uploadParam}->name;
$image = Image::crop($file->tempName . $request->post('filename'), intval($request->post('w')), intval($request->post('h')), [$request->post('x'), $request->post('y')])->resize(new Box($this->width, $this->height))->save($image_name);
// watermark
if ($this->watermark != '') {
$image = Image::watermark($image_name, $this->watermark)->save($image_name);
}
if ($image->save($image_name)) {
// create Thumbnail
if ($this->thumbnail && ($this->thumbnail_width > 0 && $this->thumbnail_height > 0)) {
Image::thumbnail($this->temp_path . $model->{$this->uploadParam}->name, $this->thumbnail_width, $this->thumbnail_height)->save($this->temp_path . '/thumbs/' . $model->{$this->uploadParam}->name);
}
$result = ['filelink' => $model->{$this->uploadParam}->name];
} else {
$result = ['error' => Yii::t('upload', 'ERROR_CAN_NOT_UPLOAD_FILE')];
}
}
Yii::$app->response->format = Response::FORMAT_JSON;
return $result;
} else {
throw new BadRequestHttpException(Yii::t('upload', 'ONLY_POST_REQUEST'));
}
}
示例2: 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]);
}
示例3: upload
public function upload($attribute)
{
$class = \yii\helpers\StringHelper::basename(get_class($this->owner)) . 'Cutter';
if ($uploadImage = UploadedFile::getInstance($this->owner, $attribute)) {
if (!$this->owner->isNewRecord) {
$this->delete($attribute);
}
$cropping = $_POST[$class][$attribute . '-cropping'];
$croppingFileName = md5($uploadImage->name . $this->quality . Json::encode($cropping));
$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);
}
$fileSavePath = $croppingFilePath . DIRECTORY_SEPARATOR . $croppingFileName . $croppingFileExt;
$point = new Point($cropping['dataX'], $cropping['dataY']);
$box = new Box($cropping['dataWidth'], $cropping['dataHeight']);
$palette = new \Imagine\Image\Palette\RGB();
$color = $palette->color('fff', 0);
Image::frame($uploadImage->tempName, 0, 'fff', 0)->rotate($cropping['dataRotate'], $color)->crop($point, $box)->save($fileSavePath, ['quality' => $this->quality]);
$this->owner->{$attribute} = $this->baseDir . DIRECTORY_SEPARATOR . $croppingFileDir . DIRECTORY_SEPARATOR . $croppingFileName . $croppingFileExt;
} elseif (isset($_POST[$class][$attribute . '-remove']) && $_POST[$class][$attribute . '-remove']) {
$this->delete($attribute);
} elseif (!empty($_POST[$class][$attribute])) {
$this->owner->{$attribute} = $_POST[$class][$attribute];
} elseif (isset($this->owner->oldAttributes[$attribute])) {
$this->owner->{$attribute} = $this->owner->oldAttributes[$attribute];
}
}
示例4: 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!']]);
}
}
}
示例5: beforeSave
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if ($file = UploadedFile::getInstance($this, 'photo')) {
$imgPath = Yii::getAlias('@storage/teachers/') . $this->photo;
if (is_file($imgPath)) {
unlink($imgPath);
}
$imgName = Yii::$app->getSecurity()->generateRandomString(8);
$img = $imgName . '.' . $file->extension;
if (!file_exists(Yii::getAlias('@storage/teachers/'))) {
mkdir(Yii::getAlias('@storage/teachers/'), 0777, true);
}
//save temp file
if ($file->saveAs(Yii::getAlias('@runtime/') . $img, true)) {
Image::thumbnail('@runtime/' . $img, 200, 200)->save(Yii::getAlias('@storage/teachers/' . $img), ['quality' => 100]);
$this->photo = $img;
//delete temp file
unlink(Yii::getAlias('@runtime/') . $img);
} else {
throw new \yii\web\HttpException(500, 'не удалось сохранить изображение ' . $file->baseName . '.' . $file->extension);
}
}
return true;
} else {
return false;
}
}
示例6: upload
/**
* @return bool
*/
public function upload()
{
if ($this->validate()) {
$model = UserProfile::findOne(['user_id' => Yii::$app->user->identity->getId()]);
if (!$model) {
$model = new UserProfile();
$model->user_id = Yii::$app->user->identity->getId();
}
$path = $this->getUserDirectory($model->user_id);
$file = $this->imageFile;
//удаляем старую аватарку
if ($model->avatar) {
$avatar = $path . '/' . $model->avatar;
if (file_exists($avatar)) {
unlink($avatar);
}
}
$name = time() . '.' . $file->extension;
//$file->imageFile->baseName
$tmp = '_' . $name;
if ($file->saveAs($path . '/' . $tmp)) {
$model->avatar = $name;
Image::thumbnail($path . '/' . $tmp, 100, 100)->save($path . '/' . $model->avatar, ['quality' => 80]);
if (file_exists($path . '/' . $tmp)) {
unlink($path . '/' . $tmp);
}
$model->save();
}
return true;
} else {
return false;
}
}
示例7: put
public function put($file_name, $thumbnail = FALSE, $copy = FALSE)
{
// Проверяем наличие файла
if (file_exists($file_name)) {
// Получаем расширение
$file = explode(".", $file_name);
$ext = $file[count($file) - 1];
// Формируем имя файла в хранилище
$md_name = md5_file($file_name);
$md_name = $md_name . '.' . $ext;
if ($thumbnail) {
$patch = $this->_storagePath($md_name, DIR_IMAGE . 'thumb') . '/' . $md_name;
Image::thumbnail($file_name, 120, 120)->save(Yii::getAlias($patch), ['quality' => 80]);
} else {
$patch = $this->_storagePath($md_name, DIR_IMAGE) . '/' . $md_name;
rename($file_name, $patch);
}
/*if ($copy) {
// Копируем файл в хранилище под новым именем
copy($file_name, $patch);
} else {
// Перемещаем файл в хранилище под новым именем
rename($file_name, $patch);
} */
return $md_name;
} else {
return FALSE;
}
}
示例8: thumb
/**
* Creates thumb from model->image attribute with specified width and height.
* @param int|null $width
* @param int|null $height
* @param bool $crop if false image will be resize instead of cropping
* @return string
*/
public function thumb($width = null, $height = null, $crop = true)
{
if ($this->image && ($width || $height)) {
return Image::thumbnail($this->image, $width, $height, $crop);
}
return '';
}
示例9: 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;
}
示例10: actionUpdate
public function actionUpdate($id)
{
$model = $this->findModelById($id);
$current_image = $model->image;
if ($model->load(Yii::$app->request->post())) {
$file = UploadedFile::getInstance($model, 'image');
if ($file && $file->tempName) {
$model->file = $file;
if ($model->validate(['file'])) {
if ($model->delImage) {
if (file_exists(Yii::getAlias('@webroot' . $current_image))) {
//удаляем файл
unlink(Yii::getAlias('@webroot' . $current_image));
$model->image = null;
}
}
$dir = Yii::getAlias('images/users');
$fileName = '/' . $model->file->baseName . '.' . $model->file->extension;
$model->file->saveAs($dir . $fileName);
$model->file = $fileName;
Image::thumbnail($dir . $fileName, 70, 70)->save(Yii::getAlias($dir . '/thumbs' . $fileName), ['quality' => 75]);
$model->image = '/' . $dir . '/thumbs' . $fileName;
}
}
if ($model->save()) {
Yii::$app->getSession()->setFlash('success', 'Профиль изменен.');
return $this->redirect(['index']);
}
}
return $this->render('update', ['model' => $model]);
}
示例11: changePortrait
public function changePortrait()
{
$user = User::findOne(Yii::$app->user->identity->id);
if (is_null($user)) {
$this->addError('portrait', '用户不存在');
return false;
}
$path = Yii::getAlias("@webroot/portrait/");
$largePath = Yii::getAlias("@webroot/portrait/large/");
$mediumPath = Yii::getAlias("@webroot/portrait/medium/");
$smallPath = Yii::getAlias("@webroot/portrait/small/");
//保存新头像
$filename = date('H.i.s') . '-' . md5($this->portrait->name) . '.' . $this->portrait->extension;
$this->portrait->saveAs($path . $filename);
//large
Image::thumbnail($path . $filename, 220, 220)->save($largePath . $filename);
//medium
Image::thumbnail($path . $filename, 128, 128)->save($mediumPath . $filename);
//small
Image::thumbnail($path . $filename, 64, 64)->save($smallPath . $filename);
//删除原头像
$oldFilename = $user->portrait;
@unlink($path . $oldFilename);
@unlink($largePath . $oldFilename);
@unlink($mediumPath . $oldFilename);
@unlink($smallPath . $oldFilename);
//保存新头像名到数据库
$user->portrait = $filename;
if (!$user->save(false)) {
$this->addError('portrait', '头像修改失败');
return false;
}
return true;
}
示例12: 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;
}
示例13: actionCrop
public function actionCrop($id)
{
$model = $this->findModel($id);
$type = \Yii::$app->getRequest()->post("type");
$x = \Yii::$app->getRequest()->post("x");
$y = \Yii::$app->getRequest()->post("y");
$w = \Yii::$app->getRequest()->post("w");
$h = \Yii::$app->getRequest()->post("h");
switch ($type) {
case CropType::ALL:
$original = $model->getAbsolutePath();
Image::crop($original, $w, $h, [$x, $y])->save($original);
$model->deleteThumbs();
break;
case CropType::THUMBNAIL:
$original = $model->getAbsolutePath();
$newPath = $model->getTempDirectory() . DIRECTORY_SEPARATOR . $model->hash . "." . $model->extension;
$newOriginal = \Yii::$app->get("fileStorage")->getPath($newPath);
Image::crop($original, $w, $h, [$x, $y])->save($newOriginal);
$thumbs = $model->getThumbs();
foreach ($thumbs as $path) {
$fileName = ltrim(pathinfo(" " . $path, PATHINFO_FILENAME));
$parts = explode("_", $fileName);
list($w, $h) = explode("x", $parts[2]);
Image::thumbnail($newOriginal, $w, $h)->save(\Yii::$app->get("fileStorage")->getPath($path));
}
\Yii::$app->get("fileStorage")->delete($newPath);
break;
case CropType::ORIGINAL:
$original = $model->getAbsolutePath();
Image::crop($original, $w, $h, [$x, $y])->save($original);
break;
}
return $this->renderJsonMessage(true, "裁剪成功");
}
示例14: 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']);
}
}
}
示例15: upload
public function upload()
{
if ($this->validate()) {
if ($this->file and $this->file_id != 2) {
unlink(Yii::getAlias('images/property-values/thumbs/' . $this->file->ime));
unlink(Yii::getAlias('images/property-values/' . $this->file->ime));
}
$fileName = $this->id . '_' . $this->name;
$this->imageFile->saveAs('images/property-values/' . $fileName . '1.' . $this->imageFile->extension);
$image = new \common\models\Images();
$image->ime = $fileName . '.' . $this->imageFile->extension;
$image->type = 'image';
$image->date = date('Y-m-d H:i:s');
$thumb = 'images/property-values/' . $fileName . '1.' . $this->imageFile->extension;
Image::thumbnail($thumb, 400, 300)->save(Yii::getAlias('images/property-values/' . $fileName . '.' . $this->imageFile->extension), ['quality' => 80]);
Image::thumbnail($thumb, 80, 64)->save(Yii::getAlias('images/property-values/thumbs/' . $fileName . '.' . $this->imageFile->extension), ['quality' => 80]);
$image->save();
if ($image->save()) {
$this->file_id = $image->id;
$this->imageFile = null;
$this->save();
}
unlink(Yii::getAlias($thumb));
return;
} else {
return false;
}
}