加载Base64编码的字符串为Python图像库 [英] Loading Base64 String into Python Image Library

查看:1546
本文介绍了加载Base64编码的字符串为Python图像库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过Ajax来的Django发送图像为base64字符串。在我的Django认为我需要调整图像大小,并将其保存在文件系统中。

下面是一个Base64字符串(简体):

 数据:图像/ JPEG; BASE64,/ 9J / 4AAQSkZJRg-IT-保持持续换几个,多线=

我试着使用PIL打开此下面的蟒蛇code:

  IMG = cStringIO.StringIO(request.POST ['文件'。德code('的base64'))
图像= Image.open(IMG)
返回的Htt presponse(图像,CONTENT_TYPE =图像/ JPEG')

我想显示上传的图片回来,但Firefox抱怨'无法显示图像,因为它包含错误

我无法弄清楚我的错误。

解决方案:

  PIC = cStringIO.StringIO()image_string = cStringIO.StringIO(base64.b64de code(request.POST ['文件']))图像= Image.open(image_string)image.save(PIC,image.format,质量= 100)pic.seek(0)返回的Htt presponse(PIC,CONTENT_TYPE =图像/ JPEG')


解决方案

解决方案:

打开PIL图像保存为一个类文件对象解决了这个问题。

  PIC = cStringIO.StringIO()
image_string = cStringIO.StringIO(base64.b64de code(request.POST ['文件']))
图像= Image.open(image_string)
image.save(PIC,image.format,质量= 100)
pic.seek(0)
返回的Htt presponse(PIC,CONTENT_TYPE =图像/ JPEG')

I'm sending images as base64 string through ajax to django. In my django view I need to resize the image and save it in the file system.

Here is a base64 string(simplified):

data:image/jpeg;base64,/9j/4AAQSkZJRg-it-keeps-going-for-few-more-lines=

I tried to open this in PIL using the below python code:

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

I'm trying to display the uploaded image back, but firefox complains that 'The image cannot be displayed because it contains error'

I couldn't figure out my mistake.

SOLUTION:

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')

解决方案

SOLUTION:

Saving the opened PIL image to a file-like object solves the issue.

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')

这篇关于加载Base64编码的字符串为Python图像库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆