将上传的文件转换为PNG

时间:2015-12-28 22:15:10

标签: python django django-models python-imaging-library image-uploading

我有一个用户上传文件的Django表单。我一直在尝试首先验证文件是否为可接受的格式(jpg,png或tiff),然后将文件转换为png。我正在使用PIL但仍然卡住了。在我的最新尝试中,我无法弄清楚如何将图像转换回文件,以便可以在我的视图中将文件保存到模型中。我怎么能这样做?

以下是我的表单的def clean_image(self)方法:

    image = self.cleaned_data.get('my_image')
    if image:
        imagetype = imghdr.what(image)
        if image._size > 4*1024*1024:
            raise forms.ValidationError("Image is too large. Please select an image < 4mb")
        else:
            if imagetype not in ('jpeg, jpg, png, tiff'):
                raise forms.ValidationError("Only jpeg, png, or tiff file types can be uploaded.")
            # convert image to png regardless of initial upload state
            #size = (130, 130)
            try:
                i = Image.open(image)
                i.load()
                converted = Image.new("RGB", i.size)
                converted_name = str(image).split('.')[0] + ".png"
                converted.save(converted_name, "PNG")
            except IOError:
                raise forms.ValidationError("There was a problem saving your image. Only jpeg, png, or tiff file < 4mb types can be uploaded.")

            return converted

0 个答案:

没有答案