Save the transformed file

@param string $endpoint
@param BinaryInterface $cropedFile
@param array $data
488736
public function saveTransformedFile($endpoint, BinaryInterface $cropedFile, array $data)
    {
        $this
            ->filesystemMap
            ->get(
                $this->configuration->getValue($endpoint, 'croped_fs')
            )
            ->write(
                $data['filename'],
                $cropedFile->getContent()
            );
    }
44273
public function cropImage(Image $file, $left, $top, $width, $height, $quality = 95)
	{
		if ( ! $file instanceof Image) {
			throw new Exception\RuntimeException('Image entity expected');
		}

		$filename = $this->getFilesystemPath($file);
		$cropper = $this->getImageCropper();
		$cropper->setSourceFile($filename)
				->setOutputFile($filename)
				->setOutputQuality($quality)
				->setLeft($left)
				->setTop($top)
				->setWidth($width)
				->setHeight($height);
		$cropper->process();

		$file->setWidth($width);
		$file->setHeight($height);

		$entityManager = $this->getDoctrineEntityManager();
		$entityManager->persist($file);
		$entityManager->flush();

		$this->recreateImageSizes($file);
	}
836639
protected function saveBean($bean, $data)
    {
        // Handle File Field that may not in the $data, because Filename always go into $_FILES.
        foreach ($_FILES as $fieldName => $file) {
            $data[$fieldName] = $file["name"];
        }

        // Store Showing fields only
        $fields = $this->getShowFields();

        foreach ($fields as $field) {
            $fieldType = $field->getFieldType();

            // Check is unique
            if ($field->isUnique()) {

                // Try to find duplicate beans
                $fieldName = $field->getName();
                $duplicateBeans = R::find($bean->getMeta('type'), " $fieldName = ? ", [$data[$field->getName()]]);

                if (count($duplicateBeans) > 0) {
                    // TODO
                }
            }

            if($fieldType->getBeforeSaveBeanClosure() != null) {
                $beforeSaveBeanClosure = $fieldType->getBeforeSaveBeanClosure();
                $beforeSaveBeanClosure($bean, $field->getStoreValue($data));
            } else if ($field->getFieldRelation() == Field::MANY_TO_MANY) {
                // 1. Many to many

                // http://www.redbeanphp.com/many_to_many
                $keyName = "shared" . ucfirst($field->getName()) . "List";

                // Clear the current list (tableB_tableA)
                try {
                    $tableName = $this->getTableName() . "_" . $field->getName();
                    $idName = $this->getTableName() . "_id";
                    R::exec("DELETE FROM $tableName WHERE $idName = ?", [$bean->id]);
                } catch (\Exception $ex) {
                }

                // Clear the current list (tableA_tableB)
                try {
                    $tableName = $field->getName() . "_" . $this->getTableName();
                    $idName = $this->getTableName() . "_id";
                    R::exec("DELETE FROM $tableName WHERE $idName = ?", [$bean->id]);
                } catch (\Exception $ex) {
                }

                // If User have checked a value in checkbox
                if (isset($data[$field->getName()])) {
                    $valueList = $data[$field->getName()];
                    $slots = R::genSlots($valueList);
                    $relatedBeans = R::find($field->getName(), " id IN ($slots)", $valueList);

                    foreach ($relatedBeans as $relatedBean) {
                        $bean->{$keyName}[] = $relatedBean;
                    }
                }

            } else if ($field->getFieldRelation() == Field::ONE_TO_MANY) {
                // TODO One to many

            } else if (! $field->isStorable()) {

                // 2. If not storable, skip
                continue;

            } elseif ($field->getFieldRelation() == Field::NORMAL) {
                // 3.Normal data field

                $value = $field->getStoreValue($data);

                if ($value == LouisCRUD::NULL) {
                    $value = null;
                }

                // Validate the value
                if ($field->isStorable())
                    $validateResult = $field->validate($value, $data);
                else {
                    // TODO: check non-storable?
                    $validateResult = true;
                }

                // If validate failed, return result object.
                if ($validateResult !== true) {
                    $result = new Result();
                    $result->id = @$bean->id;
                    $result->msg = $validateResult;
                    $result->fieldName = $field->getName();
                    $result->class = "callout-danger";
                    return $result;
                }

                // Set the value to the current bean directly
                $bean->{$field->getName()} = $value;

            }
        }

        // Store
        // Return result object
        $result = new Result();

        try {

            if ($bean->id > 0) {

                if ($this->beforeUpdateBean != null) {
                    $callable = $this->beforeUpdateBean;
                    $callable($this->currentBean);
                }

            } else {

                if ($this->beforeInsertBean != null) {
                    $callable = $this->beforeInsertBean;
                    $callable($bean);
                }

            }

            $id = R::store($bean);
            $needStore = false;
            foreach ($fields as $field) {
                $fieldType = $field->getFieldType();
                if($fieldType->getAfterSaveBeanClosure() != null) {
                    $afterSaveBeanClosure = $fieldType->getAfterSaveBeanClosure();
                    $needStore |= !!$afterSaveBeanClosure($bean, $field->getStoreValue($data));
                }
            }
            if($needStore) {
                $id = R::store($bean);
            }
            $result->id = $id;
            $result->redirect_url = Stringy::create($this->getCreateSuccURL())->replace("{id}", $id)->__toString();
        } catch (\Exception $ex) {
            $result->ok = false;
            $result->class = "callout-danger";


            if ($bean->id > 0) {
                $callback = $this->onUpdateError;
                $result->msg = $callback($ex->getMessage());
            } else {
                $callback = $this->onInsertError;
                $result->msg = $callback($ex->getMessage());
            }

        }

        return $result;
    }
615289
protected function resolveInterfaceExtension(InterfaceDefinition $definition, Endpoint $endpoint): void
    {
        $bundleNamespace = ClassUtils::relatedBundleNamespace($definition->getClass());
        $extensionClass = ClassUtils::applyNamingConvention($bundleNamespace, 'Extension', null, $definition->getName().'Extension');
        if (class_exists($extensionClass)) {
            foreach ($definition->getImplementors() as $implementor) {
                $definition->addExtension($extensionClass);
                $object = $endpoint->getType($implementor);
                if ($object instanceof HasExtensionsInterface) {
                    $object->addExtension($extensionClass);
                }
            }
        }
    }
833447
public function call(string $method, string $endpoint, array $data = []): array
    {
        $method = strtolower($method);
        if (!in_array($method, ['get', 'put', 'post', 'delete', 'patch'])) {
            throw new MailchimpException('Invalid API call method: ' . $method);
        }
        if (in_array($method, ['get', 'delete'])) {
            $url = $this->baseurl . $endpoint;
            $url .= $data ? '?' . http_build_query($data) : '';
            $response = Requests::$method($url, $this->headers(), $this->options());
        } else {
            $response = Requests::$method(
                $this->baseurl . $endpoint,
                $this->headers(),
                json_encode($data),
                $this->options()
            );
        }
        $this->responseCode = intval($response->status_code);
        if ($this->responseCode >= 400) {
            $this->apiError($response);
        }
        return json_decode($response->body, true) ?? [];
    }
587775
def generate(self, save=True):
        
        stretched_photo, crop_box = self._generate_img()

        # set crop_box to (0,0,0,0) if photo not cropped
        if not crop_box:
            crop_box = 0, 0, 0, 0

        self.crop_left, self.crop_top, right, bottom = crop_box
        self.crop_width = right - self.crop_left
        self.crop_height = bottom - self.crop_top

        self.width, self.height = stretched_photo.size

        f = StringIO()
        imgf = (self.photo._get_image().format or
                Image.EXTENSION[path.splitext(self.photo.image.name)[1]])

        stretched_photo.save(f, format=imgf, quality=self.format.resample_quality)
        f.seek(0)

        self.image.save(self.file(), ContentFile(f.read()), save)
934979
public function save($data = null) {
		if (!parent::save()) {
			return false;
		}

		if ($data) {
			// new image
			$this->simpletype = 'image';
			$this->saveImageFile($data);
			$this->saveThumbnails();
			$this->extractExifData();
		}

		return true;
	}
935363
private function transformLayer(&$layer, $transform, $sourceExtension)
    {
        /** @var ConfigModel $settings */
        $config = ImagerService::getConfig();

        // Apply any pre resize filters
        if (isset($transform['preEffects'])) {
            $this->applyEffects($layer, $transform['preEffects']);
        }

        try {
            // Get size and crop information
            $originalSize = $layer->getSize();
            $cropSize = ImagerHelpers::getCropSize($originalSize, $transform, $config->getSetting('allowUpscale', $transform));
            $resizeSize = ImagerHelpers::getResizeSize($originalSize, $transform, $config->getSetting('allowUpscale', $transform));
            $filterMethod = $this->getFilterMethod($transform);

            // Do the resize
            if (ImagerService::$imageDriver === 'imagick' && $config->getSetting('smartResizeEnabled', $transform)) {
                /** @var ImagickImage $layer */
                $layer->smartResize($resizeSize, (bool)Craft::$app->config->general->preserveImageColorProfiles, $config->getSetting('jpegQuality', $transform));
            } else {
                $layer->resize($resizeSize, $filterMethod);
            }

            // Do the crop
            if (!isset($transform['mode']) || mb_strtolower($transform['mode']) === 'crop' || mb_strtolower($transform['mode']) === 'croponly') {
                $cropPoint = ImagerHelpers::getCropPoint($resizeSize, $cropSize, $config->getSetting('position', $transform));
                $layer->crop($cropPoint, $cropSize);
            }
        } catch (InvalidArgumentException $e) {
            throw new ImagerException($e->getMessage(), $e->getCode(), $e);
        } catch (RuntimeException $e) {
            throw new ImagerException($e->getMessage(), $e->getCode(), $e);
        }

        // Letterbox, add padding
        if (isset($transform['mode']) && mb_strtolower($transform['mode']) === 'letterbox') {
            $this->applyLetterbox($layer, $transform);
        }

        // Apply post resize effects
        if (isset($transform['effects'])) {
            $this->applyEffects($layer, $transform['effects']);
        }

        // Interlace if true
        if ($config->getSetting('interlace', $transform)) {
            $interlaceVal = $config->getSetting('interlace', $transform);

            if (\is_string($interlaceVal)) {
                $layer->interlace(ImagerService::$interlaceKeyTranslate[$interlaceVal]);
            } else {
                $layer->interlace(ImagerService::$interlaceKeyTranslate['line']);
            }
        }

        // Apply watermark if enabled
        if (isset($transform['watermark'])) {
            $this->applyWatermark($layer, $transform['watermark']);
        }

        // Apply background color if enabled and applicable
        if (($sourceExtension !== 'jpg') && ($config->getSetting('bgColor', $transform) !== '')) {
            $this->applyBackgroundColor($layer, $config->getSetting('bgColor', $transform));
        }
    }
641632
private function endpoint($endpoint, $schema = null, $doc_id = null, $file_id = null)
    {
        $endpoints = [
            'auth' => 'auth/',
            'user' => 'auth/user/',
            'schema-list' => 'schemas/',
            'schema-detail' => 'schemas/%s/',
            'document-query' => 'schemas/%s/query/',
            'document-save' => 'schemas/%s/save/',
            'document-detail' => 'schemas/%s/%s/',
            'file-list' => 'files/',
            'file-detail' => 'files/%s/',
        ];

        if (!array_key_exists($endpoint, $endpoints))
        {
            throw new MontageUnknownEndpointException(
                sprintf('Unknown endpoint "%s" requested.', $endpoint)
            );
        }

        //do the endpoint formatting
        if (!is_null($file_id)) {
            return sprintf($endpoints[$endpoint], $file_id);
        } else if (!is_null($schema) && !is_null($doc_id)) {
            return sprintf($endpoints[$endpoint], $schema, $doc_id);
        } else if (!is_null($schema)) {
            return sprintf($endpoints[$endpoint], $schema);
        }

        return $endpoints[$endpoint];
    }
739572
public function store(BinaryInterface $binary, $path, $filter)
    {
        $tmpFile = tmpfile();
        fwrite($tmpFile, $binary->getContent());
        $tmpMetadata = stream_get_meta_data($tmpFile);

        $binaryCreateStruct = $this->ioService->newBinaryCreateStructFromLocalFile($tmpMetadata['uri']);
        $binaryCreateStruct->id = $this->getFilePath($path, $filter);
        $this->ioService->createBinaryFile($binaryCreateStruct);

        fclose($tmpFile);
    }
746666
public static function appendDataToFile($filePath, $data, $newLine = false) {
        if ($newLine) {
            file_put_contents($filePath, $data . PHP_EOL, FILE_APPEND);
        } else {
            file_put_contents($filePath, $data, FILE_APPEND);
        }
    }
542549
private void save() {

        if ((m_focalPoint != null) && isEditable()) {
            int x = (int)m_focalPoint.getX();
            int y = (int)m_focalPoint.getY();
            String val = "" + x + "," + y;
            CmsUUID sid = m_imageInfoProvider.get().getStructureId();
            List<CmsPropertyModification> propChanges = new ArrayList<>();
            propChanges.add(new CmsPropertyModification(sid, CmsGwtConstants.PROPERTY_IMAGE_FOCALPOINT, val, false));
            final CmsPropertyChangeSet changeSet = new CmsPropertyChangeSet(sid, propChanges);
            CmsRpcAction<Void> action = new CmsRpcAction<Void>() {

                @Override
                public void execute() {

                    CmsCoreProvider.getVfsService().saveProperties(changeSet, this);

                }

                @SuppressWarnings("synthetic-access")
                @Override
                protected void onResponse(Void result) {

                    m_savedFocalPoint = m_focalPoint;

                    if (m_pointWidget != null) {
                        m_pointWidget.setIsDefault(false);
                    }
                    m_imageInfoProvider.get().setFocalPoint(m_focalPoint);
                    if (m_nextAction != null) {
                        m_nextAction.run();
                    }

                }
            };
            action.execute();

        }
    }
405034
public function saveFile($path, $data)
    {
        $storage = $data;

        if ($data instanceof Slice)
        {
            $storage = $data->asArray();
        }

        switch ($this->type)
        {
            case PHP:
                $result = '<?php'
                    . PHP_EOL
                    . PHP_EOL .
                    'return ' . var_export($storage, true) . ';';
                break;

            case YML:
                $result = \Symfony\Component\Yaml\Yaml::dump($storage);
                break;

            case JSON:
                $json = clone $this->helper->json();
                $json->addOption(JSON_PRETTY_PRINT);
                $result = $json->encode($storage);
                break;

            default:
                throw new Exceptions\TypeNotFound($this->type);
        }

        $filePath = $this->path($path);

        return file_put_contents($filePath, $result);
    }
1307608
protected function appendLines(array &$stepActionParams, array &$endpointOptions, array &$context)
    {
        $stepParamsResolver = new OptionsResolver();
        $stepParamsResolver->setRequired([
            self::PARAM_CSV_ROWS,
        ]);
        $stepParamsResolver->setDefault(self::PARAM_FILE_NAME, $endpointOptions[CsvConfigurableProtocol::OPTION_PATH]);
        $stepParamsResolver->setDefault(self::PARAM_HEADERS, null);
        $params = $stepParamsResolver->resolve($stepActionParams);

        $filePath = $params[self::PARAM_FILE_NAME];
        $fullPath = $this->getRootPath($endpointOptions).DIRECTORY_SEPARATOR.$filePath;

        $rows = $params[self::PARAM_CSV_ROWS];

        $headers = $params[self::PARAM_HEADERS];
        if (is_array($headers) && !file_exists($fullPath)) {
            $rows = array_merge([$headers], $rows);
        }

        $fileHandle = $this->getFileHandle($fullPath, 'a');

        foreach ($rows as $row) {
            if (!is_array($row)) {
                $type = gettype($row);
                throw new \InvalidArgumentException("Row in Rows is not an array, {$type} given.");
            }

            fputcsv($fileHandle, $row, $endpointOptions[CsvConfigurableProtocol::OPTION_DELIMITER], $endpointOptions[CsvConfigurableProtocol::OPTION_ENCLOSURE], $endpointOptions[CsvConfigurableProtocol::OPTION_ESCAPE_CHAR]);
        }
    }
290554
public function closeArchiveAndCopyToStream($streamPointer)
    {
        $zip = $this->createOrGetZip();
        $zip->close();
        unset($this->zip);

        $this->copyZipToStream($streamPointer);
    }
461365
private function doMultipartUpload ($endpoint, $type, $stream, array $extra = [])
    {
        return json_decode(
            $this->client->send(
                new Request(
                    'POST',
                    Uri::withQueryValue(new Uri($endpoint), 'type', $type),
                    [],
                    new MultipartStream(array_merge([
                        [
                            'name'     => 'media',
                            'contents' => $stream,
                        ],
                    ], $extra))
                )
            )->getBody()
        );
    }
1187238
public function post(
        string $endpoint,
        array $options
    )
    {
        $this->streamBody = $this->client
            ->post($endpoint, $options)
            ->getBody();
    }