【问题标题】:return dynamic generated file without creating tmp version?返回动态生成的文件而不创建 tmp 版本?
【发布时间】:2013-09-11 19:13:13
【问题描述】:

在我的 django 服务器上,我通过命令行使用 imagemagick 创建了一个图像文件。

cmd = local_file + " -crop 50%x50%+10+10 " + temp_final_file

out, err = subprocess.Popen( cmd.split(), 
                  stdin = subprocess.PIPE,
                  stdout = subprocess.PIPE,
                  stderr = subprocess.PIPE ).communicate()

然后我将文件返回给客户端:

    mt = mimetypes.guess_type( temp_final_file )[0]
    with open( temp_final_file, "rb" ) as f:
       response = HttpResponse( f.read(), mimetype=mt )
    return response

我想知道是否可以避免写入本地文件而直接返回字节?

【问题讨论】:

标签: python django imagemagick


【解决方案1】:

ImageMagick 可以写入其标准输出,因此您实际上并不需要临时文件。试试这个:

cmd = ['convert', local_file, '-crop', '50%x50%+10+10', '-']
new_image = subprocess.check_output( cmd )
response = HttpResponse( new_image, mimetype=mt )

注意:您仍然需要弄清楚 mime 类型。如果没有文件,这可能会更困难。

【讨论】:

  • 最后的'-'是我不熟悉的一些imagemagick-fu。很有趣,谢谢。
  • 您也可以说'JPG:-''GIF:-' 来强制使用特定的图像格式。
  • 因为我在 python 2.6 上并且没有 check_output,所以我刚刚调整了我的 OP 中的代码以返回标准输出并且一切正常。非常感谢!
【解决方案2】:

f.read() 只是一个 python2 字节串。你可以在那里传递任何东西。

您必须使用一些接口,而不是允许您直接检索字节,而不是写入文件。例如,一个 imagemagick 包装器,像这样:

https://www.assembla.com/wiki/show/pythonmagickwand

【讨论】:

    猜你喜欢
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    • 1970-01-01
    相关资源
    最近更新 更多