Save temporary file and return filename

@param GdImage|ImagickImage $imageInstance
@param string               $sourceExtension

@return string

@throws ImagerException
166673
private function saveTemporaryFile($imageInstance, $sourceExtension): string
    {
        $tempPath = Craft::$app->getPath()->getRuntimePath().'imager/temp/';

        // Check if the path exists
        if (!realpath($tempPath)) {
            try {
                FileHelper::createDirectory($tempPath);
            } catch (Exception $e) {
                // just ignore for now, trying to create
            }

            if (!realpath($tempPath)) {
                $msg = Craft::t('imager', 'Temp folder “{tempPath}” does not exist and could not be created', ['tempPath' => $tempPath]);
                Craft::error($msg, __METHOD__);
                throw new ImagerException($msg);
            }
        }

        $targetFilePath = $tempPath.md5(microtime()).'.'.$sourceExtension;

        $saveOptions = [
            'jpeg_quality' => 100,
            'png_compression_level' => 1,
            'flatten' => true
        ];

        $imageInstance->save($targetFilePath, $saveOptions);

        return $targetFilePath;
    }
1250934
public function saveImage(FileCreateOrUpdateEvent $event, FileModelInterface $imageModel)
    {
        return $this->saveFile($event->getParentId(), $imageModel);
    }
318651
public function upload($imageFile)
    {
        if ($imageFile instanceof UploadedFile) {
            if ($imageFile->isValid()) {
                $pictureId = $this->pictureIdGenerator->generate($imageFile);
                if(false === $this->disk->putFileAs('', $imageFile, $this->pictureUrlManager->getOriginalPath($pictureId))){
                    throw new UploadException();
                }
                return $pictureId;
            } else {
                throw new UploadException($imageFile->getErrorMessage());
            }
        } else {
            throw new UploadException();
        }
    }
1031208
public function createFromString($imageString)
    {
        $this->sourceImageResource = new \Imagick();

        try {

            return $this->sourceImageResource->readImageBlob($imageString);

        } catch (\ImagickException $e) {

            $this->errors[ $e->getCode() ] = $e->getMessage();

        }

        return false;
    }
789711
public static function saveImage( $fileName, $config, $data, $invertOrder = FALSE )
	{
		$graph	= self::buildGraph( $config, $data, $invertOrder );
		$graph->stroke( $fileName );
	}
840412
final public function saveImage($filename)
	{
		$extension = pathinfo($filename, PATHINFO_EXTENSION);

		if (! is_string($extension)) {
			$extension = image_type_to_extension($this->_image_type);
			$filename .= ".{$extension}";
		}

		switch(strtolower($extension))
		{
			case 'jpeg':
			case 'jpg':
				return $this->imageJPEG($filename);
				break;

			case 'png':
				return $this->imagePNG($filename);
				break;

			case 'gif':
				return $this->imageGIF($filename);

			default:
				trigger_error('Invalid extension or not an image', E_USER_WARNING);
				return false;
		}
	}
830339
protected function initSourceImageResource() 
    { 
    	$ext = $this->getExtension();
    	
    	switch($ext) {
		case 'gif':
			$this->sourceImageResource = ImageCreateFromGif($this->sourceImagePath);
			break;
    	
		case 'jpg':
			$this->sourceImageResource = ImageCreateFromJpeg($this->sourceImagePath);
			break;
    	
		case 'png':
			$this->sourceImageResource = ImageCreateFromPng($this->sourceImagePath);
			break;
    	
		default:
			throw new \RuntimeException("An error occurred trying to create the image, extension '" . $ext. "' is not supported");
			break;
    	}
    	
    	return $this;
    }
1324588
public function saveImageResource(ImageResource $imageResource) {
		$resource = $imageResource->getHandle();
		imagesavealpha($resource, true);
		IoUtils::imagePng($resource, $this->getFileName(), 9, PNG_ALL_FILTERS);
	}
476712
public static String getImageFileName(String originalFilename) {
    String namePart = StringUtils.substringBeforeLast(originalFilename, ".");
    String extensionPart = StringUtils.substringAfterLast(originalFilename, ".");

    // use PNG format if original image is PNG, otherwise always use JPEG
    if (StringUtils.equalsIgnoreCase(extensionPart, FileExtension.PNG)) {
      extensionPart = FileExtension.PNG;
    }
    else {
      extensionPart = FileExtension.JPEG;
    }
    return namePart + "." + extensionPart;
  }
582012
protected function store( $source, $destination, $width, $height, $crop ) {
		if ( file_exists( $destination ) ) {
			return $destination;
		}

		$editor = wp_get_image_editor( $source );

		if ( is_wp_error( $editor ) ) {
			return '';
		}

		$editor->resize( $width, $height, $crop );
		$editor->save( $destination );

		return $destination;
	}
1283711
private function validMimeImage($extension, $mimes)
    {
        if (is_array($mimes)) {
            foreach ($mimes as $mime) {
                if (!strstr($mime, 'image/')) {
                    throw new \InvalidArgumentException(htmlspecialchars(
                        "The extension $extension is not an image extension."
                    ));
                }
            }
        } else {
            if (!strstr($mimes, 'image/')) {
                throw new \InvalidArgumentException(htmlspecialchars(
                    "The extension $extension is not an image extension."
                ));
            }
        }
    }
1221737
protected static function calculateResourcePathname($filenamePath, $source)
    {
        $sourceFile = preg_replace("/'/", "", $source[1]);
        if (preg_match('/\#/', $sourceFile)) {
            $sourceFile = explode("#", $sourceFile);
            $sourceFile = $sourceFile[0];
        }
        if (preg_match('/\?/', $sourceFile)) {
            $sourceFile = explode("?", $sourceFile);
            $sourceFile = $sourceFile[0];
        }
        $orig = realpath(dirname($filenamePath) . DIRECTORY_SEPARATOR . $sourceFile);
        return $orig;
    }
150742
public static function create($contentDescription = null, $imageSources = []): self
    {
        $image = new self();

        $image->contentDescription = $contentDescription;
        $image->sources            = $imageSources;

        return $image;
    }
1309237
public function safeRename($source, $destination)
    {
        $isRenamed = @rename($source, $destination);
        if ($isRenamed) {
            return;

        }

        // copy to the target filesystem
        $tempFileOnSameFS = "$destination.tmp";

        $isCopied = copy($source, $tempFileOnSameFS);
        if (! $isCopied) {
            throw new FileException(
                "failed to copy $source to $tempFileOnSameFS."
            );

        }

        $isUnlinked = unlink($source);
        if (! $isUnlinked) {
            trigger_error("Failed to unlink $source.");

        }

        $isRenamed = rename($tempFileOnSameFS, $destination);
        if (! $isRenamed) {
            throw new FileException(
                "failed to rename $tempFileOnSameFS to $destination."
            );

        }
    }
1221356
protected function convertToValidFilenameWithoutExtension(string $filenameWithoutExtension): string
    {
        /** @var string 制御文字、先頭末尾の空白を取り除いた文字列。 */
        $trimed = preg_replace('/^\\p{Z}+|\\p{C}+|\\p{Z}+$/u', '', $filenameWithoutExtension);
        
        return $trimed === ''
            ? (new FilenameValidator())->generateRandomFilename()
            : preg_replace_callback(
                '/^(CON|PRN|AUX|CLOCK\\$|NUL|(COM|LPT)[1-9])$|["*.\\/:<>?\\\\|]+/i',
                function (array $matches): string {
                    $breakIterator = \IntlCodePointBreakIterator::createCodePointInstance();
                    $breakIterator->setText($matches[0]);
                    $fullWidthChars = '';
                    foreach ($breakIterator as $index) {
                        if ($index > 0) {
                            $fullWidthChars .= \IntlChar::chr(
                                $breakIterator->getLastCodePoint() + static::BETWEEN_HALF_AND_FULL
                            );
                        }
                    }
                    return $fullWidthChars;
                },
                $trimed
            );
    }
1066152
protected function getImageSizeByExtension($file, $extension)
	{
		$extension = strtolower($extension);
		$this->loadExtension($extension);
		if (isset($this->classMap[$extension]))
		{
			$this->classMap[$extension]->getSize($file);
		}
	}
30539
public static function saveImage( $fileName, $resource, $type = IMAGETYPE_PNG, $quality = 100 )
	{
		switch( $type )
		{
			case IMAGETYPE_PNG:
				ImagePNG( $resource, $fileName );
				break;
			case IMAGETYPE_JPEG:
				ImageJPEG( $resource, $fileName, $quality );
				break;
			case IMAGETYPE_GIF:
				ImageGIF( $resource, $fileName );
				break;
			default:
				throw new InvalidArgumentException( 'Invalid Image Type' );
		}
	}