PHP GD:如何将图像数据作为二进制字符串获取?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1206884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:32:56  来源:igfitidea点击:

PHP GD: How to get imagedata as binary string?

phpzipgd

提问by Cambiata

I'm using a solution for assembling image files to a zip and streaming it to browser/Flex application. (ZipStream by Paul Duncan, http://pablotron.org/software/zipstream-php/).

我正在使用一种解决方案将图像文件组装到 zip 并将其流式传输到浏览器/Flex 应用程序。(Paul Duncan 的 ZipStream,http://pablotron.org/software/zipstream-php/ )。

Just loading the image files and compressing them works fine. Here's the core for compressing a file:

只需加载图像文件并压缩它们就可以正常工作。这是压缩文件的核心:

// Reading the file and converting to string data
$stringdata = file_get_contents($imagefile);

// Compressing the string data
$zdata = gzdeflate($stringdata );

My problem is that I want to process the image using GD before compressing it. Therefore I need a solution for converting the image data (imagecreatefrompng) to string data format:

我的问题是我想在压缩之前使用 GD 处理图像。因此,我需要一个将图像数据 (imagecreatefrompng) 转换为字符串数据格式的解决方案:

// Reading the file as GD image data
$imagedata = imagecreatefrompng($imagefile);
// Do some GD processing: Adding watermarks etc. No problem here...

// HOW TO DO THIS??? 
// convert the $imagedata to $stringdata - PROBLEM!

// Compressing the string data
$zdata = gzdeflate($stringdata );

Any clues?

有什么线索吗?

回答by spoulson

One way is to tell GD to output the image, then use PHP buffering to capture it to a string:

一种方法是告诉GD输出图像,然后使用PHP缓冲将其捕获为字符串:

$imagedata = imagecreatefrompng($imagefile);
ob_start();
imagepng($imagedata);
$stringdata = ob_get_contents(); // read from buffer
ob_end_clean(); // delete buffer
$zdata = gzdeflate($stringdata);

回答by Stefan Brinkmann

// ob_clean(); // optional
ob_start();
imagepng($imagedata);
$image = ob_get_clean();

回答by M.i.X

The php://memory stream can be used when output-buffer juggling is unwanted. https://www.php.net/manual/en/wrappers.php.php

当不需要输出缓冲区杂耍时,可以使用 php://memory 流。 https://www.php.net/manual/en/wrappers.php.php

$imagedata = imagecreatefrompng($imagefile);

// processing

$stream = fopen('php://memory','r+');
imagepng($imagedata,$stream);
rewind($stream);
$stringdata = stream_get_contents($stream);

// Compressing the string data
$zdata = gzdeflate($stringdata );