python - Django 。如何保存使用 Pillow 编辑的内容文件

标签 python django python-imaging-library

我正在尝试保存使用 requests 下载的图像,然后使用 Pillow 将其编辑到模型中的 ImageField。但是创建对象时没有图像。

这是我的:

设置.py

MEDIA_ROOT = BASE_DIR + "/media/"
MEDIA_URL = MEDIA_ROOT + "/magicpy_imgs/"

模型.py

def create_path(instance, filename):
    path = "/".join([instance.group, instance.name])
    return path

class CMagicPy(models.Model):
    image = models.ImageField(upload_to=create_path)
    ....

    # Custom save method
    def save(self, *args, **kwargs):
        if self.image:
            image_in_memory = InMemoryUploadedFile(self.image, "%s" % (self.image.name), "image/jpeg", self.image.len, None)
            self.image = image_in_memory

        return super(CMagicPy, self).save(*args, **kwargs)

表单.py

class FormNewCard(forms.Form):
    imagen = forms.URLField(widget=forms.URLInput(attrs={'class': 'form-control'}))

View .py

def new_card(request):
    template = "hisoka/nueva_carta.html"

    if request.method == "POST":

        form = FormNewCard(request.POST)

        if form.is_valid():

            url_image = form.cleaned_data['imagen']
            group = form.cleaned_data['grupo']
            name = form.cleaned_data['nombre']
            description = form.cleaned_data['descripcion']

            answer = requests.get(url_image)
            image = Image.open(StringIO(answer.content))
            new_image = image.crop((22, 44, 221, 165))
            stringio_obj = StringIO()

            try:
                new_image.save(stringio_obj, format="JPEG")
                image_stringio = stringio_obj.getvalue()
                image_file = ContentFile(image_stringio)
                new_card = CMagicPy(group=group, description=description, name=name, image=image_file)
                new_card.save()

            finally:
                stringio_obj.close()

            return HttpResponse('lets see ...')

它创建对象但没有图像。请帮忙。几个小时以来,我一直在努力解决这个问题。

最佳答案

背景

虽然InMemoryUploadedFile主要供 MemoryFileUploadHandler 使用,它也可以用于其他目的。应该注意的是,MemoryFileUploadHandler 用于处理用户使用网络表单或小部件上传文件到您的服务器的情况。然而,您正在处理的情况是,用户仅提供一个链接,您将文件下载到您的网络服务器上。

让我们还记得 ImageFile本质上是对存储在文件系统中的文件的引用。只有文件名输入数据库,文件内容本身存储在存储系统中。 Django 允许您指定不同的存储系统,以便在需要时可以将文件保存在云端。

解决方案

您需要做的就是将使用 Pillow 生成的图像内容和文件名传递给 ImageField。该内容可以通过 InMemoryUploaded 文件 ContentFile 发送。但是,没有必要同时使用两者。

这就是您的模型。

class CMagicPy(models.Model):
    image = models.ImageField(upload_to=create_path)

    # over ride of save method not needed here.

这是你的看法。

  try:
     # form stuff here

     answer = requests.get(url_image)

     image = Image.open(StringIO(answer.content))
     new_image = image.rotate(90) #image.crop((0, 0, 22, 22))
     stringio_obj = StringIO()


     new_image.save(stringio_obj, format="JPEG")
     image_file = InMemoryUploadedFile(stringio_obj, 
         None, 'somefile.jpg', 'image/jpeg',
         stringio_obj.len, None)

     new_card = CMagicPy()
     new_card.image.save('bada.jpg',image_file)
     new_card.save()

 except:
     # note that in your original code you were not catching
     # an exception. This is probably what made it harder for
     # you to figure out what the root cause of the problem was
     import traceback
     traceback.print_exc()
     return HttpResponse('error')
 else:
     return HttpResponse('done')

脚注

添加了异常处理,因为事情可能会出错。

您应该使用 answers.headers['Content-type'] 并选择合适的一个,而不是使用 JPEG 和 image/jpeg。

关于python - Django 。如何保存使用 Pillow 编辑的内容文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37153809/

相关文章:

python - 在Python中删除异常值并计算具有不同实际值数量的多列的修剪平均值

django - 为什么 Django 不使用默认的 404 View 传递错误消息?

用于检测损坏图像的 Python 脚本

multithreading - 在标签tkinter上显示视频大小

Python PIL 图像比较问题

c# - 在 JetBrains PyCharm 上使用 IronPython

python - 名称错误 : name 'scipy' is not defined

mysql - 另一个数据库中的 Django 外键

python - 如何在删除重复单词并在 Python 中对列表进行排序的同时将文本文件转换为列表?

python - 在Django上实现多层角色