简体   繁体   English

如何将图像传递给 Django 中的模板?

[英]How can I pass an image to a template in Django?

Suppose that the corresponding function in views.py looks like假设views.py中对应的function长这样

from PIL import Image
def get_img(request, img_source)
    base_image = Image.open(os.getcwd() + '/deskprod/media/img/'+ img_source + ".png")
    #Some editing of base_image done with PIL that prevents image from being directly loaded in html
    return render_to_response('get_img.html', {
        'base_image': base_image},
        context_instance=RequestContext(request))

How can I then display base_image in the get_img.html template?然后如何在get_img.html模板中显示base_image

You should process the image, save it on local disk and then send a path to it or more like the media url which will correspond to that image as context to html template.您应该处理图像,将其保存在本地磁盘上,然后将路径发送到它或更像媒体 url,它将与该图像作为 html 模板的上下文相对应。 You need to configure your django server to serve static and media files to do that and configure serving those files in production environment as well.您需要配置 django 服务器来提供静态和媒体文件,并在生产环境中配置为这些文件提供服务。 Read more here https://docs.djangoproject.com/en/1.9/howto/static-files/在这里阅读更多https://docs.djangoproject.com/en/1.9/howto/static-files/

However it should be possible to create dynamic image and serve with django in the fly with PIL if you can't or really do not want to save it locally.但是,如果您不能或真的不想将其保存在本地,则应该可以使用 PIL 创建动态图像并在运行中与 django 一起使用。 It will be sth like at the and of you code you should add.它会像你应该添加的代码一样。

response = HttpResponse(mimetype="image/png")
base_image.save(response, "PNG")
return response

Check also more info http://effbot.org/zone/django-pil.htm , it may work, although I didn't test it.检查更多信息http://effbot.org/zone/django-pil.htm ,它可能工作,虽然我没有测试它。

settings.py设置.py

   'DIRS': [os.path.join(BASE_DIR, 'templates')], # add this line in TEMPLATES
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media/images')
    MEDIA_URL = '/media/images/'

add templates and media/images directory where manage.py is stored.添加存储 manage.py 的模板和媒体/图像目录。

urls.py网址.py

urlpatterns = [

                  url('polls/', views.get_img, name="polls"),


              ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

views.py视图.py

from django.conf import settings

def get_img(request):
    path = settings.MEDIA_ROOT
    img_list = os.listdir(path + "/")
    print(img_list[0])
    base_image = "http://127.0.0.1:8000/media/images/" + img_list[0]
    content = {"base_image": base_image}
    return render(request, 'get_img.html', content)

get_img.html get_img.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>drop_down</title>
</head>
<body>

  {{base_image}}
  <img src="{{base_image}}" style="width: 20%; height: 20%;" alt="{{base_image}}">

</body>
</html>

我认为您必须在项目的静态目录中保存图像(将其写入临时文件),并在模板中使用静态命令和图像文件名来显示它。

You can pass image as base64 bytes to Django template, and then use it in html:您可以将图像作为 base64 字节传递给 Django 模板,然后在 html 中使用它:

view.py查看.py

from PIL import Image
from io import BytesIO
import base64
    
    
# Convert Image to Base64
def image_to_base64(image):
    buff = BytesIO()
    image.save(buff, format="PNG")
    img_str = base64.b64encode(buff.getvalue())
    img_str = img_str.decode("utf-8")  # convert to str and cut b'' chars
    return img_str

def home(request):
    image = Image.open('some_image.png')
    image64 = image_to_base64(image)
    return render(request, 'index.html', {'image64': image64})

index.html index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <img src="data:image/png;base64,{{image64}}">
</body>
</html>

It will works for JPG too - need to change all PNG mentions to JPG in.py/.html它也适用于 JPG - 需要将所有提及的 PNG 更改为 JPG in.py/.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM