要在python中压缩的图像

时间:2014-01-21 17:17:55

标签: python django python-2.7

目前,我正在使用下面的代码,但它给了我一个损坏的zip文件..

url = urllib2.urlopen('http://mattfarmer.net/projects/thickbox/images/plant4.jpg')
f = StringIO()
zip = zipfile.ZipFile(f, 'w')
zip.writestr('plant4.jpg', url.read())
response = HttpResponse(f.getvalue(), content_type="application/zip")
response['Content-Disposition'] = 'attachment; filename=plant4bar.zip'
return response

1 个答案:

答案 0 :(得分:1)

你应该关闭你的zip文件

from django.http import HttpResponse
import urllib2
from StringIO import StringIO
import zipfile

def home(request):
    url = urllib2.urlopen('http://mattfarmer.net/projects/thickbox/images/plant4.jpg')
    f = StringIO()
    zip = zipfile.ZipFile(f, 'w')
    zip.writestr('plant4.jpg', url.read())
    zip.close() # Close
    response = HttpResponse(f.getvalue(), content_type="application/zip")
    response['Content-Disposition'] = 'attachment; filename=plant4bar.zip'
    return response