/**
  * @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'));
     }
 }
Beispiel #2
0
 public function getImageMergePrint($print_id)
 {
     /**
      * @var Prints $print
      */
     $print = Prints::find()->where('id=:id', [':id' => $print_id])->one();
     if (!$print) {
         throw new Exception('Print not found!');
     }
     $pathPrints = $print->getSavePath() . $print->image;
     $pathShirt = $this->getSavePath() . $this->image;
     $image = Image::watermark($pathShirt, $pathPrints);
     $imageSize = $image->getSize();
     $imageData = base64_encode($image->get('png'));
     $imageHTML = "data:89504E470D0A1A0A;base64,{$imageData}";
     return $imageHTML;
 }
 public function testWatermark()
 {
     $img = Image::watermark($this->imageFile, $this->watermarkFile);
     $img->save($this->runtimeWatermarkFile);
     $this->assertTrue(file_exists($this->runtimeWatermarkFile));
 }
 /**
  * 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;
     }
 }
 /**
  * 自动处理图片
  * @param $fullName
  * @return mixed|string
  */
 protected function imageHandle($fullName)
 {
     if (substr($fullName, 0, 1) != '/') {
         $fullName = '/' . $fullName;
     }
     $file = $fullName;
     //先处理缩略图
     if ($this->thumbnail && !empty($this->thumbnail['height']) && !empty($this->thumbnail['width'])) {
         $file = pathinfo($file);
         $file = $file['dirname'] . '/' . $file['filename'] . '.thumbnail.' . $file['extension'];
         Image::thumbnail($this->webroot . $fullName, intval($this->thumbnail['width']), intval($this->thumbnail['height']))->save($this->webroot . $file);
     }
     //再处理缩放,默认不缩放
     //...缩放效果非常差劲-,-
     if (isset($this->zoom['height']) && isset($this->zoom['width'])) {
         $size = $this->getSize($this->webroot . $fullName);
         if ($size && $size[0] > 0 && $size[1] > 0) {
             $ratio = min([$this->zoom['height'] / $size[0], $this->zoom['width'] / $size[1], 1]);
             Image::thumbnail($this->webroot . $fullName, ceil($size[0] * $ratio), ceil($size[1] * $ratio))->save($this->webroot . $fullName);
         }
     }
     //最后生成水印
     if (isset($this->watermark['path']) && file_exists($this->watermark['path'])) {
         if (!isset($this->watermark['start'])) {
             $this->watermark['start'] = [0, 0];
         }
         Image::watermark($file, $this->watermark['path'], $this->watermark['start'])->save($file);
     }
     return $file;
 }
 /**
  * After file save
  * Generate image thumb, if need.
  */
 public function afterFileSave()
 {
     $images = ['original' => $this->_filePath];
     // Thumbnail
     $thumb = $this->thumb;
     if (isset($thumb['generate']) && $thumb['generate']) {
         // Generate thumb image
         $images['thumbnail'] = $this->getThumbnailPath($images['original']);
         Image::thumbnail($images['original'], $thumb['width'], $thumb['height'])->save($images['thumbnail']);
     }
     // Add watermark to image
     $watermark = $this->watermark;
     if (isset($watermark['generate']) && $watermark['generate'] && !empty($watermark['content'])) {
         foreach ($images as $image) {
             if ($watermark['type'] == 'text') {
                 Image::text($image, $watermark['content'], __DIR__ . '/simkai.ttf', [10, 10])->save($image);
             } elseif ($watermark == 'image' && is_file($watermark['content'])) {
                 Image::watermark($image, $watermark['content']);
             }
         }
     }
 }
Beispiel #7
0
 /**
  * Метод загружает фото на удаленный сервер на GoDaddy
  *
  * @return bool
  */
 public function uploadOnDaddyPhoto()
 {
     try {
         // Разбираем архив
         //Создаём объект для работы с ZIP-архивами
         $zip = new ZipArchive();
         if ($this->photosUpload != null && $zip->open($this->photosUpload->tempName) === true) {
             $zip->extractTo("../web/uploads/temp");
             //Извлекаем файлы в указанную директорию
             $arrFiles = [];
             $count = $zip->numFiles;
             for ($i = 0; $i < $count; $i++) {
                 $arrFiles[] = $zip->getNameIndex($i);
             }
             sort($arrFiles);
             for ($i = 0; $i < $count; $i++) {
                 $nameFile = time() . '_' . $arrFiles[$i];
                 // сохраняем превьюшки
                 // Сохраняем оригинал фотки в temp папку
                 Image::getImagine()->open("../web/uploads/temp/" . $arrFiles[$i])->flipHorizontally()->save("../web/uploads/temp/" . $nameFile);
                 // Вешаем ваатермарку
                 $size = getimagesize("../web/uploads/temp/" . $nameFile);
                 Image::watermark('../web/uploads/temp/' . $nameFile, "../web/uploads/watermark/LogoForNewPhoto.png", [$size[0] - 218, 0])->save('../web/uploads/temp/' . $nameFile);
                 $this->ftpUpload('../web/uploads/temp/' . $nameFile, 'photos', $nameFile);
                 // сохраняем превьюшки
                 Image::thumbnail('../web/uploads/temp/' . $nameFile, 255, 340)->save('../web/uploads/temp/' . $nameFile, ['quality' => 80]);
                 //$preview = Image::thumbnail('../web/uploads/temp/'.$nameFile, 255, 340);
                 //                    echo "START".$count; die();
                 $this->ftpUpload('../web/uploads/temp/' . $nameFile, 'thumbnail', $nameFile);
                 unlink("../web/uploads/temp/" . $arrFiles[$i]);
                 $photos = new Photos();
                 $photos->url = "http://loveporno.net/uploads/photos/" . $nameFile;
                 $photos->catalog_id = $this->id;
                 $photos->url_thumbnail = 'http://loveporno.net/uploads/thumbnail/' . $nameFile;
                 $photos->sort = $i;
                 $photos->save();
                 unlink("../web/uploads/temp/" . $nameFile);
             }
             $zip->close();
             //Завершаем работу с архивом
         }
     } catch (Exception $e) {
         echo $e->getMessage();
         Yii::$app->session->setFlash('error', $e->getMessage());
     }
     return true;
 }
Beispiel #8
0
 /**
  * Накладывает водяной знак на изображение и сохраняет его
  *
  * Если указан аргумент $saveImagePath, изображение сохранится по этому пути. Иначе изображение с водяным знаком
  * будет сохранено вместо исходного изображения.
  *
  * @param string $sourceImagePath Полный путь к изображению, на которое накладывается водяной знак
  * @param string $watermarkImagePath Полный путь к водяному знаку
  * @param int $padding Отступ от нужней и правой границы изображения до водяного знака
  * @param string|null $saveImagePath Полный путь для сохранения изображения с водяным знаком
  * @return bool
  */
 protected function putWatermark($sourceImagePath, $watermarkImagePath, $padding = 10, $saveImagePath = null)
 {
     /* TODO Переделать "return false" на исключения */
     // Получаем размеры изображения и водяного знака
     if (!($imgSize = getimagesize($sourceImagePath))) {
         $this->_result[] = 'Не удалось наложить водяной знак. Файл не найден или не является изображением';
         return false;
     }
     if (!($watermarkSize = getimagesize($watermarkImagePath))) {
         $this->_result[] = 'Не удалось наложить водяной знак. Водяной знак не найден или не является изображением';
         return false;
     }
     if ($watermarkSize[0] + $padding > $imgSize[0] || $watermarkSize[1] + $padding > $imgSize[1]) {
         $this->_result[] = 'Не удалось наложить водяной знак. Размеры водяного знака превышают размеры изображения';
         return false;
     }
     // Определяем координаты стартовой точки
     $startX = $imgSize[0] - $watermarkSize[0] - $padding;
     $startY = $imgSize[1] - $watermarkSize[1] - $padding;
     // Накладываем водяной знак
     $img = Image::watermark($sourceImagePath, $watermarkImagePath, [$startX, $startY]);
     // Если задан путь для сохранения изображения
     if ($saveImagePath) {
         $sourceImagePath = $saveImagePath;
     }
     // Сохраняем файл
     if ($img->save($sourceImagePath)) {
         return true;
     }
     return false;
 }
 /**
  * Updates an existing Sertificate model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id
  * @return mixed
  */
 public function actionUpdate($id)
 {
     $model = $this->findModel($id);
     // if ($model->load(Yii::$app->request->post()) && $model->save()) {
     //    return $this->redirect(['view', 'id' => $model->id]);
     //} else {
     //   return $this->render('update', [
     //       'model' => $model,
     //  ]);
     //}
     $dir = Yii::getAlias('@frontend/web/images/');
     $uploaded = false;
     if ($model->load($_POST)) {
         //$file = UploadedFile::getInstances($model, 'image');
         $file = UploadedFile::getInstance($model, 'image');
         $model->image = $file;
         //$model->image_s = 'sm_'.$file;
         //$model->on = 1;
         if ($model->validate()) {
             // $uploaded = $file->saveAs( $dir . $model->image->name );
             $uploaded = $file->saveAs($dir . 'tmp/' . $file);
             $name_img = uniqid() . '.jpg';
             $waterfile = $dir . 'watermark.png';
             Image::thumbnail($dir . 'tmp/' . $file, 150, 210)->save(Yii::getAlias($dir . $name_img), ['quality' => 60]);
             Image::thumbnail($dir . 'tmp/' . $file, 400, 560)->save(Yii::getAlias($dir . 'tmp/big_' . $name_img), ['quality' => 60]);
             Image::watermark($dir . 'tmp/big_' . $name_img, $waterfile, [250, 450])->save(Yii::getAlias($dir . 'big_' . $name_img));
             unlink($dir . 'tmp/' . $file);
             unlink($dir . 'tmp/big_' . $name_img);
             $model->image = 'big_' . $name_img;
             $model->image_s = $name_img;
             $model->on = 1;
             $model->save();
             return $this->render('view', ['model' => $model, 'uploaded' => $uploaded, 'dir' => $dir]);
         }
     }
     return $this->render('update', ['model' => $model, 'uploaded' => $uploaded, 'dir' => $dir]);
 }
 public function createThumbs()
 {
     $path = $this->getUploadedFilePath($this->attribute);
     if (file_exists($path)) {
         foreach ($this->thumbs as $profile => $config) {
             $thumbPath = static::getThumbFilePath($this->attribute, $profile);
             if (!is_file($thumbPath)) {
                 /** @var GD $thumb */
                 $thumb = new GD($path);
                 $dimensions = $thumb->getCurrentDimensions();
                 if ($dimensions['width'] > $dimensions['height']) {
                     $thumb->resize($config['width'], $config['height']);
                 } else {
                     $thumb->resize($config['height'], $config['width']);
                 }
                 FileHelper::createDirectory(pathinfo($thumbPath, PATHINFO_DIRNAME), 0775, true);
                 $thumb->save($thumbPath);
                 if (isset($config['watermark'])) {
                     $watermarkedImage = Image::watermark($thumbPath, $config['watermark']);
                     $watermarkedImage->save($thumbPath);
                 }
             }
         }
     }
 }
 /**
  * @inheritdoc
  */
 public function run()
 {
     if (Yii::$app->request->isPost) {
         if (isset($_POST['filename'])) {
             $this->fileName = \URLify::filter(pathinfo($_POST['filename'], PATHINFO_FILENAME), 255, "", true) . '_' . uniqid() . '.' . pathinfo($_POST['filename'], PATHINFO_EXTENSION);
             $upload_dir = $this->uploadDir;
             $upload_file = $this->fileName;
             $uploader = new FileUpload('uploadfile');
             $uploader->newFileName = $this->fileName;
             $uploader->sizeLimit = $this->fileSizeLimit;
             // Handle the upload
             $result = $uploader->handleUpload($upload_dir);
             unset($_POST['filename']);
             if (!$result) {
                 $upload_result = json_encode(array('success' => false, 'msg' => $uploader->getErrorMsg()));
             } else {
                 if ($this->isImage($upload_dir . $upload_file)) {
                     //
                     $image_name = $upload_dir . $upload_file;
                     // resize with calculate aspect ratio
                     list($image_width, $image_height, $type, $attr) = getimagesize($image_name);
                     $ratio = $image_width / $image_height;
                     if ($ratio > 1) {
                         $target_width = $this->resize_max_width;
                         $target_height = $this->resize_max_width / $ratio;
                     } else {
                         $target_width = $this->resize_max_height * $ratio;
                         $target_height = $this->resize_max_height;
                     }
                     // resize image if original dimension is bigger from max size
                     if ($target_width < $this->resize_max_width || $target_height < $this->resize_max_height) {
                         Image::thumbnail($image_name, $target_width, $target_height, ManipulatorInterface::THUMBNAIL_INSET)->save($image_name);
                     }
                     // apply watermark
                     if ($this->watermark) {
                         Image::watermark($image_name, $this->watermark)->save($image_name);
                     }
                 }
                 // thumbnails create
                 if ($this->thumbnail && $this->isImage($image_name) && ($this->thumbnail_width > 0 && $this->thumbnail_height > 0)) {
                     Image::thumbnail($image_name, $this->thumbnail_width, $this->thumbnail_height)->save($upload_dir . 'thumbs/' . $upload_file);
                 }
                 $upload_result = ['success' => true, 'filelink' => $upload_file];
             }
             Yii::$app->response->format = Response::FORMAT_JSON;
             return $upload_result;
         }
     } else {
         throw new BadRequestHttpException(Yii::t('upload', 'ONLY_POST_REQUEST'));
     }
 }