【问题标题】:Django/Python/toDataURL return a response with the string from toDataURLDjango/Python/toDataURL 返回带有来自 toDataURL 的字符串的响应
【发布时间】:2014-09-18 06:03:46
【问题描述】:

我在数据库中保存了一个由 javascript 方法 toDataURL 返回的字符串。此处提供示例:http://pastebin.com/0Qu8rngD

我需要在 django 响应中返回图像。比如:

return HttpResponse(image, mimetype='image/png')

我用base64decode、urlsafe_b64decode、Image ...尝试了很多方法,但都没有成功。导航器不显示图像,无法读取响应数据。

当然,我可以使用<img src="{{image}}"> 在 HTML 页面中显示我的图像,效果很好。

【问题讨论】:

    标签: javascript python django image todataurl


    【解决方案1】:

    图片是base64编码的数据uri;先解码图像:

    import base64
    
    ...    
    
    data_uri = 'data:...'
    image_data = data_uri.partition('base64,')[2]
    binary = base64.b64decode(image_data)
    return HttpResponse(binary, mimetype='image/png')
    

    【讨论】:

    • 我们可以使用更短的image_data.decode('base64'),而不是导入base64。无论如何,+1 更快 =)
    • 谢谢,完美,partition() 解决方案!
    • 当然.. 只是希望我有另一个 +1 插槽。
    猜你喜欢
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 2015-09-20
    • 2016-05-06
    • 2014-10-21
    • 1970-01-01
    相关资源
    最近更新 更多