Loading Base64 String into Python Image Library(将 Base64 字符串加载到 Python 图像库中)
问题描述
我通过 ajax 将图像作为 base64 字符串发送到 django.在我的 django 视图中,我需要调整图像大小并将其保存在文件系统中.
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.
这是一个base64字符串(简体):
Here is a base64 string(simplified):
data:image/jpeg;base64,/9j/4AAQSkZJRg-it-keeps-going-for-few-more-lines=
我尝试使用以下 python 代码在 PIL 中打开它:
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')
我正在尝试将上传的图片显示回来,但是firefox抱怨'图片无法显示,因为它包含错误'
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.
解决方案:
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 图像保存到类似文件的对象可以解决问题.
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 图像库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 Base64 字符串加载到 Python 图像库中
基础教程推荐
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
