views:

71

answers:

1

I have some divs and each one has its own background image. The base images as stored is just a black silhouette.

What I would like to do is use the PHP GD package to modify the color of those images somewhat randomly and have the modified randomly coloured images be the background images of the divs.

One way to do it is just create GD images structures from the original files, modify them, save the results as a temp file, pass this filename into the client, and then use jquery to modify the css background image properties of the divs to be the new file. But this is going to leave a lot of files laying around to garbage collect.

Is there some way to do it without creating a bunch of files?

A: 

If it's just "somewhat random", then you might as well just pre-generate all the variations you want to use. The CPU/memory overhead of having to build the images on-the-fly will quickly exceed the time it took to pre-build.

If you REALLY don't want to have static versions sitting around, just use the image???() calls and don't specify a filename for output. This will send the completed image directly to the client, so you could just specify a css rule of:

div.randombg {
    background-image: url(/randomimage.php);
}

And the script would boil down to:

<?php

...  GD stuff to build image here ...
header("Content-type: image/jpeg");
imagejpg($gdhandle);
exit();

If you want the background to stay relatively constant per-user, you could set a flag in a cookie/session to tell the image generating script to send out "not-modified" headers so the client can re-use the previously built image and not force it to change for every hit.

Marc B
this is a good answer and it also addresses the issue of keeping the colors constant during a session. However some testing is that truly random colors are mostly ugly so I think I will follow the first advice and just pregenerate eight or nine different permament nice colors for each silhouette and randomly replace the black ones with jquery.
I could even generate inline styles using php in the first place then I wouldn't have to replace anything. The black one that's in the stylesheet would just be superseeded.