If enabled, crop the image, save as a new file, and link it via relation
@return void
507556
public function saveInto(DataObjectInterface $object) {
		if(!$this->canCrop() || !$this->hasSourceFile()) {
			return;
		}
		$object->setField($this->getName() . 'ID', $this->generateCropped()->ID);
		$object->write();
	}
624542
public function onBeforeWrite()
    {
        if (!$this->Original()->exists() && $this->Cropped()->exists()) {
            $this->Cropped()->delete();
        } elseif ($this->Original()->exists()) {
            $changes = $this->getChangedFields();

            if ($this->hasChanged($changes, 'ContainerX') ||
                $this->hasChanged($changes, 'ContainerY') ||
                $this->hasChanged($changes, 'ContainerWidth') ||
                $this->hasChanged($changes, 'ContainerHeight') ||
                $this->hasChanged($changes, 'CropperX') ||
                $this->hasChanged($changes, 'CropperY') ||
                $this->hasChanged($changes, 'CropperWidth') ||
                $this->hasChanged($changes, 'CropperHeight')) {
                    $this->doCrop = true;
            }
        }

        parent::onBeforeWrite();
    }
1307455
public function imageReset()
    {
        $this->imageRemoveFile();
        $this->owner->setAttribute($this->imageAttribute, null);
        $this->owner->updateAttributes([$this->imageAttribute]);
    }
520034
protected function imageProcess()
    {
        if ($this->saved) {
            if (!$this->image)  $this->image = ImageManager::make($this->saved);

            if ($this->image_callable) {
                $callable = $this->image_callable;
                $callable($this->image);
            }

            if (count($this->resize)) {
                foreach ($this->resize as $resize) {
                    $this->image->resize($resize["width"], $resize["height"]);
                    $this->image->save($this->parseString($resize["filename"]));
                }
            }

            if (count($this->fit)) {
                foreach ($this->fit as $fit) {
                    $this->image->fit($fit["width"], $fit["height"]);
                    $this->image->save($this->parseString($fit["filename"]));
                }
            }

        }
    }
132362
function save($path_copy = null, $quality = 100)
    {
        if($path_copy)
        {
            $copy = $path_copy;
        }
        else
        {
            $copy = $this->path_image;
        }

        //---Guardar la imagen en el tipo de archivo correcto
        switch($this->type){
            case IMAGETYPE_JPEG:
                imagejpeg($this->image, $copy, $quality);
                break;
            case IMAGETYPE_GIF:
                imagegif($this->image, $copy);
                break;
            case IMAGETYPE_PNG:
                $pngquality = floor(($quality - 10) / 10);
                imagepng($this->image, $copy, $pngquality);
                break;
        }
    }
333622
protected function process()
    {

        // query whether or not we've to upload the image files
        if ($this->getSubject()->hasCopyImages()) {
            // initialize the image path
            if ($imagePath = $this->getValue(ColumnKeys::IMAGE_PATH)) {
                // upload the file and set the new image path
                $imagePath = $this->getSubject()->uploadFile($imagePath);

                // log a message that the image has been copied
                $this->getSubject()->getSystemLogger()->debug(
                    sprintf('Successfully copied image %s => %s', $imagePath, $imagePath)
                );

                // write the new image path to the target column
                $this->setValue(ColumnKeys::IMAGE_PATH, $imagePath);
            }
        }
    }
957694
public function beforeSave()
    {
        /* @var $model ActiveRecord */
        $model = $this->owner;
        foreach ($this->attributes as $attr => $options) {
            $this->ensureAttribute($attr, $options);
            if ($file = UploadedFile::getInstance($model, $attr)) {
                $this->createDirIfNotExists($attr);
                if (!$model->isNewRecord) {
                    $this->deleteFiles($attr);
                }
                $fileName = uniqid() . '.' . $file->extension;
                if ($this->needCrop($attr)) {
                    $coords = $this->getCoords($attr);
                    if ($coords === false) {
                        throw new InvalidCallException();
                    }
                    $image = $this->crop($file, $coords, $options);
                    $image->save($this->getSavePath($attr) . $fileName);
                } else {
                    $image = $this->processImage($file->tempName, $options);
                    $image->save($this->getSavePath($attr) . $fileName);
                }
                $model->{$attr} = $fileName;

                if ($this->issetThumbnails($attr)) {
                    $thumbnails = $this->attributes[$attr]['thumbnails'];
                    foreach ($thumbnails as $name => $options) {
                        $this->ensureAttribute($name, $options);
                        $tmbFileName = $name . '_' . $fileName;
                        $image = $this->processImage($this->getSavePath($attr) . $fileName, $options);
                        $image->save($this->getSavePath($attr) . $tmbFileName);
                    }
                }
            } elseif (isset($model->oldAttributes[$attr])) {
                $model->{$attr} = $model->oldAttributes[$attr];
            }
        }
    }
41485
public function do_crop($width, $height, $offsetX = 0, $offsetY = 0)
    {
        if (version_compare(PHP_VERSION, '5.5.0') < 0) {
            $image = imagecreatetruecolor($width, $height);
            imagealphablending($image, false);
            imagesavealpha($image, true);
            imagecopy($image, $this->_image, 0, 0, $offsetX, $offsetY, $width, $height);
        } else {
            $rect = ['x' => $offsetX, 'y' => $offsetY, 'width' => $width, 'height' => $height];
            $image = imagecrop($this->_image, $rect);
        }

        imagedestroy($this->_image);
        $this->_image = $image;
        $this->_width = imagesx($image);
        $this->_height = imagesy($image);

        return $this;
    }
1267269
public function setPhoto($photo)
	{
		if (is_string($photo)) {
			$this->photo = $photo;
		} else if (is_resource($photo)) {
			$this->addMultipart("photo", $photo);
			$this->photo = "attach://photo";
		} else if ($photo instanceof InputFile) {
			$this->addMultipart("photo", $photo->getFile());
			$this->photo = "attach://photo";
		}
	}
532992
public function saveModel()
    {
        $fileName = basename($this->filePath);
        $fullName = str_replace('\\', '/', $this->fullName);
        $at = new Attachment([
            'filename' => $fileName,
            'original_name' => $this->oriName,
            'path' => $fullName,
            'size' => $this->fileSize,
            'type' => $this->fileType,
        ]);
        return $at->save();
    }
966470
public function save()
    {
        $myConfig = \OxidEsales\Eshop\Core\Registry::getConfig();

        if ($myConfig->isDemoShop()) {
            // disabling uploading pictures if this is demo shop
            $oEx = oxNew(\OxidEsales\Eshop\Core\Exception\ExceptionToDisplay::class);
            $oEx->setMessage('ARTICLE_PICTURES_UPLOADISDISABLED');
            \OxidEsales\Eshop\Core\Registry::getUtilsView()->addErrorToDisplay($oEx, false);

            return;
        }

        parent::save();

        $oArticle = oxNew(\OxidEsales\Eshop\Application\Model\Article::class);
        if ($oArticle->load($this->getEditObjectId())) {
            $oArticle->assign(\OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter("editval"));
            \OxidEsales\Eshop\Core\Registry::getUtilsFile()->processFiles($oArticle);

            // Show that no new image added
            if (\OxidEsales\Eshop\Core\Registry::getUtilsFile()->getNewFilesCounter() == 0) {
                $oEx = oxNew(\OxidEsales\Eshop\Core\Exception\ExceptionToDisplay::class);
                $oEx->setMessage('NO_PICTURES_CHANGES');
                \OxidEsales\Eshop\Core\Registry::getUtilsView()->addErrorToDisplay($oEx, false);
            }

            $oArticle->save();
        }
    }
1166430
public function changePicture()
    {
        $id = $this->Auth->user('id');

        if ($this->request->getData('file')) {
            //Deletes any picture that already exists
            foreach (((new Folder(USER_PICTURES))->find($id . '\..+')) as $filename) {
                @unlink(USER_PICTURES . $filename);
            }

            $filename = sprintf('%s.%s', $id, pathinfo($this->request->getData('file')['tmp_name'], PATHINFO_EXTENSION));

            $uploaded = $this->Uploader->set($this->request->getData('file'))
                ->mimetype('image')
                ->save(USER_PICTURES, $filename);

            if (!$uploaded) {
                return $this->setUploadError($this->Uploader->getError());
            }

            //Updates the authentication data and clears similar thumbnails
            $this->Auth->setUser(array_merge($this->Auth->user(), ['picture' => $uploaded]));
            (new ThumbManager)->clear($uploaded);
        }
    }
751001
protected function process()
    {

        // query whether or not the media gallery has to be cleaned up
        if ($this->getSubject()->getConfiguration()->hasParam(ConfigurationKeys::CLEAN_UP_MEDIA_GALLERY) &&
            $this->getSubject()->getConfiguration()->getParam(ConfigurationKeys::CLEAN_UP_MEDIA_GALLERY)
        ) {
            // initialize the array for the actual images
            $actualImageNames = array();

            // iterate over the available image fields
            foreach (array_keys($this->getImageTypes()) as $imageColumnName) {
                if ($this->hasValue($imageColumnName) && !in_array($imageName = $this->getValue($imageColumnName), $actualImageNames)) {
                    $actualImageNames[] = $imageName;
                }
            }

            // query whether or not, we've additional images
            if ($additionalImages = $this->getValue(ColumnKeys::ADDITIONAL_IMAGES, null, array($this, 'explode'))) {
                foreach ($additionalImages as $additionalImageName) {
                    // do nothing if the image has already been added, e. g. it is the base image
                    if (in_array($additionalImageName, $actualImageNames)) {
                        continue;
                    }

                    // else, add the image to the array
                    $actualImageNames[] = $additionalImageName;
                }
            }

            // load the existing media gallery entities for the produdct with the given SKU
            $existingProductMediaGalleries = $this->getProductMediaProcessor()
                                                  ->getProductMediaGalleriesBySku($sku = $this->getValue(ColumnKeys::SKU));

            // remove the images that are NOT longer available in the CSV file
            foreach ($existingProductMediaGalleries as $existingProductMediaGallery) {
                // do nothing if the file still exists
                if (in_array($existingImageName = $existingProductMediaGallery[MemberNames::VALUE], $actualImageNames)) {
                    continue;
                }

                try {
                    // remove the old image from the database
                    $this->getProductMediaProcessor()
                         ->deleteProductMediaGallery(array(MemberNames::VALUE_ID => $existingProductMediaGallery[MemberNames::VALUE_ID]));

                    // log a debug message that the image has been removed
                    $this->getSubject()
                         ->getSystemLogger()
                         ->warning(
                             $this->getSubject()->appendExceptionSuffix(
                                 sprintf(
                                     'Successfully removed image "%s" from media gallery for product with SKU "%s"',
                                     $existingImageName,
                                     $sku
                                 )
                             )
                         );
                } catch (\Exception $e) {
                    // log a warning if debug mode has been enabled and the file is NOT available
                    if ($this->getSubject()->isDebugMode()) {
                        $this->getSubject()
                             ->getSystemLogger()
                             ->warning($this->getSubject()->appendExceptionSuffix($e->getMessage()));
                    } else {
                        throw $e;
                    }
                }
            }

            // log a message that the images has been cleaned-up
            $this->getSubject()
                 ->getSystemLogger()
                 ->debug(
                     $this->getSubject()->appendExceptionSuffix(
                         sprintf(
                             'Successfully cleaned-up media gallery for product with SKU "%s"',
                             $sku
                         )
                     )
                 );
        }
    }
1024731
public function afterSave()
    {
        if (!$this->files) {
            return true;
        }
        $oldFileCount = $this->getFileCount();
        /**
         * @var UploadedFile $file
         */
        foreach ($this->files as $key => $file) {
            $this->fileNumber = $oldFileCount + $key + 1;
            $this->fileName = $this->fileNumber . '_' . $file->name;
            if ($this->fileNumber == 1) {
                $this->owner->updateAttributes([$this->fileField => $this->fileName]);
            }
            $path = $this->getFilePath(null, $this->fileName);
            $this->createFilePath($path);
            $file->saveAs($path);
            foreach ($this->imageSettings as $name => $options) {
                $this->processImage($name, $options);
            }    
        }
    }
1158233
public function save()
    {
        $file = $this->getFilename() . '.' . $this->getFileExtension();

        // Add save path if given
        if (null !== $this->savePath) {
            $file = $this->savePath . $file;
        }

        file_put_contents(
            $file,
            $this->getOutput()
        );
    }
618913
public function create() {
        switch($this->info[2]) {
            case IMAGETYPE_JPEG:
                $this->resource = imagecreatefromjpeg($this->file);
                break;
            case IMAGETYPE_GIF:
                $this->resource = imagecreatefromgif($this->file);
                break;
            case IMAGETYPE_PNG:
                $this->resource = imagecreatefrompng($this->file);
                break;
            default:
                throw new Exception('Image type is not supported');
                break;
        }
    }
369009
private function hookupUI()
    {
        // TODO: Still need to hook up the edit attachment page

        add_filter('media_row_actions',function($actions,$post){
            $newaction['ilab_crop_image'] = '<a class="ilab-thickbox" href="'.$this->cropPageURL($post->ID).'" title="Crop Image">' . __('Crop Image') . '</a>';
            return array_merge($actions,$newaction);
        },10,2);

        add_filter('admin_post_thumbnail_html', function($content,$id){
            if (!has_post_thumbnail($id))
                return $content;

            $image_id = get_post_thumbnail_id($id);
            if (!current_user_can('edit_post',$image_id))
                return $content;

            $content.='<a class="ilab-thickbox" href="'.$this->cropPageURL($image_id).'">'.__('Crop Image').'</a>';
            return $content;
        },10,2);

        add_action( 'wp_enqueue_media', function () {
            remove_action('admin_footer', 'wp_print_media_templates');

            add_action('admin_footer', function(){
                ob_start();
                wp_print_media_templates();
                $result=ob_get_clean();
                echo $result;


                $sizes=ilab_get_image_sizes();
                $sizeKeys=array_keys($sizes);

                ?>
                <script>
                    jQuery(document).ready(function() {
                        jQuery('input[type="button"]')
                            .filter(function() {
                                return this.id.match(/imgedit-open-btn-[0-9]+/);
                            })
                            .each(function(){
                                var image_id=this.id.match(/imgedit-open-btn-([0-9]+)/)[1];
                                var button=jQuery('<input type="button" class="button" style="margin-left:5px;" value="Crop Image">');
                                jQuery(this).after(button);

                                button.on('click',function(e){
                                    e.preventDefault();

                                    ILabModal.loadURL("<?php echo get_admin_url(null, 'admin-ajax.php')?>?action=ilab_crop_image_page&size=<?php echo $sizeKeys[0]?>&post="+image_id,false,null);

                                    return false;
                                });
                            });

                        attachTemplate=jQuery('#tmpl-image-details');
                        if (attachTemplate)
                            attachTemplate.text(attachTemplate.text().replace(/(<input type="button" class="replace-attachment button")/,'<a href="<?php echo $this->cropPageURL('{{data.attachment.id}}')?>" class="ilab-thickbox button"><?php echo __('Crop Image') ?></a>&nbsp;$1'));

                        attachTemplate=jQuery('#tmpl-attachment-details-two-column');
                        if (attachTemplate)
                        {
                            attachTemplate.text(attachTemplate.text().replace(/(<button(?:.*)class="(?:.*)edit-attachment(?:.*)"[^>]*[^<]+<\/button>)/,'$1&nbsp;<a href="<?php echo $this->cropPageURL('{{data.id}}')?>" class="ilab-thickbox button"><?php echo __('Crop Image') ?></a>'));
                            attachTemplate.text(attachTemplate.text().replace(/(<a(?:.*)class="(?:.*)edit-imgix(?:.*)"[^>]*[^<]+<\/a>)/,'$1&nbsp;<a href="<?php echo $this->cropPageURL('{{data.id}}')?>" class="ilab-thickbox button"><?php echo __('Crop Image') ?></a>'));
                            attachTemplate.text(attachTemplate.text().replace(/(<a class="(?:.*)edit-attachment(?:.*)"[^>]+[^<]+<\/a>)/,'$1&nbsp;<a href="<?php echo $this->cropPageURL('{{data.id}}')?>" class="ilab-thickbox button"><?php echo __('Crop Image') ?></a>'));
                            attachTemplate.text(attachTemplate.text().replace(/(<a class="(?:.*)view-attachment(?:.*)"[^>]+[^<]+<\/a>)/,'$1 | <a class="ilab-thickbox" href="<?php echo $this->cropPageURL('{{data.id}}')?>"><?php echo __('Crop Image') ?></a>'));
                        }

                        attachTemplate=jQuery('#tmpl-attachment-details');
                        if (attachTemplate)
                        {
                            attachTemplate.text(attachTemplate.text().replace(/(<a(?:.*)class="(?:.*)edit-imgix(?:.*)"[^>]*[^<]+<\/a>)/, '$1<br><a class="ilab-thickbox" href="<?php echo $this->cropPageURL('{{data.id}}')?>"><?php echo __('Crop Image') ?></a>'));
                            attachTemplate.text(attachTemplate.text().replace(/(<a class="(?:.*)edit-attachment(?:.*)"[^>]+[^<]+<\/a>)/, '$1\n<a class="ilab-thickbox" href="<?php echo $this->cropPageURL('{{data.id}}')?>"><?php echo __('Crop Image') ?></a>'));
                        }
                    });
                </script>
                <?php
            },1000);
        } );
    }