简体   繁体   English

如何使用jquery在Django中提供图像

[英]How to serve an image in Django using jquery

I am trying to update a div element in my html page with a png image which gets returned from the Django server. 我正在尝试使用从Django服务器返回的png图像更新我的html页面中的div元素。

In my client-side script where I send an ajax POST request on a button click, I have - 在我的客户端脚本中,我点击按钮发送ajax POST请求,我有 -

    $('#mybtn').click(function (event) {
        event.preventDefault();
        $.ajax({
            url: "/analysis",
            type: "POST",
            data: { 'data': $("#analysis_list").val(), csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value },
            success: function (response) {
                $('#imagediv').html('<img src=' + response + ' />');
            },
        });
    });

In my views.py, I have - 在我的views.py中,我有 -

def analysis(request):
    dataFromClient = dict(request.POST)['data'][0]
    pathToImg = testAnalytics(dataFromClient)
    img = Image.open(pathToImg)
    response = HttpResponse(content_type="image/png")
    img.save(response, "PNG")
    return response

Where testAnalytics method generates the image to be displayed according to the data sent by client and returns the path to it. testAnalytics方法根据客户端发送的数据生成要显示的图像,并返回路径。 Image is imported from PIL . ImagePIL导入。

I am facing problem with rendering the image at client-side javascript. 我在客户端javascript渲染图像时遇到问题。 When I assign response to src attribute of the <img> tag, I see raw image data on the browser instead of the image (as discussed in here - How to update a div with an image in Django? ). 当我为<img>标签的src属性分配response ,我在浏览器而不是图像上看到原始图像数据(如下所述 - 如何使用Django中的图像更新div? )。 I am not sure where I am going wrong. 我不确定我哪里出错了。

I have also tried base64 encoding on the response as follows (but not sure whether I have implemented correctly) - 我还在响应上尝试了base64编码,如下所示(但不确定我是否已正确实现) -

success: function (response) {
                $('#imagediv').html('<img alt="Embedded Image" src="data:image/png;base64,' + response + '" />');
            }

I have referred to following links to get upto this point - 我已经提到以下链接来达到这一点 -
Django: How to render image with a template Django:如何使用模板渲染图像
Serve a dynamically generated image with Django 使用Django提供动态生成的图像

I am fairly new to web-programming as well as Django. 我对网络编程和Django都很陌生。 Any insights regarding the problem will be really helpful. 任何关于这个问题的见解都会非常有用。 Thanks in advance. 提前致谢。

Try encoding the image using base64 before you send it. 在发送之前尝试使用base64对图像进行编码。

import base64
#rest of your code 
with open("pathToImage.png", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

Then 然后

success: function(response){
            $('#imagediv').html('<img src="data:image/png;base64,' + response + '" />');

If you want set image by content of any HTML tags you must apply data:{type};{encode-format} before image content and set background url in CSS, similar below: 如果您希望按照任何HTML标记的内容设置图像,则必须在图像内容之前应用data:{type};{encode-format}并在CSS中设置background网址,类似如下:

html-element{
   background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAEklEQVQImWNgIAD+QzFuAeIAAPVzA/0vfQ+9AAAAAElFTkSuQmCC) repeat;
}

Or set this by src attribute of img tag: 或者通过img标签的src属性设置:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAEklEQVQImWNgIAD+QzFuAeIAAPVzA/0vfQ+9AAAAAElFTkSuQmCC">

for example if you generate a new pattern in www.patternify.com site, you can copy and use base64 content from Base64 Code field. 例如,如果您在www.patternify.com网站中生成新模式,则可以从Base64代码字段复制和使用base64内容。

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

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