2009-07-30 145 views
18

我正在使用一個解決方案將圖像文件組裝成zip並將其傳輸到瀏覽器/ Flex應用程序。 (Paul Duncan的ZipStream,http://pablotron.org/software/zipstream-php/)。PHP的GD:如何獲得imagedata作爲二進制字符串?

只需加載圖像文件並壓縮它們就能正常工作。這裏是壓縮文件的核心:

// 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);

任何線索?

回答

39

一種方法是告訴GD輸出圖像,然後使用PHP緩存把它捕捉到一個字符串:

$imagedata = imagecreatefrompng($imagefile); 
ob_start(); 
imagepng($imagedata); 
$stringdata = ob_get_contents(); // read from buffer 
ob_end_clean(); // delete buffer 
$zdata = gzdeflate($stringdata); 
8
// ob_clean(); // optional 
ob_start(); 
imagepng($imagedata); 
$image = ob_get_clean(); 
+0

ob_get_clean()基本上是執行雙方ob_get_contents()和ob_end_clean(),所以這個解決方案稍微比上面所接受的答案更優雅。 – 2016-09-12 23:34:49

相關問題