Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将Base64字符串加载到Python映像库中_Python_Django_Image_Base64_Python Imaging Library - Fatal编程技术网

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

将Base64字符串加载到Python映像库中,python,django,image,base64,python-imaging-library,Python,Django,Image,Base64,Python Imaging Library,我通过ajax将图像作为base64字符串发送到django。在django视图中,我需要调整图像大小并将其保存在文件系统中 以下是base64字符串(简化): 我尝试使用以下python代码在PIL中打开此文件: img = cStringIO.StringIO(request.POST['file'].decode('base64')) image = Image.open(img) return HttpResponse(image, content_type='image/jpeg')

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

以下是base64字符串(简化):

我尝试使用以下python代码在PIL中打开此文件:

img = cStringIO.StringIO(request.POST['file'].decode('base64'))
image = Image.open(img)
return HttpResponse(image, content_type='image/jpeg')
我试图显示上传的图像,但firefox抱怨说,
“图像无法显示,因为它包含错误”

我想不出我的错误


解决方案:

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

解决方案:

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图像保存到类似文件的对象可以解决此问题

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

发布的字符串(
data:image/jpeg;base64,
)的开头是一个头,应该在解码之前删除。 否则图像将损坏

photo = request.POST['photo'].partition('base64,')[2]
image_data = b64decode(photo)
someobject.photo.save('user.jpg', ContentFile(image_data), save=True)

多亏了Praveen针对python2的解决方案,但我发现python3的版本是:

import io
import base64
pic = io.BytesIO()
image_string = io.BytesIO(base64.b64decode(base64_str))
image = Image.open(image_string)
image.save(pic, image.format, quality=100)
pic.seek(0)
return HttpResponse(pic, content_type='image/jpeg')
请注意
数据:image/jpeg;base64,
part实际上不是base64字符串,因此如果base64字符串包含,则应将其删除:

base64_str = base64_uri[23:]

您是否尝试过:
base64.b64解码(request.POST['file'])
?是的,我得到了无法识别的图像文件您尝试过使用解释器会话吗?只需对文件进行编码,稍后解码,看看是否有效?是的,尝试过了。解码字符串没有问题。请尝试在某个地方准确打印您得到的内容:request.POST['file'],然后查看它是否与在交互式会话中工作的字符串相同。此解决方案似乎是错误的。使用PIL,可以强制将图像保存为有效的JPEG格式,但事实并非如此(请参见下面的答案)?因此,它可能有点损坏,但人们无法注意到它。
base64_str = base64_uri[23:]