如何将div的背景图像属性设置为动态生成的图像

问题描述:

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?

我有一些div,每个都有自己的背景图像。 存储的基本图像只是黑色轮廓。 p>

我想要做的是使用PHP GD包稍微随机修改这些图像的颜色,并将修改后的随机彩色图像作为div的背景图像。 p>

一种方法是从原始文件创建GD图像​​结构,修改它们,将结果保存为临时文件,将此文件名传递到客户端,然后使用jquery 将div的css背景图像属性修改为新文件。 但这将留下大量垃圾收集文件。 p>

有没有办法在不创建一堆文件的情况下做到这一点? p> div>

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.