How to change the background image using img file

2019-09-18 16:44发布

What I am trying to do is to keep changing the background image using image files that are uploaded in the database instead in the 'static', 'images' folder.

I obviously can't do this in the css, actually, I am not sure if this is even possible. Can I make this work in the layout.html or in the View somehow?

This is how I would display an image in the View if it wasn't intended to be a background-image:

<img src="{{=URL('download', args=pic_row.pics)}}"/>

Of course, this approach to display a background-mage won't work:

<section id="main" class="main row" style="background-image:{{=URL('download', args=pic_row.pics)}}">

..but is there a way I can actually achieve this?

标签: web2py
3条回答
何必那么认真
2楼-- · 2019-09-18 17:07
<section id="main" class="main row" style="background-image:{{=URL('download', args=pic_row.pics)}}">

The above method proposed in the question is close, but the CSS syntax is incorrect. The style attribute should be:

"background-image: url('{{=URL('download', args=pic_row.pics)}}')"
查看更多
一夜七次
3楼-- · 2019-09-18 17:11

Please read Anthony´s answer.

With this it should be possible if you include

<style>
    body {
        background: url('{{=URL('download',args=picture_name)}}')
    }
</style>

into your view.

查看更多
姐就是有狂的资本
4楼-- · 2019-09-18 17:14

Why wouldn't it work in CSS?

I'm not sure this is the best way, but surely you can construct a controller that returns an image from the database?

controllers/random.py:

def image():
    image = db(db.images ...).select().first() # get the image from db
    from io import StringIO
    stream = StringIO(image.bytes)
    response.headers['Content-Type'] = 'image/png'
    return response.stream(stream, 1024**2)

And then just point your stylesheet to it.

some_view.html:

...
<style>
body { background: url("/random/image"); }
</style>
...
查看更多
登录 后发表回答