Generate image from a source and save to specified file
@param $file
344606
protected function savePicture($file)
    {
        $this->loadImageResource();

        // SUPPORT FOR CMYK IMAGES
        $colorSpace = new Colorspace();
        $colorSpace->apply($this);

        // APPLY EFFECT ON IMAGE
        foreach($this->effect as $effect)
        {
            if($effect instanceof PictureEffect)
            {
                $effect->apply($this);
            }
        }

        // CREATE DIRECTORY BY FILE PATH
        if(!file_exists($directory = dirname($file)))
        {
            mkdir($directory, 0777, TRUE);
        }

        $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));

        if($this->isGd())
        {
            if($extension === 'png')
            {
                if($this->progressive)
                {
                    imageinterlace($this->resource, TRUE);
                }

                imagepng($this->resource, $file, 9);
            }
            elseif($extension === 'gif')
            {
                $gifResource = $this->resource;

                if($this->isGdImageTransparent($gifResource))
                {
                    $validAlpha = ceil(0.333 * 127);
                    $visiblePixels = 0;

                    $height = imagesy($gifResource);
                    $width  = imagesx($gifResource);

                    $transparentColor = imagecolorallocate($gifResource, 0xfe, 0x3, 0xf4);

                    // FIX GIF IMAGE OPACITY
                    for($x = 0; $x < $width; $x++)
                    {
                        for($y = 0; $y < $height; $y++)
                        {
                            $pixelIndex = imagecolorat($gifResource, $x, $y);
                            $pixelColor = imagecolorsforindex($gifResource, $pixelIndex);

                            if($pixelColor['alpha'] <= $validAlpha)
                            {
                                $visiblePixels++;
                            }
                        }
                    }

                    if(!$visiblePixels)
                    {
                        $validAlpha = 127;
                    }

                    for($x = 0; $x < $width; $x++)
                    {
                        for($y = 0; $y < $height; $y++)
                        {
                            $pixelIndex = imagecolorat($gifResource, $x, $y);
                            $pixelColor = imagecolorsforindex($gifResource, $pixelIndex);

                            if($pixelColor['alpha'] >= $validAlpha)
                            {
                                imagesetpixel($gifResource, $x, $y, $transparentColor);
                            }
                            else
                            {
                                $visiblePixel = imagecolorallocatealpha(

                                    $gifResource,
                                    $pixelColor['red'],
                                    $pixelColor['green'],
                                    $pixelColor['blue'],
                                    0
                                );

                                imagesetpixel($gifResource, $x, $y, $visiblePixel);
                            }
                        }
                    }

                    imagecolortransparent($gifResource, $transparentColor);
                }

                if($this->progressive)
                {
                    imageinterlace($gifResource, TRUE);
                }

                imagegif($gifResource, $file);
            }
            else
            {
                $image = $this->resource;

                $width  = imagesx($image);
                $height = imagesy($image);

                $background = imagecreatetruecolor($width, $height);
                $whiteColor = imagecolorallocate($background,  255, 255, 255);

                imagefilledrectangle($background, 0, 0, $width, $height, $whiteColor);
                imagecopy($background, $image, 0, 0, 0, 0, $width, $height);

                if($this->progressive)
                {
                    imageinterlace($background, TRUE);
                }

                imagejpeg($background, $file, $this->quality);
            }
        }
        else
        {
            if($extension === 'jpg')
            {
                $background = $this->createImagick();
                $background->newImage(

                    $this->resource->getImageWidth(),
                    $this->resource->getImageHeight(),
                    '#FFFFFF'
                );

                $background->compositeImage($this->resource, Imagick::COMPOSITE_OVER, 0, 0);
                $background->setImageFormat('jpg');
                $background->setImageCompression(Imagick::COMPRESSION_JPEG);
                $background->setImageCompressionQuality($this->quality);

                if($this->progressive)
                {
                    $background->setInterlaceScheme(Imagick::INTERLACE_PLANE);
                }

                $background->writeImage($file);
            }
            elseif($extension === 'gif')
            {
                $validAlpha = 0.333;
                $visiblePixels = 0;
                $iterator = $this->resource->getPixelIterator();

                /** @var $pixel \ImagickPixel */
                foreach($iterator as $row => $pixels)
                {
                    foreach ($pixels as $col => $pixel)
                    {
                        $color = $pixel->getColor(TRUE);

                        if($color['a'] >= $validAlpha)
                        {
                            $visiblePixels++;
                        }
                    }

                    $iterator->syncIterator();
                }

                if(!$visiblePixels)
                {
                    $validAlpha = 0;
                }

                // SAVE NEW ALPHA COLOR VALUE
                foreach($iterator as $row => $pixels)
                {
                    foreach ($pixels as $col => $pixel)
                    {
                        $color = $pixel->getColor(TRUE);
                        $pixel->setColorValue(Imagick::COLOR_ALPHA, $color['a'] >= $validAlpha ? 1 : 0);
                    }

                    $iterator->syncIterator();
                }

                if($this->progressive)
                {
                    $this->resource->setInterlaceScheme(Imagick::INTERLACE_PLANE);
                }

                $this->resource->writeImage($file);
            }
            else
            {
                if($this->progressive)
                {
                    $this->resource->setInterlaceScheme(Imagick::INTERLACE_PLANE);
                }

                $this->resource->writeImage($file);
            }
        }

        chmod($file, 0777);
        touch($file, filemtime($this->getImage()));

        // DELETE TEMP FILES
        foreach($this->tmpImage as $tmpImage)
        {
            unlink($tmpImage);
        }
    }
966968
protected function openGif($file)
    {
        if (file_exists($file) && filesize($file)) {
            $this->resource = @imagecreatefromgif($file);
        } else {
            $this->resource = false;
        }
    }
1264031
public function display_uploaded_file($file)
    {
        if (empty($file)) {
            return;
        }

        $file = $this->plugins->exec_hook('attachment_display', $file);

        if ($file['status']) {
            if (empty($file['size'])) {
                $file['size'] = $file['data'] ? strlen($file['data']) : @filesize($file['path']);
            }

            // generate image thumbnail for file browser in HTML editor
            if (!empty($_GET['_thumbnail'])) {
                $temp_dir       = $this->config->get('temp_dir');
                $thumbnail_size = 80;
                $mimetype       = $file['mimetype'];
                $file_ident     = $file['id'] . ':' . $file['mimetype'] . ':' . $file['size'];
                $cache_basename = $temp_dir . '/' . md5($file_ident . ':' . $this->user->ID . ':' . $thumbnail_size);
                $cache_file     = $cache_basename . '.thumb';

                // render thumbnail image if not done yet
                if (!is_file($cache_file)) {
                    if (!$file['path']) {
                        $orig_name = $filename = $cache_basename . '.tmp';
                        file_put_contents($orig_name, $file['data']);
                    }
                    else {
                        $filename = $file['path'];
                    }

                    $image = new rcube_image($filename);
                    if ($imgtype = $image->resize($thumbnail_size, $cache_file, true)) {
                        $mimetype = 'image/' . $imgtype;

                        if ($orig_name) {
                            unlink($orig_name);
                        }
                    }
                }

                if (is_file($cache_file)) {
                    // cache for 1h
                    $this->output->future_expire_header(3600);
                    header('Content-Type: ' . $mimetype);
                    header('Content-Length: ' . filesize($cache_file));

                    readfile($cache_file);
                    exit;
                }
            }

            header('Content-Type: ' . $file['mimetype']);
            header('Content-Length: ' . $file['size']);

            if ($file['data']) {
                echo $file['data'];
            }
            else if ($file['path']) {
                readfile($file['path']);
            }
        }
    }
566751
public function loadImage(string $file, string $path = '') : AbstractResize
    {
        if (file_exists($path . $file) === true) {
            $this->source['path'] = $path;
            $this->source['file'] = $file;
            $this->sourceProperties();
        } else {
            throw new \Exception("File couldn't be found in supplied destination: '" . $path . $file . "'");
        }

        // Reset the processed status when a new image is loaded
        $this->processed = false;
        $this->file = null;
        $this->path = null;

        return $this;
    }
757240
public function save($file = null)
    {
        //argument 1 must be a file or null
        Argument::i()->test(1, 'string', 'null');
        
        if (is_null($file)) {
            $file = $this->file;
        }
        
        if (is_null($file)) {
            Exception::i()
                ->setMessage(Argument::INVALID_ARGUMENT)
                ->addVariable(1)
                ->addVariable(__CLASS__.'->'.__FUNCTION__)
                ->addVariable('file or null')
                ->addVariable($file)
                ->setTypeLogic()
                ->trigger();
        }
        
        File::i($file)->setData($this->language);
        
        return $this;
    }
351848
public static function create( $file, $type = null ) 
	{
		// when no type is given use the file extension
		if ( is_null( $type ) ) 
		{
			$type = CCStr::extension( $file );

			// validate type
			if ( !in_array( $type, static::$available_image_types ) )
			{
				$type = null;
			}
		}

		$image_data = getimagesize( $file );

		if ( $image_data === false ) 
		{
			return false;
		}

		$image = null;

		switch( $image_data['mime'] ) 
		{
			case 'image/gif':
				$image = imagecreatefromgif( $file );
			break;

			case 'image/jpeg';
				$image = imagecreatefromjpeg( $file );
			break;

			case 'image/png':
				$image = imagecreatefrompng( $file );
			break;

			default:
				// we dont support other image types
				return false;
			break;
		}

		// when the image type is still null we are going to use 
		// the mime type of the image 
		if ( is_null( $type ) )
		{
			$type = CCStr::suffix( $image_data['mime'], '/' );
		}

		return new static( $image, $type );
	}
1000445
public function writePoFile(string $file): void
    {
        $source = $this->dumpString();
        $testName = file_exists($file) ? $file : dirname($file);
        $status = is_writable($testName);
        if ($status === true) {
            $status = file_put_contents($file, $source);
        }
        if (false === $status) {
            throw new FileNotWritableException($file);
        }
    }
721201
protected function makeImage($file = null, $quality = null)
  {
    $dir = dirname($file);
    if (!is_dir($dir)) {
      mkdir($dir, 0777, true);
    }

    switch ($this->getTypeByFile($file)) {
      case IMG_JPG:
        return imagejpeg($this->image, $file, $quality ? : static::QUALITY_JPG);
        break;
      case IMG_PNG:
        return imagepng($this->image, $file, $quality ? : static::QUALITY_PNG);
        break;
      case IMG_GIF:
        return imagegif($this->image, $file);
        break;
      default:
        Ex::ThrowError(Ex::BAD_TYPE);
    }
  }
1222011
public function upload($file)
    {
        $this->filename = $this->getRandomFilename();
        $this->image = Image::make(Input::file($file)->getRealPath());

        return $this;
    }
340019
protected function saveFile($file, array $data)
    {
        $path = $this->getVendorDir() . '/' . $file;
        if (!file_exists(dirname($path))) {
            mkdir(dirname($path), 0777, true);
        }
        $array = str_replace("'" . self::BASE_DIR_SAMPLE, '$baseDir . \'', Helper::exportVar($data));
        file_put_contents($path, "<?php\n\n\$baseDir = dirname(dirname(__DIR__));\n\nreturn $array;\n");
    }
1077082
public static function upload($file)
    {
        $photo = self::create();

        $image_manager = new ImageManager(['driver' => 'imagick']);

        $disk = Storage::disk(config('mustard.storage.disk', 'local'));

        if (!file_exists($file)) {
            RuntimeException("File $file does not exist");
        }

        $dest_dir = config('mustard.storage.photo.dir', 'mustard/photos');
        $quality = config('mustard.storage.photo.quality', 90);

        $disk->makeDirectory($dest_dir);

        $photo_id = $photo->getKey();

        Queue::push(function ($job) use ($file, $quality, $dest_dir, $photo_id) {
            if (!file_exists($file)) {
                RuntimeException("File $file no longer exists");
            }

            $image_manager = new ImageManager(['driver' => 'imagick']);

            $disk = Storage::disk(config('mustard.storage.disk', 'local'));

            if ($file != "$dest_dir/$photo_id.jpg") {
                $image = $image_manager->make($file);

                $disk->put("$dest_dir/$photo_id.jpg", (string) $image->encode('jpg', $quality));

                $image->destroy();
            }

            $image = $image_manager->make($file)->heighten(83);

            $disk->put("$dest_dir/{$photo_id}_s.jpg", (string) $image->encode('jpg', $quality));

            $image->destroy();

            $image = $image_manager->make($file)->widen(500);

            $disk->put("$dest_dir/{$photo_id}_l.jpg", (string) $image->encode('jpg', $quality));

            $image->destroy();

            $photo = Photo::find($photo_id);

            $photo->processed = true;

            $photo->save();

            $job->delete();
        });

        return $photo;
    }
335431
public function dump(string $file = null):string{
		$file    = $file ?? $this->options->cachefile;
		$imagick = new Imagick;

		$imagick->newImage(
			$this->length,
			$this->length,
			new ImagickPixel($this->options->imagickBG ?? 'transparent'),
			$this->options->imagickFormat
		);

		$imageData = $this->drawImage($imagick);

		if($file !== null){
			$this->saveToFile($imageData, $file);
		}

		return $imageData;
	}
1152358
protected function createLogsFile($file)
    {
        $directory = dirname($file);

        // Create directory
        if (!$this->files->isDirectory($directory)) {
            $this->files->createDir($directory);
        }

        // Create file
        if (!$this->files->has($file)) {
            $this->files->put($file, '');
        }
    }
448708
protected function touchFile($file)
    {
        passthru('touch '.$file, $error);
        if ($error !== 0) {
            $this->output->writeln('<error>Error creating file '.$file.'</error>');
        } else {
            $this->output->writeln('<info>File '.$file.' created successfully</info>');
        }
    }
857630
public function generate($file = null) {

		if(null !== $file && false === is_string($file)) {
            return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($file)), E_USER_ERROR);
        }

		if(null === $this -> image) {
			return trigger_error('Can not generate captcha image without valid background image. Set background image with setImage() method', E_USER_ERROR);
		}

		if(null === $this -> font) {
			return trigger_error('Can not generate captcha image without valid font. Set font with setFont() method', E_USER_ERROR);
		}

		//Generate and set text if not already set
		if(null === $this -> getText()) {
			$this -> setText($this -> generateText());
		}

		$text 	= $this -> getText();
		$image 	= $this -> image -> entity();
		$font 	= $this -> font -> entity();

		//Add image header
		if(null === $file) {
			Response :: addHeader('Content-type', $this -> image -> getMime());
		}
		else {
			
			$file = new File($file);

			if(false === in_array($file -> entity() -> getExtension(), ['png', 'jpg', 'jpeg'])) {
				return trigger_error(sprintf('Argument 1 passed to %s() must have the jpg, jpeg or png extension, "%s" given', __METHOD__, $file -> entity() -> getExtension()), E_USER_ERROR);
			}
		}

		//Create image
		switch(strtolower($image -> getExtension())) {
			
			case 'png' 	: $img = imagecreatefrompng($image -> getBasepath()); break;
			default 	: $img = imagecreatefromjpeg($image -> getBasepath());
		}

		//Generate output object
		$output = [];

		for($i = 0; $i < strlen($text); $i++) {

			$fontsize 	= rand($this -> fontsize['min'], $this -> fontsize['max']);
			$angle 		= rand($this -> angle['min'], $this -> angle['max']);
			$tb 		= imagettfbbox($fontsize, $angle, $font -> getBasepath(), $text[$i]);
			$color 		= imagecolorallocate($img, $this -> color['r'], $this -> color['g'], $this -> color['b']);
			$width 		= $image -> getWidth() / strlen($text);
			$width 		= $width < 2 ? 3 : $width;
			$tries 		= 0;

			if($tb[2] >= $width && $tries < 20) {

				$this -> fontsize['min']--;
				$i--;
				$tries++;

				continue;
			}

			$output[] 	= [

				'text' 		=> $text[$i], 
				'width' 	=> $tb[2], 
				'height' 	=> $tb[1],
				'angle'		=> $angle,
				'fontsize' 	=> $fontsize, 
				'color' 	=> $color
			];
		}

		foreach($output as $index => $char) {

			$x = $width * $index + rand(0, $width - $char['width']);
			$y = rand($char['fontsize'], $image -> getHeight() - $char['height']);
			
			imagettftext($img, $char['fontsize'], $char['angle'], $x, $y, $char['color'], $font -> getBasepath(), $char['text']);
		}
		
		$extension 	= $file !== null ? $file -> entity() -> getExtension() : $image -> getExtension();
		$file 		= $file !== null ? $file -> entity() -> getBasepath() : null;

		//Show image
		switch(strtolower($extension)) {
			
			case 'png' 	: imagepng($img, $file); break;
			default 	: imagejpeg($img, $file);
		}
	}
1327591
public function save($file, $free = true)
    {
        $this->createWriter($file);
        $this->render();
        if ($free) {
            $this->free();
        }
    }
424962
public function create($file = '')
    {
        $this->file   = $file;
        $this->memory = '';
        $this->fh     = 0;

        if ($this->file) {
            // determine compression
            if ($this->comptype == Archive::COMPRESS_AUTO) {
                $this->setCompression($this->complevel, $this->filetype($file));
            }

            if ($this->comptype === Archive::COMPRESS_GZIP) {
                $this->fh = @gzopen($this->file, 'wb'.$this->complevel);
            } elseif ($this->comptype === Archive::COMPRESS_BZIP) {
                $this->fh = @bzopen($this->file, 'w');
            } else {
                $this->fh = @fopen($this->file, 'wb');
            }

            if (!$this->fh) {
                throw new ArchiveIOException('Could not open file for writing: '.$this->file);
            }
        }
        $this->writeaccess = true;
        $this->closed      = false;
    }