Output gd image to file

@param resource $image gd image resource
@param string $filename The path to save the file to.
@param string $destformat The Image type to use for $filename
@param string $mime The original image mime type
435762
protected function gdImage($image, $filename, $destformat, $mime ){

		if ($destformat == 'jpg' || ($destformat == null && $mime == 'image/jpeg')) {
			return imagejpeg($image, $filename, 100);
		}

		if ($destformat == 'gif' || ($destformat == null && $mime == 'image/gif')) {
			return imagegif($image, $filename, 7);
		}

		return imagepng($image, $filename, 7);
	}
938021
public function blob($quality = 100, $mime = null)
    {
        $imageBlob = '';

        $filename = pathinfo($this->sourceImageFile->getBasename(), PATHINFO_FILENAME);
        $extension = pathinfo($this->sourceImageFile->getBasename(), PATHINFO_EXTENSION);

        if (empty($mime)) {
            $mime = $this->sourceImageFile->getMime();
            $mime = is_array($mime) ? $mime[ 0 ] : $mime;

            $extension = $this->getMimeExtension($mime);
        }

        header('Content-Disposition: filename=' . $filename . '.' . $extension);

        if ($this->save($tempImageFilePath = rtrim(sys_get_temp_dir(),
                DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $filename . '.' . $extension,
            $quality)
        ) {
            $imageBlob = readfile($tempImageFilePath);
            unlink($tempImageFilePath);
        }

        return $imageBlob;
    }
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' );
		}
	}
735939
public function output(string $mime)
    {
        $output = $this->getOutput($mime);
        if (empty($output))
            $output = "Unknown mime type requested";

        echo $output;
        return $this;
    }
484374
public function writeImage( $image, $file, $type) {
		switch ($type) {
			case 2:	//JPEG
			Imagejpeg( $image, $file);
			break;
			
			case 3:	//PNG
			Imagepng( $image, $file);
			break;
			
			default:
			$this->errorMsg="File format not supported.";
		}
	}
623671
public function save($filename)
    {
        $type = pathinfo($filename, PATHINFO_EXTENSION);
        $type = ($type === 'jpg') ? 'jpeg' : $type;
        $type = (in_array($type, $this->imageTypes)) ? $type : 'png';

        header('Content-type: image/' . $type);

        $imageFunc = 'image' . $type;
        $imageFunc($this->image, $filename);

        $this->destroy($this->image);

        return $this;
    }
27006
public function save($filename, $image_type = null, $quality = null, $permissions = null)
    {
        $image_type = $image_type ?: $this->source_type;
        if ($this->centered) {
            $dest_image = imagecreatetruecolor($this->ask_w, $this->ask_h);
        } else {
            $dest_image = imagecreatetruecolor($this->getDestWidth(), $this->getDestHeight());
        }
        imageinterlace($dest_image, $this->interlace);
        switch ($image_type) {
            case IMAGETYPE_GIF:
                $background = imagecolorallocatealpha($dest_image, 255, 255, 255, 1);
                imagecolortransparent($dest_image, $background);
                imagefill($dest_image, 0, 0, $background);
                imagesavealpha($dest_image, true);
                break;
            case IMAGETYPE_JPEG:
                $background = imagecolorallocate($dest_image, 255, 255, 255);
                if ($this->centered) {
                    imagefilledrectangle($dest_image, 0, 0, $this->ask_w, $this->ask_h, $background);
                } else {
                    imagefilledrectangle($dest_image, 0, 0, $this->getDestWidth(), $this->getDestHeight(), $background);
                }
                break;
            case IMAGETYPE_PNG:
                imagealphablending($dest_image, false);
                $background = imagecolorallocate($dest_image, 255, 255, 255);
                if ($this->centered) {
                    imagefilledrectangle($dest_image, 0, 0, $this->ask_w, $this->ask_h, $background);
                } else {
                    imagefilledrectangle($dest_image, 0, 0, $this->getDestWidth(), $this->getDestHeight(), $background);
                }
                    imagesavealpha($dest_image, true);
                break;
        }
        imagecopyresampled(
            $dest_image,
            $this->source_image,
            $this->dest_x,
            $this->dest_y,
            $this->source_x,
            $this->source_y,
            $this->getDestWidth(),
            $this->getDestHeight(),
            $this->source_w,
            $this->source_h
        );
        switch ($image_type) {
            case IMAGETYPE_GIF:
                imagegif($dest_image, $filename);
                break;
            case IMAGETYPE_JPEG:
                if ($quality === null) {
                    $quality = $this->quality_jpg;
                }
                imagejpeg($dest_image, $filename, $quality);
                break;
            case IMAGETYPE_PNG:
                if ($quality === null) {
                    $quality = $this->quality_png;
                }
                imagepng($dest_image, $filename, $quality);
                break;
        }
        if ($permissions) {
            chmod($filename, $permissions);
        }
        return $this;
    }
996835
public static function copyRecDir($source, $dest) {
    if (!is_dir($dest)) {
      self::mkdirRec($dest);
    }
    $dir = opendir($source);
    while ($file = readdir($dir)) {
      if ($file == "." || $file == "..") {
        continue;
      }
      self::copyRec("$source/$file", "$dest/$file");
    }
    closedir($dir);
  }
14748
protected function uploadResourceToGoogleDrive($resource, $parentId, $fileName, $srcDriveFile, $mime)
    {
        $chunkSizeBytes = $this->detectChunkSizeBytes();
        $fileSize = $this->getFileSizeBytes($resource);

        if ($fileSize <= $chunkSizeBytes) {
            // If the resource fits in a single chunk, we'll just upload it in a single request
            return $this->uploadStringToGoogleDrive(stream_get_contents($resource), $parentId, $fileName, $srcDriveFile, $mime);
        }

        $client = $this->service->getClient();
        // Call the API with the media upload, defer so it doesn't immediately return.
        $client->setDefer(true);
        $request = $this->ensureDriveFileExists('', $parentId, $fileName, $srcDriveFile, $mime);
        $client->setDefer(false);
        $media = $this->getMediaFileUpload($client, $request, $mime, $chunkSizeBytes);
        $media->setFileSize($fileSize);

        // Upload chunks until we run out of file to upload; $status will be false until the process is complete.
        $status = false;
        while (! $status && ! feof($resource)) {
            $chunk = $this->readFileChunk($resource, $chunkSizeBytes);
            $status = $media->nextChunk($chunk);
        }

        // The final value of $status will be the data from the API for the object that has been uploaded.
        return $status;
    }
900977
public function writeToFile(string $filename, array $options = [])
    {
        Utils::debugLog('writeToFile', [
            'instance' => $this,
            'arguments' => [$filename, $options]
        ]);

        $options = self::unwrap($options);
        $result = vips_image_write_to_file($this->image, $filename, $options);
        if ($result === -1) {
            self::errorVips();
        }
    }
320673
public static function output(&$image, $type = 'png', $filename = null, $quality = 100)
    {
        $type == 'jpg' && $type = 'jpeg';
        $imageFun = "image{$type}";
        if (is_null($filename)) { //输出到浏览器
            header("Content-type: image/{$type}");
            ($type == 'jpeg') ? $imageFun($image, null, $quality) : $imageFun($image);
        } else { //保存到文件
            ($type == 'jpeg') ? $imageFun($image, $filename, $quality) : $imageFun($image, $filename);
        }
        imagedestroy($image);
        exit();
    }
490080
public static function getDataURI($image, $mime = '') {
        return 'data: ' . (function_exists('mime_content_type') ? mime_content_type($image) : $mime) . ';base64,' . base64_encode(file_get_contents($image));
    }
308027
protected function makeGD($image)
  {
    if (is_resource($image)) {
      return $image;
    }

    if (!is_file($image)) {
      Ex::ThrowError(Ex::FILE_NOT_EXIST, $image);
    }

    $this->type = $this->getTypeByFile($image);

    switch ($this->type) {
      case IMG_JPEG:
        return imagecreatefromjpeg($image);
        break;
      case IMG_GIF:
        return imagecreatefromgif($image);
        break;
      case IMG_PNG:
        return imagecreatefrompng($image);
        break;
      default:
        $file = file_get_contents($image);

        return imagecreatefromstring($file);
    }
  }
193093
public static function isGifFile($filename)
    {
        try {
            $image = new ImageFile($filename);
            if (strtolower($image->getMime()) !== @image_type_to_mime_type(IMAGETYPE_GIF)) {
                return false;
            }

            return true;
        } catch (\RuntimeException $ex) {
            return false;
        }
    }
265497
private static function _mime_magic(
		string $fname, string $path_to_file=null
	) {
		# with builtin
		if (
			function_exists('mime_content_type') &&
			($mime = @mime_content_type($fname)) &&
			$mime != 'application/octet-stream'
		)
			return $mime;

		# with `file`, skip coverage because `file` is usually
		# not available on CI
		// @codeCoverageIgnoreStart
		if ($path_to_file && is_executable($path_to_file)) {
			$bin = $path_to_file;
		} elseif (!($bin = self::exec("bash -c 'type -p file'")[0])) {
			return 'application/octet-stream';
		}

		if (
			($mimes = self::exec('%s -bip %s', [$bin, $fname])) &&
			preg_match('!^[a-z0-9\-]+/!i', $mimes[0])
		)
			return $mimes[0];

		# giving up
		return 'application/octet-stream';
		// @codeCoverageIgnoreEnd
	}
1277665
public static void writeOutContent(final byte[] data, final String filename, final String mime) {
        writeOutContent(data, filename, mime, true);
    }
399419
public static function serialize($filename, $instance, $force = false)
    {
        if ($filename == '') {
            throw new \danog\MadelineProto\Exception('Empty filename');
        }
        if ($instance->API->asyncInitPromise) {
            return $instance->call(static function () use ($filename, $instance, $force) {
                yield $instance->API->asyncInitPromise;
                $instance->API->asyncInitPromise = null;
                return self::serialize($filename, $instance, $force);
            });
        }
        if (isset($instance->API->setdem) && $instance->API->setdem) {
            $instance->API->setdem = false;
            $instance->API->__construct($instance->API->settings);
        }
        if ($instance->API === null && !$instance->getting_api_id) {
            return false;
        }
        $instance->serialized = time();
        $realpaths = self::realpaths($filename);
        if (!file_exists($realpaths['lockfile'])) {
            touch($realpaths['lockfile']);
            clearstatcache();
        }
        $realpaths['lockfile'] = fopen($realpaths['lockfile'], 'w');
        \danog\MadelineProto\Logger::log('Waiting for exclusive lock of serialization lockfile...');
        flock($realpaths['lockfile'], LOCK_EX);
        \danog\MadelineProto\Logger::log('Lock acquired, serializing');

        try {
            if (!$instance->getting_api_id) {
                $update_closure = $instance->API->settings['updates']['callback'];
                if ($instance->API->settings['updates']['callback'] instanceof \Closure) {
                    $instance->API->settings['updates']['callback'] = [$instance->API, 'noop'];
                }
                $logger_closure = $instance->API->settings['logger']['logger_param'];
                if ($instance->API->settings['logger']['logger_param'] instanceof \Closure) {
                    $instance->API->settings['logger']['logger_param'] = [$instance->API, 'noop'];
                }
            }
            $wrote = file_put_contents($realpaths['tempfile'], serialize($instance));
            rename($realpaths['tempfile'], $realpaths['file']);
        } finally {
            if (!$instance->getting_api_id) {
                $instance->API->settings['updates']['callback'] = $update_closure;
                $instance->API->settings['logger']['logger_param'] = $logger_closure;
            }
            flock($realpaths['lockfile'], LOCK_UN);
            fclose($realpaths['lockfile']);
        }

        return $wrote;
    }