Crop image AJAX handler
@return array
13051
public function onCropImage()
    {
        $this->abortIfReadOnly();

        $imageSrcPath = trim(Input::get('img'));
        $selectionData = Input::get('selection');
        $cropSessionKey = Input::get('cropSessionKey');
        $path = Input::get('path');
        $path = MediaLibrary::validatePath($path);

        if (!strlen($imageSrcPath)) {
            throw new ApplicationException('Invalid input data');
        }

        if (!preg_match('/^[0-9a-z]+$/', $cropSessionKey)) {
            throw new ApplicationException('Invalid input data');
        }

        if (!is_array($selectionData)) {
            throw new ApplicationException('Invalid input data');
        }

        $result = $this->cropImage($imageSrcPath, $selectionData, $cropSessionKey, $path);

        $selectionMode = Input::get('selectionMode');
        $selectionWidth = Input::get('selectionWidth');
        $selectionHeight = Input::get('selectionHeight');

        $this->setSelectionParams($selectionMode, $selectionWidth, $selectionHeight);

        return $result;
    }
253003
public function cropImage($imageResource)
    {
        /** @var int $imageTransparency Transparent color */
        $imageTransparency = imagecolorallocatealpha($imageResource, 255, 255, 255, 127);
        /** @var resource $rotatedImage Rotated image resource */
        $rotatedImage = imagerotate($imageResource, -($_POST['rotate']), $imageTransparency);
        /** @var resource $croppedImage Cropped image resource */
        $croppedImage = imagecrop($rotatedImage, array('x' => $_POST['crop_x'],
            'y' => $_POST['crop_y'],
            'width' => $_POST['crop_width'],
            'height' => $_POST['crop_height']));
        // Delete temp image resource
        imagedestroy($rotatedImage);
        // Return cropped image
        return $croppedImage;
    }
84487
public function actionDeleteImage(): Response
    {
        $model = $this->findModel($this->attachmentModelClass, Yii::$app->request->post('id'));

        $model->delete();

        return $this->asJson([
            'status' => 'success',
        ]);
    }
1328881
public static function getAcceptImageMimeTypes()
    {
        $imageAllowFiles = Yii::$app->getSettings()->get('imageAllowFiles','attachment');
        $extensions = explode(',', $imageAllowFiles);
        array_walk($extensions, function (&$value) {
            $value = 'image/' . $value;
        });
        return $extensions;
    }
131646
public function getAJAXTypeHandlers()
    {
        if ($this->ajaxTypeHandlers != null) {
            return $this->ajaxTypeHandlers;
        }

        $this->ajaxTypeHandlers = array();

        /** @noinspection PhpUndefinedFieldInspection */
        if (!$this->configFile->AJAXTypeHandlers->getName()) {
            return $this->ajaxTypeHandlers;
        }


        /** @noinspection PhpUndefinedFieldInspection */
        foreach ($this->configFile->AJAXTypeHandlers->class as $handler) {
            $class_array = array("class_name" => (string)$handler);
            if (isset($handler['link'])) {
                $class_array['link'] = $this->rootPath . "/" . $handler['link'];
            }
            $this->ajaxTypeHandlers[] = $class_array;
        }
        return $this->ajaxTypeHandlers;
    }
693199
public function getCMSFields()
    {
        // Obtain Field Objects (from parent):
        
        $fields = parent::getCMSFields();
        
        // Insert Image Tab:
        
        $fields->insertAfter(
            Tab::create(
                'Image',
                $this->fieldLabel('Image')
            ),
            'Main'
        );
        
        // Create Image Fields:
        
        $fields->addFieldsToTab(
            'Root.Image',
            [
                FieldSection::create(
                    'LinkImage',
                    $this->fieldLabel('LinkImage'),
                    [
                        $image = UploadField::create(
                            'LinkImage',
                            $this->fieldLabel('LinkImageFile')
                        ),
                        ViewportsField::create(
                            'LinkImageWidth',
                            $this->fieldLabel('LinkImageWidth')
                        )->setUseTextInput(true),
                        ViewportsField::create(
                            'LinkImageHeight',
                            $this->fieldLabel('LinkImageHeight')
                        )->setUseTextInput(true),
                        CheckboxField::create(
                            'InlineVector',
                            $this->fieldLabel('InlineVector')
                        )
                    ]
                )
            ]
        );
        
        // Define Image Field:
        
        $image->setAllowedExtensions(['gif', 'jpg', 'jpeg', 'png', 'svg']);
        $image->setFolderName($this->getAssetFolder());
        
        // Answer Field Objects:
        
        return $fields;
    }
382262
public function uploadImage()
    {
        $image = $this->getTempImage();
        $file = $_FILES['Filedata'];
        $uploadError = Nip_File_System::instance()->getUploadError($file, $image->extensions);

        if (!$uploadError) {
            $image->setResourceFromUpload($file);
            if ($image->validate()) {
                $image->resize();
                $image->save();

                $imageCrop = $this->getTempImage();
                $imageCrop->copyResource($image);

                $ratio = $imageCrop->getRatio();
                $max_width = $imageCrop->minWidth > 600 ? $imageCrop->minWidth : 600;
                $heightCalculated = round($max_width / $ratio);
                if ($heightCalculated < $imageCrop->minHeight) {
                    $max_width = round($imageCrop->minHeight * $ratio);
                }

                $imageCrop->max_width = $max_width;
                $imageCrop->setName('crop-' . $image->name);
                $imageCrop->resize();
                $imageCrop->save();

                return $imageCrop;
            } else {
                $this->errors['upload'] = 'Eroare dimensiuni.';
            }
        } else {
            $this->errors['upload'] = $uploadError;
        }


        return false;
    }
1358016
public function actionImages(): Response
    {
        $result = [];

        foreach (AttachmentModel::find()->each() as $attachment) {
            $result[] = [
                'id' => $attachment->id,
                'url' => $attachment->getFileUrl('origin'),
                'thumb' => $attachment->getFileUrl('thumbnail'),
            ];
        }

        return $this->asJson($result);
    }
1355543
public function getCrop()
    {
        $cropMethods = [
            'crop-top-left' => [0, 0, 1.0],
            'crop-top' => [50, 0, 1.0],
            'crop-top-right' => [100, 0, 1.0],
            'crop-left' => [0, 50, 1.0],
            'crop-center' => [50, 50, 1.0],
            'crop-right' => [100, 50, 1.0],
            'crop-bottom-left' => [0, 100, 1.0],
            'crop-bottom' => [50, 100, 1.0],
            'crop-bottom-right' => [100, 100, 1.0],
        ];

        if (array_key_exists($this->fit, $cropMethods)) {
            return $cropMethods[$this->fit];
        }

        if (preg_match('/^crop-([\d]{1,3})-([\d]{1,3})(?:-([\d]{1,3}(?:\.\d+)?))*$/', $this->fit, $matches)) {
            $matches[3] = isset($matches[3]) ? $matches[3] : 1;

            if ($matches[1] > 100 or $matches[2] > 100 or $matches[3] > 100) {
                return [50, 50, 1.0];
            }

            return [
                (int) $matches[1],
                (int) $matches[2],
                (float) $matches[3],
            ];
        }

        return [50, 50, 1.0];
    }
1203478
public function toArray()
    {
        $commands = array();

        $maybeAppend = function ($command) use (&$commands) {
            if ($command) $commands []= (string) $command;
        };

        if ($this->metadataOnly) {
            $commands []= 'meta';
        }

        $maybeAppend($this->trim);
        $maybeAppend($this->crop);
        $maybeAppend($this->resize);
        $maybeAppend($this->halign);
        $maybeAppend($this->valign);

        if ($this->smartCrop) {
            $commands []= 'smart';
        }

        if (count($this->filters)) {
            $filters = 'filters:' . implode(':', $this->filters);
            $commands []= $filters;
        }

        return $commands;
    }
1044192
public function getDimensions()
    {
        $imageDimension = getimagesize($this->image);

        $width  = $imageDimension[0];
        $height = $imageDimension[1];

        foreach($this->effect as $effect)
        {
            if($effect instanceof PictureEffect)
            {
                $modified = $effect->getNewDimensions($width, $height);

                $width  = $modified['w'];
                $height = $modified['h'];
            }
        }

        return array(

            'w' => $width,
            'h' => $height,
        );
    }
450590
public function values() {
		$res = [];
		foreach($this->fields as $name=>$field) {
			$value = $field->getValue();
			if($value === null)
				continue;
			if(($field->getType() == 'image' || $field->getType() == 'submit') && $name !== $this->submit)
				continue;

			$path = $this->getPath($name);

			$arr =& $res;
			$key = array_pop($path);

			foreach($path as $parent)
				$arr =& $arr[$parent];
			if(!$key)
				$arr[] = $value;
			else
				$arr[$key] = $value;
		}
		return $res;
	}
1265561
public function render()
    {
        if (($this->arguments['src'] === null && $this->arguments['image'] === null) || ($this->arguments['src'] !== null && $this->arguments['image'] !== null)) {
            throw new Exception('You must either specify a string src or a File object.', 1382284106);
        }

        try {
            $image = $this->imageService->getImage($this->arguments['src'], $this->arguments['image'], $this->arguments['treatIdAsReference']);
            $cropString = $this->arguments['crop'];
            if ($cropString === null && $image->hasProperty('crop') && $image->getProperty('crop')) {
                $cropString = $image->getProperty('crop');
            }
            $cropVariantCollection = CropVariantCollection::create((string)$cropString);
            $cropVariant = $this->arguments['cropVariant'] ?: 'default';
            $cropArea = $cropVariantCollection->getCropArea($cropVariant);
            $processingInstructions = [
                'width' => $this->arguments['width'],
                'height' => $this->arguments['height'],
                'minWidth' => $this->arguments['minWidth'],
                'minHeight' => $this->arguments['minHeight'],
                'maxWidth' => $this->arguments['maxWidth'],
                'maxHeight' => $this->arguments['maxHeight'],
                'crop' => $cropArea->isEmpty() ? null : $cropArea->makeAbsoluteBasedOnFile($image),
                // Added by me
                'additionalParameters' => $this->generateAdditionalProcessingParameters(),
                'skipProcessing' => !ConfigurationUtility::isProcessingEnabled(),
            ];
            $processedImage = $this->imageService->applyProcessingInstructions($image, $processingInstructions);
            $imageUri = $this->imageService->getImageUri($processedImage, $this->arguments['absolute']);

            if (!$this->tag->hasAttribute('data-focus-area')) {
                $focusArea = $cropVariantCollection->getFocusArea($cropVariant);
                if (!$focusArea->isEmpty()) {
                    $this->tag->addAttribute('data-focus-area', $focusArea->makeAbsoluteBasedOnFile($image));
                }
            }
            $this->tag->addAttribute('src', $imageUri);
            $this->tag->addAttribute('width', $processedImage->getProperty('width'));
            $this->tag->addAttribute('height', $processedImage->getProperty('height'));

            $alt = $image->getProperty('alternative');
            $title = $image->getProperty('title');

            // The alt-attribute is mandatory to have valid html-code, therefore add it even if it is empty
            if (empty($this->arguments['alt'])) {
                $this->tag->addAttribute('alt', $alt);
            }
            if (empty($this->arguments['title']) && $title) {
                $this->tag->addAttribute('title', $title);
            }
        } catch (ResourceDoesNotExistException $e) {
            // thrown if file does not exist
            throw new Exception($e->getMessage(), 1509741911, $e);
        } catch (\UnexpectedValueException $e) {
            // thrown if a file has been replaced with a folder
            throw new Exception($e->getMessage(), 1509741912, $e);
        } catch (\RuntimeException $e) {
            // RuntimeException thrown if a file is outside of a storage
            throw new Exception($e->getMessage(), 1509741913, $e);
        } catch (\InvalidArgumentException $e) {
            // thrown if file storage does not exist
            throw new Exception($e->getMessage(), 1509741914, $e);
        }

        return $this->tag->render();
    }
1164869
public function registerClientScript()
    {
        $view = $this->getView();
        // Register jQuery image cropping js and css files
        CropperAsset::register($view);
        // Additional plugin options
        $options = Json::encode($this->pluginOptions);

        $selector = "#$this->id .crop-image-container > img";

        if ($this->modal) {
            $ajaxOptions = Json::encode($this->ajaxOptions);
            $view->registerJs(<<<JS
(function() {

    var modalBox = $("#$this->id"),
        image = $("$selector"),
        cropBoxData,
        canvasData,
        cropUrl;

    modalBox.on("shown.bs.modal", function (event) {
        var button = $(event.relatedTarget); // Button that triggered the modal
        cropUrl = button.data('crop-url'); // Extract info from data-* attributes

        image.cropper($.extend({
            built: function () {
                // Strict mode: set crop box data first
                image.cropper('setCropBoxData', cropBoxData);
                image.cropper('setCanvasData', canvasData);
            },
            dragend: function() {
                cropBoxData = image.cropper('getCropBoxData');
                canvasData = image.cropper('getCanvasData');
            }
        }, $options));
    }).on('hidden.bs.modal', function () {
        cropBoxData = image.cropper('getCropBoxData');
        canvasData = image.cropper('getCanvasData');
        image.cropper('destroy');
    });

    $(document).on("click", "#$this->id .crop-submit", function(e) {
        e.preventDefault();

        $.ajax($.extend({
            method: "POST",
            url: cropUrl,
            data: image.cropper("getData"),
            dataType: "JSON",
            error: function() {
                alert("Error while cropping");
            }
        }, $ajaxOptions));

        modalBox.modal("hide");
    });

})();
JS
            );
        } else {
            $view->registerJs(";$(\"$selector\").cropper($options);");
        }
    }
1109828
public function uploadPhoto()
    {
        $result = [];
        if ($this->validate()) {
            $fileOrgname = Helper::validateFilename($this->file->name, 40);
            $filename = $fileOrgname;
            $filePath = Media::getCurrentDirectory() . DIRECTORY_SEPARATOR . $filename;
            $result['originName'] = $this->file->name;
            if ($this->file->saveAs($filePath)) {
                $result['originPath'] = $filePath;
                if ($this->options->resize) {
                    $tsize = (new Size(getimagesize($filePath)))->resize($this->options->resizeTo);
                    $size    = new \Imagine\Image\Box($tsize->width, $tsize->height);
                    $imagine = new \Imagine\Gd\Imagine();
                    $resizedName = 'primary_' . $filename;
                    $resizedPath = Media::getCurrentDirectory() . DIRECTORY_SEPARATOR . $resizedName;
                    $imagine->open($filePath)->resize($size)->save($resizedPath);
                    $filename = $resizedName;
                    $filePath = $resizedPath;
                }
                $result['success'] =  true;
                $result['fileName'] = $filename;
                $result['filePath'] = $filePath;
                $result['size'] = filesize($filePath);
                if ($this->options->generateThumbnail) {
                    $thumbName = 'thumb_' . $fileOrgname;
                    $thumbPath = Media::getCurrentDirectory() . DIRECTORY_SEPARATOR . $thumbName;
                    $tsize = (new Size(getimagesize($filePath)))->resize($this->options->thumbnailSize);
                    $size    = new \Imagine\Image\Box($tsize->width, $tsize->height);
                    $imagine = new \Imagine\Gd\Imagine();
                    try {
                        $imagine->open($filePath)->thumbnail($size)->save($thumbPath);
                        $result['thumbnailPath'] = $thumbPath;
                        $result['thumbnailName'] = $thumbName;

                    } catch (\Exception $e) {
                        //Nothing to do
                        \Yii::$app->log->logger->log($e);
                    }
                }
            }

        }
        $result['error'] = new ModelErrors($this->getErrors());
        return new UploadResult($result);
    }
1172822
public function getImageDimensions()
    {
        $dimension = $this->getData()->chained->getComponent()->_getSetting('dimension');
        if ($this->getData()->chained->getComponent()->getRow()->use_crop) {
            $parentDimensions = $this->_getImageEnlargeComponent()->getImageDimensions();
            $dimension['crop'] = $parentDimensions['crop'];
        }
        $data = $this->getImageData();
        return Kwf_Media_Image::calculateScaleDimensions($data['file'], $dimension);
    }
914593
public function loadImageHandle()
    {
        if (method_exists($this, 'cacheable') && $this->cacheable()) {
            return $this->getHandleFromCache();
        }

        return $this->makeImage($this->getOriginalImageFile());
    }