Colleen  Kitchen
Colleen Kitchen

Reputation: 1069

how to set the background image property of a div to a dynamically generated image

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?

Upvotes: 1

Views: 1715

Answers (1)

Marc B
Marc B

Reputation: 360702

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.

Upvotes: 1

Related Questions