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

35

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

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

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

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

我的问题是,我想在压缩图片之前使用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 );

有什么线索吗?

3个回答

51

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

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

我尝试过这个,但由于嵌套的 ob_start,它失败了。我发现下面 M.i.X 的答案是更好的解决方案。 - supersan

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

1
ob_get_clean() 本质上执行了 ob_get_contents() 和 ob_end_clean(),因此这个解决方案比上面被接受的答案更加优雅。 - Kenneth Vogt

20

当不想进行输出缓冲区操作时,可以使用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 );

1
这个答案比ob_start()的hackery好多了。谢谢! - supersan
不确定为什么,在 PHP 5.6.18 下在 Windows 上无法正常工作。"10 不是有效的流资源"。 - Tom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接