我通过ajax将图像作为base64字符串发送到django。在我的django视图中,我需要调整图像大小并将其保存在文件系统中。
这是一个base64字符串(简体):
data:image/jpeg;base64,/9j/4AAQSkZJRg-it-keeps-going-for-few-more-lines=
我尝试使用以下python代码在PIL中打开此文件:
img = cStringIO.StringIO(request.POST['file'].decode('base64')) image = Image.open(img) return HttpResponse(image, content_type='image/jpeg')
我正在尝试将上传的图像显示回去,但是firefox抱怨说 'The image cannot be displayed because it contains error'
'The image cannot be displayed because it contains error'
我不知道我的错误。
解:
pic = cStringIO.StringIO() image_string = cStringIO.StringIO(base64.b64decode(request.POST['file'])) image = Image.open(image_string) image.save(pic, image.format, quality = 100) pic.seek(0) return HttpResponse(pic, content_type='image/jpeg')
将打开的PIL图像保存到类似文件的对象即可解决此问题。