python Django值错误“seek of closed file”在更新记录时使用PIL调整图像大小

xlpyo6sf  于 2022-12-10  发布在  Python
关注(0)|答案(1)|浏览(461)

我有以下模型:

class Players(models.Model):
    team = models.ForeignKey(Teams, verbose_name=_('Team'), on_delete=models.CASCADE)
    player_name = models.CharField(_('Player Name'),max_length=200)
    player_description = models.TextField(_('Player Description'))
    player_image = models.ImageField(_('Profile Pic'),upload_to='upload/player_image', null=True, blank=True)
    player_social = models.CharField(_('Social Media Tag'),max_length=200)

    class Meta:
        verbose_name = _("Players")
        verbose_name_plural = _("Players")

    def __str__(self):
        return self.team.team_name + ' - ' + self.player_name
    
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        if self.player_image:
            image_resize(self.player_image, 250)

最后一个函数将调用另一个函数来调整图像大小,以获取文件和预期的最大宽度:

# Use PIL to resize images; set target width on each
def image_resize(image, tgt_width):
        img = PIL.Image.open(image)
        img.load()
        width, height = img.size
        target_width = tgt_width
        h_coefficient = width/tgt_width
        target_height = height/h_coefficient
        img = img.resize((int(target_width), int(target_height)), PIL.Image.ANTIALIAS)
        img.save(image.path, quality=100)
        img.close()
        image.close()

我对更新的看法如下:

@method_decorator(superuser_required, name='dispatch')
class PlayerUpdateView(UpdateView):
    model = Players
    template_name = 'scoreboard/players/player_update.html'
    form_class = PlayersForm
    context_object_name: str = 'player'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        team_id = Players.objects.get(pk=self.kwargs['pk']).team.id
        context["team"] = Teams.objects.get(pk=team_id)
        return context
    
    def form_valid(self, form):
        form.save()
        return super().form_valid(form)

    def get_success_url(self):
        team_id = Players.objects.get(pk=self.kwargs['pk']).team.id
        return reverse_lazy('team_detail', kwargs={'pk': team_id})

无论我是否提供了新的图像文件,我都会得到相同的“seek of closed file”错误:

File "D:\00_www\hts-score\overlay\scoreboard\models.py", line 62, in save
    image_resize(self.player_image, 250)
  File "D:\00_www\hts-score\overlay\scoreboard\models.py", line 15, in image_resize
    img = PIL.Image.open(image)
  File "D:\00_www\hts-score\venv\lib\site-packages\PIL\Image.py", line 3096, in open
    fp.seek(0)
ValueError: seek of closed file

我怎样才能让图像得到处理呢?我错过了什么?
我试着添加if方法,这样如果没有文件,它就不会触发resize函数。我希望函数检查图像文件的存在,然后处理它。添加img.load()没有帮助。

bvjxkvbb

bvjxkvbb1#

所以,在尝试了几次之后,我找到了这个答案。我不是很清楚为什么它能工作,但是看起来with方法能正确地打开和关闭文件。在PIL文档中找到了这个答案。image_resize()函数看起来像这样:

def image_resize(image, tgt_width):
    with Image.open(image) as img:
        width, height = img.size
        ratio = width / height
        tgt_height = int(tgt_width / ratio)
        img = img.resize((tgt_width, tgt_height), Image.ANTIALIAS)
        img.save(image.path)

在保存方法中使用if条件时,每次都有效。

相关问题