PHP GD:如何将imagedata作为二进制字符串?

Cam*_*ata 20 php zip gd

我正在使用一种解决方案将图像文件组合到一个zip并将其流式传输到浏览器/ Flex应用程序.(Paul Duncan的ZipStream,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 );
Run Code Online (Sandbox Code Playgroud)

我的问题是我想在压缩之前使用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 );
Run Code Online (Sandbox Code Playgroud)

有线索吗?

spo*_*son 40

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

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


小智 13

// ob_clean(); // optional
ob_start();
imagepng($imagedata);
$image = ob_get_clean();
Run Code Online (Sandbox Code Playgroud)


M.i*_*i.X 13

当不需要输出缓冲区杂耍时,可以使用 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 );
Run Code Online (Sandbox Code Playgroud)

  • 这是比“ob_start()”黑客更好的答案。谢谢! (2认同)