Return image as PNG string

@param int $compression

@return string
184499
public function asPng($compression = 9)
    {
        ob_start();

        $im = $this->output();
        imagepng($im, null, $compression);

        return ob_get_clean();
    }
656435
public function setPngCompression($compression)
  {
    if (!is_numeric($compression) ||
      $compression < 0 ||
      $compression > 9) {
      throw new \Exception('Compression PNG : valeur numérique attendue de 0 à 9');
    }
    $this->jpgQuality = $quality;
  }
673306
public function getPngType($filename = null)
    {
        $filename = $filename ? $filename : $this->pathToImage;

        $pngType = ord(file_get_contents($filename, false, null, 25, 1));

        if ($this->verbose) {
            $this->log("Checking png type of: " . $filename);
            $this->log($this->getPngTypeAsString($pngType));
        }

        return $pngType;
    }
817179
protected function generateImage(string $format): string
    {
        $url = $this->generateUrl($format);

        $content = file_get_contents($url);

        if ($content === false) {
            $content = '';
        }

        return $content;
    }
1337025
def png(self):
        """"""
        use_plugin('freeimage')
        with TemporaryFilePath(suffix='.png') as tmp:
            safe_range_im = 255 * normalise(self)
            imsave(tmp.fpath, safe_range_im.astype(np.uint8))
            with open(tmp.fpath, 'rb') as fh:
                return fh.read()
796754
public function generateContentType($extension)
    {
        if (!in_array($extension, InvalidExtensionException::getValidExtensions())) {
            throw InvalidExtensionException::fromExtension($extension);
        }

        return sprintf('image/%s', $extension == self::DEFAULT_EXTENSION ? 'jpeg' : $extension);
    }
1224323
public function cacheToJPEGFilename($quality, $backgroundColor, $pathinfo) {
		$folder = $this->owner->ParentID ? $this->owner->Parent()->Filename : ASSETS_DIR . "/";

		$format = $pathinfo['extension'].'tojpeg-'.$quality.'-'.$backgroundColor;

		if($this->owner instanceof SecureImage){
			return $folder . "_resampled/".md5($format."-".$pathinfo['filename']).".jpg";
		}else{
			return $folder . "_resampled/".$format."-".$pathinfo['filename'].".jpg";
		}
	}
497015
public static function png($text, $outfile = false, $level = Constants::QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint=false)
    {
        $enc = QRencode::factory($level, $size, $margin);
        return $enc->encodePNG($text, $outfile, $saveandprint);
    }
14218
private function getQualityFromExtension($ext, $transform = null): string
    {
        /** @var ConfigModel $settings */
        $config = ImagerService::getConfig();

        switch ($ext) {
            case 'png':
                $pngCompression = $config->getSetting('pngCompressionLevel', $transform);

                return max(100 - ($pngCompression * 10), 1);

            case 'webp':
                return $config->getSetting('webpQuality', $transform);
        }

        return $config->getSetting('jpegQuality', $transform);
    }
546992
public static function image2Jpeg($file, $quality = 80)
    {
        try {
            if (is_file($file)) {
                return Image::open($file)->setCacheDir(dirname($file))->jpeg($quality);
            }
        } catch (Exception $e) {
        }
        return false;
    }
1303517
public function colAtoString($c)
	{
		if ($c{0} == static::MODE_GRAYSCALE) {
			return 'rgb(' . ord($c{1}) . ', ' . ord($c{1}) . ', ' . ord($c{1}) . ')';
		}

		if ($c{0} == static::MODE_SPOT) {
			return 'spot(' . ord($c{1}) . ', ' . ord($c{2}) . ')';
		}

		if ($c{0} == static::MODE_RGB) {
			return 'rgb(' . ord($c{1}) . ', ' . ord($c{2}) . ', ' . ord($c{3}) . ')';
		}

		if ($c{0} == static::MODE_CMYK) {
			return 'cmyk(' . ord($c{1}) . ', ' . ord($c{2}) . ', ' . ord($c{3}) . ', ' . ord($c{4}) . ')';
		}

		if ($c{0} == static::MODE_RGBA) {
			return 'rgba(' . ord($c{1}) . ', ' . ord($c{2}) . ', ' . ord($c{3}) . ', ' . sprintf('%0.2F', ord($c{4}) / 100) . ')';
		}

		if ($c{0} == static::MODE_CMYKA) {
			return 'cmyka(' . ord($c{1}) . ', ' . ord($c{2}) . ', ' . ord($c{3}) . ', ' . ord($c{4}) . ', ' . sprintf('%0.2F', ord($c{5}) / 100) . ')';
		}

		return '';
	}
12368
public function getHex($prefix = '')
    {
        return sprintf('%s%02x%02x%02x', $prefix, $this->r, $this->g, $this->b);
    }
51308
public function serialize($maxlength=null, $compress=false) {
        if ( ! $maxlength ) $maxlength = $this->maxlen;
        $retval = $this->scale . ':' .$this->timestart . ':' . U::array_Integer_Serialize($this->buckets);
        if ( strlen($retval) <= $maxlength ) return $retval;

        $allowCompress = $compress && function_exists('gzcompress') && function_exists('gzuncompress');

        // Stratey 1 - Compress if we are allowed - since it is lossless
        if ( $allowCompress ) {
            $compressed = gzcompress($retval);
            if ( strlen($retval) <= $maxlength ) return $retval;
        }
        
        // Strategy 2 - Double or Quadruple Scale as long as buckets < 24 hours
        if ( $this->scale < 24*60*60 ) { 
            foreach(array(2,4) as $factor ) {
                $newbuckets = $this->reScale($factor);
                $newscale = $this->scale * $factor;
                $newstart = (int) ($this->timestart / $factor);
                $retval = $newscale . ':' .$newstart . ':' . U::array_Integer_Serialize($newbuckets);

                if ( strlen($retval) <= $maxlength ) return $retval;

                if ( $allowCompress ) {
                    $compressed = gzcompress($retval);
                    if ( strlen($retval) <= $maxlength ) return $retval;
                }
            }
        }

        // Strategy 3, pitch data
        $oldbuckets = $this->buckets;
        $newstart = $this->timestart;
        $firstoffset = null;
        while( count($oldbuckets) > 4 ) {
            $fewerbuckets = array();
            $pos = 0;
            $fistoffset = null;
            foreach($oldbuckets as $oldoffset => $v ) {
                $pos++;
                if ( $pos == 1 ) continue; // first entry
                if ( $pos == 2 ) $firstoffset = $oldoffset;
                $newoffset = $oldoffset - $firstoffset;
                $fewerbuckets[$newoffset] = $oldbuckets[$oldoffset];
            }
            if ( count($oldbuckets)-1 != count($fewerbuckets) ) {
                throw new Exception('Internal failure during serialization');
            }
            $newstart = $newstart + $firstoffset;

            $retval = $this->scale . ':' .$newstart . ':' . U::array_Integer_Serialize($fewerbuckets);
            if ( strlen($retval) <= $maxlength ) return $retval;

            if ( $allowCompress ) {
                 $compressed = gzcompress($retval);
                 if ( strlen($retval) <= $maxlength ) return $retval;
            }
            $oldbuckets = $fewerbuckets;
        }

        // Strategy 4: Violate the max request :)
        return $retval;
    }
553497
private function createTargetFilename($source, $transform): string
    {
        /** @var ConfigModel $settings */
        $config = ImagerService::getConfig();

        $useFilenamePattern = $config->getSetting('useFilenamePattern', $transform);
        $hashFilename = $config->getSetting('hashFilename', $transform);
        $shortHashLength = $config->getSetting('shortHashLength', $transform);

        $basename = $source->basename;
        $extension = $source->extension;

        if (isset($transform['format'])) {
            $extension = $transform['format'];
            unset($transform['format']);
        }

        if ($extension === '') {
            // todo : detect from mime type?
        }

        $this->extension = $extension;

        $transformFileString = ImagerHelpers::createTransformFilestring($transform).$config->getConfigOverrideString();

        // If $useFilenamePattern is false, use old behavior with hashFilename config setting.
        if (!$useFilenamePattern) { 
            if ($hashFilename) {
                if (\is_string($hashFilename) && $hashFilename === 'postfix') {
                    return $basename.'_'.md5($transformFileString).'.'.$extension;
                }

                return md5($basename.$transformFileString).'.'.$extension;
            }

            return $basename.$transformFileString.'.'.$extension;
        }

        // New behavior, uses filenamePattern config setting. Much joy.
        $transformFileString = ltrim($transformFileString, '_');
        $fullname = $basename.'_'.$transformFileString;

        $patternFilename = $config->getSetting('filenamePattern', $transform);
        $patternFilename = mb_ereg_replace('{extension}', $extension, $patternFilename);
        $patternFilename = mb_ereg_replace('{basename}', $basename, $patternFilename);
        $patternFilename = mb_ereg_replace('{fullname}', $fullname, $patternFilename);
        $patternFilename = mb_ereg_replace('{transformString}', $transformFileString, $patternFilename);

        $patternFilename = mb_ereg_replace('{basename\|hash}', md5($basename), $patternFilename);
        $patternFilename = mb_ereg_replace('{fullname\|hash}', md5($fullname), $patternFilename);
        $patternFilename = mb_ereg_replace('{transformString\|hash}', md5($transformFileString), $patternFilename);

        $patternFilename = mb_ereg_replace('{basename\|shorthash}', substr(md5($basename), 0, $shortHashLength), $patternFilename);
        $patternFilename = mb_ereg_replace('{fullname\|shorthash}', substr(md5($fullname), 0, $shortHashLength), $patternFilename);
        $patternFilename = mb_ereg_replace('{transformString\|shorthash}', substr(md5($transformFileString), 0, $shortHashLength), $patternFilename);

        return $patternFilename;
    }
113406
private function createImages($output) {
        $image = array();
        
        foreach ($output as $key => $singleLine) {
            if (preg_match('/\(format/', $singleLine)) {
                $imageInfo  = $singleLine;
                $startPos   = strpos($imageInfo, "(") + 1;
                $endPos     = strpos($imageInfo, ")");
                $dataStr   = substr($imageInfo, $startPos, $endPos - $startPos);

                $dataExplode    = explode(",", $dataStr);
                $contentFormat  = explode(":", $dataExplode[0]);
                $format         = $contentFormat[1];
                $contentFormat  = explode(":", $dataExplode[1]);
                $type         = $contentFormat[1];

                $imageValue = $output[$key + 2];

                $exploded = explode(" ", $singleLine);
                $imagePath = array_shift($exploded);

                $image[] = new ZxingImage($imagePath, $imageValue, $format, $type);

            } else if(preg_match('/No barcode found/', $singleLine)) {
                
                $exploded = explode(" ", $singleLine);
                $imagePath = array_shift($exploded);
                $image[] = new ZxingBarNotFound($imagePath, 101, "No barcode found");
            }
        }

        return $image;
    }
235182
public function logo($filename = 'logo.png', $linked = true)
    {
        $framework = Framework::instance();
        $output = [];

        if (file_exists(sprintf('%s/img/%s', $framework->getThemeAssetsDir(), $filename))) {
            if ($linked) {
                $output[] = sprintf(
                    '<a href="%s" alt="%s logo">',
                    esc_url(home_url('/')),
                    esc_attr(get_bloginfo('name'))
                );
            }

            $output[] = sprintf('<img src="%s/img/%s">', esc_attr($framework->getThemeAssetsUri()), $filename);

            if ($linked) {
                $output[] = '</a>';
            }
        }

        return apply_filters('novusopress_view_logo_output', implode('', $output));
    }
368514
protected function getUncompressed($compressed)
    {
        $decompressed = $this->_gzdecode($compressed);

        if ($decompressed === false) {

            throw new ehough_shortstop_api_exception_RuntimeException('Could not decompress data with simulated gzdecode()');
        }

        return $decompressed;
    }