Temp img to string in php

2009-01-16

So I was trying to create fresh images and put them directly into a MySQL database. Seemed to me like a trivial task for PHP. But for some reason, it's not. Well, not as trivial as it should have been.

Basically, it comes down to imagepng/imagejpg/imagegif/etc not being able to return a string. They can either output to the buffer or to a file, but not return anything! Highly undesirable when you want to put the image to database.

To fix I found two methods, one seems obviously faster and better than the other... The one, slower, is outputting to file, using file_get_contents, put the string in query and delete the file. The other is fetching the output buffer and using that string.

The code below uses the output buffer.

Code: (PHP)

ob_start();
imagepng($objImg);
$strImg = ob_get_contents();
ob_end_clean(); // dont use this buffer


So what it does is start another layer of output buffering (they stack so it doesn't matter whether it's on or off). The buffer is fetched, cleaned and (this buffer layer) is stopped.

Works fine in at least php 5.0.3 and allows my server to process about 10k small (750b) images within the 30 seconds limit.

Since Google only shows the one email conversation about this, over and over again, I figured someone would like this :)