将Base64字符串加载到Python图像库中

Pra*_*een 10 python django base64 image python-imaging-library

我通过ajax将图像作为base64字符串发送到django.在我的django视图中,我需要调整图像大小并将其保存在文件系统中.

这是一个base64字符串(简化):

data:image/jpeg;base64,/9j/4AAQSkZJRg-it-keeps-going-for-few-more-lines=
Run Code Online (Sandbox Code Playgroud)

我尝试使用下面的python代码在PIL中打开它:

img = cStringIO.StringIO(request.POST['file'].decode('base64'))
image = Image.open(img)
return HttpResponse(image, content_type='image/jpeg')
Run Code Online (Sandbox Code Playgroud)

我正在尝试显示上传的图像,但是firefox抱怨说 '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')
Run Code Online (Sandbox Code Playgroud)

Pra*_*een 13

解:

将打开的PIL图像保存到类似文件的对象可以解决问题.

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')
Run Code Online (Sandbox Code Playgroud)