If you are writing your page with PHP (your file has a .php extension), which you would need to be doing in order to implement @pokra's solution (since it escapes to PHP) then you might also be able to write out the styled dimensions of the container/image as well at the same time. No JavaScript required. This would be the preferred solution. To be honest, I had assumed that this was not the case.
May be a background-image isn't the correct tool here and an absolutely positioned IMG (positioned
behind other content), as in @pokra's solution would be better? This could be altered to simply:
<img src="bgimage.php" alt="" style="position: absolute;">
Which doesn't rely on the actual page being rendered by PHP.
How does bgimage.php work? Does it return a different image on
every request? Or do you have some control over this? If this always returns a different image then even a JavaScript solution is going to be tricky?!
(1) I think, in order to do this with JavaScript you would need to load the
same image in a hidden IMG element. JavaScript can then examine the dimensions of this IMG element once loaded and then set the dimensions of the DIV container that contains the background-image. Would people agree? Or is there a better JavaScript method?
(2) Or, may be... load the image in a hidden IMG element (nothing is currently set as the background-image of the DIV container). Get the dimensions of this image (as above) and then set the dimensions AND background-image of your DIV container to the same as the IMG element. Not that this is possible though?