gpt4 book ai didi

python - 尝试将 .gif 文件转换为 .jpeg 时 Django 抛出 IO 错误

转载 作者:太空宇宙 更新时间:2023-11-04 10:23:13 26 4
gpt4 key购买 nike

我是 python 世界的新手。对于一个项目(使用 django),我使用 PIL 库将 .gif 文件转换为 .jpg 文件。但是当运行模型的保存方法时,它会抛出“IOError at ... cannot write mode P as JPEG”

这是我的模型类。请给我一个解决方案。提前致谢。

class ImageArtwork(models.Model):
filepath = 'art_images/'
artwork = models.ForeignKey(Artwork, related_name='images')
artwork_image = models.ImageField(_(u"Dieses Bild hinzufügen: "), upload_to=filepath)
image_medium = models.CharField(max_length=255, blank=True)
image_thumb = models.CharField(max_length=255, blank=True)
uploaded_at = models.DateTimeField(auto_now_add=True)

def get_thumb(self):
return "/media/%s" % self.image_thumb

def get_medium(self):
return "/media/%s" % self.image_medium

def get_original(self):
return "/media/%s" % self.artwork_image

def save(self):
sizes = {'thumbnail': {'height': 50, 'width': 50}, 'medium': {'height': 300, 'width': 300}, }

# Check if the number of images for the artwork has already reached maximum limit

if ImageArtwork.objects.filter(artwork=self.artwork).count() < 6:
super(ImageArtwork, self).save()
photopath = str(self.artwork_image.path) # this returns the full system path to the original file
im = Image.open(photopath) # open the image using PIL

# pull a few variables out of that full path
extension = photopath.rsplit('.', 1)[1] # the file extension
filename = photopath.rsplit('/', 1)[1].rsplit('.', 1)[0] # the file name only (minus path or extension)
fullpath = photopath.rsplit('/', 1)[0] # the path only (minus the filename.extension)

# use the file extension to determine if the image is valid before proceeding
if extension.lower() not in ['jpg', 'jpeg', 'gif', 'png']:
return
im = ImageOps.fit(im, (sizes['medium']['width'], sizes['medium']['height']), Image.ANTIALIAS) # create medium image
medname = filename + "_" + str(sizes['medium']['width']) + "x" + str(sizes['medium']['height']) + ".jpg"
im.save(fullpath + '/' + medname)
self.image_medium = '/media/' + self.filepath + medname
im = ImageOps.fit(im, (sizes['thumbnail']['width'], sizes['thumbnail']['height']), Image.ANTIALIAS) # create thumbnail
thumbname = filename + "_" + str(sizes['thumbnail']['width']) + "x" + str(
sizes['thumbnail']['height']) + ".jpg"
im.save(fullpath + '/' + thumbname)
self.image_thumb = '/media/' + self.filepath + thumbname
super(ImageArtwork, self).save()

else:
pass

最佳答案

cannot write mode P as JPEG

这不是 django 的问题,这是图像库的限制。

P 代表调色板。 PIL 在写入 JPEG 时尝试保留原始图像的颜色模式。由于 JPEG 仅支持“TrueColor”(即 RGB)图像,因此在转换(调色板)GIF 文件时会出现此错误。

保存为 JPEG 时始终将图像转换为 RGB:

im.convert('RGB').save(fullpath + '/' + medname)

关于python - 尝试将 .gif 文件转换为 .jpeg 时 Django 抛出 IO 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31000177/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com