php yii-imagine-Image类(方法)实例源码

下面列出了php yii-imagine-Image 类(方法)源码代码实例,从而了解它的用法。

作者:plathi    项目:yii2-smart-uploa   
/**
  * @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'));
     }
 }

作者:bajade    项目:yii2-ckedito   
/**
  * @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]);
 }

作者:sadovoja    项目:yii2-image-cutte   
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];
     }
 }

作者:humanize    项目:yii2-content-tools-pag   
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!']]);
         }
     }
 }

作者:sergey-ex    项目:ki   
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;
     }
 }

作者:Dominus7    项目:blo   
/**
  * @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;
     }
 }

作者:ni032ma    项目:emtol_yii   
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;
     }
 }

作者:oakcm    项目:oakcm   
/**
  * 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 '';
 }

作者:kalyabi    项目:comitk   
/**
  * Скропать изображения и вернуть объет для работы с ним.
  *
  * Если исходное изображение меньше по размерам - сначала его ресайзит до нужных размеров.
  *
  * @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;
 }

作者:sAnbl    项目:getlooky-tes   
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]);
 }

作者:NikDevPH    项目:yii2-blo   
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;
 }

作者:rocketyan    项目:adma   
/**
  *  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;
 }

作者:rocketyan    项目:hasscms-ap   
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, "裁剪成功");
 }

作者:mihailde    项目:yii2-file-uploa   
/**
  * @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']);
         }
     }
 }

作者:bokko7    项目:servicemap   
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;
     }
 }

作者:budyag    项目:yii2-croppe   
/**
  * @inheritdoc
  */
 public function run()
 {
     if (Yii::$app->request->isPost) {
         $file = UploadedFile::getInstanceByName($this->uploadParam);
         $model = new DynamicModel(compact($this->uploadParam));
         $model->addRule($this->uploadParam, 'image', ['maxSize' => $this->maxSize, 'tooBig' => Yii::t('cropper', 'TOO_BIG_ERROR', ['size' => $this->maxSize / (1024 * 1024)]), 'extensions' => explode(', ', $this->extensions), 'wrongExtension' => Yii::t('cropper', '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;
             $width = $request->post('width', $this->width);
             $height = $request->post('height', $this->height);
             $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($width, $height));
             if ($image->save($this->path . $model->{$this->uploadParam}->name)) {
                 $result = ['filelink' => $this->url . $model->{$this->uploadParam}->name];
             } else {
                 $result = ['error' => Yii::t('cropper', 'ERROR_CAN_NOT_UPLOAD_FILE')];
             }
         }
         Yii::$app->response->format = Response::FORMAT_JSON;
         return $result;
     } else {
         throw new BadRequestHttpException(Yii::t('cropper', 'ONLY_POST_REQUEST'));
     }
 }

作者:mark3    项目:yii2-site-mn   
public function uploadImage($route, $gallery_types_id, $gallery_groups_id)
 {
     $type = (new Query())->select('*')->from($this->tableTypes)->where(['id' => $gallery_types_id])->createCommand()->queryOne();
     $route = preg_replace('/\\/$/', '', $route);
     $destination = preg_replace('/\\/$/', '', $type['destination']);
     if (!is_dir($route . $destination)) {
         if (!mkdir($route . $destination)) {
             return ['success' => false, 'message' => 'Failed to add directory'];
         }
     }
     $imageFile = UploadedFile::getInstanceByName('image');
     $image = (new Query())->select('*')->from($this->tableImages)->where(['gallery_groups_id' => $gallery_groups_id])->andWhere(['name' => $imageFile->baseName . '.' . $imageFile->extension])->createCommand()->queryOne();
     if ($image) {
         return ['success' => false, 'message' => 'File downloaded previously in this group'];
     }
     $src_file = $route . $destination . '/' . $imageFile->baseName . '.' . $imageFile->extension;
     $imageFile->saveAs($src_file, true);
     $size = $this->getSize($src_file, $type);
     $image_small = $this->renderFilename($route . $destination, $imageFile->extension);
     $image_large = $this->renderFilename($route . $destination, $imageFile->extension);
     Image::$driver = [Image::DRIVER_GD2];
     Image::thumbnail($src_file, $size['small_width'], $size['small_height'])->save($route . $destination . '/' . $image_small . '.' . $imageFile->extension, ['quality' => $type['quality']]);
     Image::thumbnail($src_file, $size['large_width'], $size['large_height'])->save($route . $destination . '/' . $image_large . '.' . $imageFile->extension, ['quality' => $type['quality']]);
     unlink($src_file);
     $query = new Query();
     $query->createCommand()->insert($this->tableImages, ['gallery_groups_id' => $gallery_groups_id, 'small' => $destination . '/' . $image_small . '.' . $imageFile->extension, 'large' => $destination . '/' . $image_large . '.' . $imageFile->extension, 'name' => $imageFile->baseName . '.' . $imageFile->extension, 'seq' => $this->getLastSequence($gallery_groups_id) + 1])->execute();
     return ['success' => true, 'gallery_images_id' => Yii::$app->db->getLastInsertID(), 'gallery_groups_id' => $gallery_groups_id, 'small' => $destination . '/' . $image_small . '.' . $imageFile->extension, 'large' => $destination . '/' . $image_large . '.' . $imageFile->extension];
 }

作者:Elgor    项目:apple-touch-ico   
/**
  * Lists all MetaBase models.
  * @return mixed
  */
 public function actionIndex()
 {
     $model = new Icon();
     if (Yii::$app->request->isPost) {
         $model->imageOriginal = UploadedFile::getInstance($model, 'imageOriginal');
         $model->imageDelete = Yii::$app->request->Post('Icon')['imageDelete'];
         if ($model->imageOriginal && $model->validate()) {
             if (!file_exists($model->pathForIcons)) {
                 mkdir($model->pathForIcons, 0777, true);
             }
             $model->imageOriginal->saveAs($model->pathForIcons . '/apple-icon-original.' . $model->imageOriginal->extension);
             if ($model->imageOriginal) {
                 if (!file_exists($model->pathForIcons)) {
                     mkdir($model->pathForIcons, 0777, true);
                 }
                 Image::thumbnail($model->pathForIcons . '/apple-icon-original.png', 60, 60)->save($model->pathForIcons . '/apple-touch-icon.png');
                 Image::thumbnail($model->pathForIcons . '/apple-icon-original.png', 76, 76)->save($model->pathForIcons . '/apple-touch-icon-76x76.png');
                 Image::thumbnail($model->pathForIcons . '/apple-icon-original.png', 120, 120)->save($model->pathForIcons . '/apple-touch-icon-120x120.png');
                 Image::thumbnail($model->pathForIcons . '/apple-icon-original.png', 152, 152)->save($model->pathForIcons . '/apple-touch-icon-152x152.png');
                 $this->redirect(Url::to());
             }
         } else {
             $model->delete();
             $this->redirect(Url::to());
         }
     }
     return $this->render('index', ['model' => $model]);
 }

作者:asus485    项目:sho   
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');
     }
 }

作者:uraankhayayaa    项目:aic.s-vfu.r   
public function Uploadphoto($images, $article_id)
 {
     $i = 0;
     // счетчик что определить фотографии когда они загружаются второе изображение может перезаписать первую в ту же секунду.
     foreach ($images as $file) {
         $newFileName = date("YmdHis") . $i;
         $filePath = Yii::getAlias('@frontend') . '/web/uploads/' . $newFileName . '.' . $file->extension;
         $file427320 = Yii::getAlias('@frontend') . '/web/uploads/427320/' . $newFileName . '.' . $file->extension;
         $file7070 = Yii::getAlias('@frontend') . '/web/uploads/7070/' . $newFileName . '.' . $file->extension;
         $file->saveAs($filePath);
         Image::thumbnail($filePath, 427, 320)->save($file427320, ['quality' => 50]);
         Image::thumbnail($filePath, 70, 70)->save($file7070, ['quality' => 50]);
         $image = new article_photo();
         $image->article_id = $article_id;
         $image->photo_path = Yii::getAlias('@resource') . '/uploads/' . $newFileName . '.' . $file->extension;
         $image->photo_path427320 = Yii::getAlias('@resource') . '/uploads/427320/' . $newFileName . '.' . $file->extension;
         $image->photo_path7070 = Yii::getAlias('@resource') . '/uploads/7070/' . $newFileName . '.' . $file->extension;
         $image->alt = '';
         if ($image->save()) {
             $errorLoadFile = true;
         } else {
             $errorLoadFile = false;
         }
         $i++;
     }
     return $errorLoadFile;
 }


问题


面经


文章

微信
公众号

扫码关注公众号