project.py 文件源码

python
阅读 22 收藏 0 点赞 0 评论 0

项目:tn2 作者: hsoft 项目源码 文件源码
def validate_and_resize_image(self, image_uploaded_file):
        def cant_read():
            raise forms.ValidationError(
                "Impossible de lire l'image. Veuillez contacter les administrateurs de T&N"
            )

        if not isinstance(image_uploaded_file, UploadedFile):
            return image_uploaded_file
        result_bytes = io.BytesIO()
        try:
            with Image.open(image_uploaded_file) as image:
                # Ensure that our image has the proper orientation according to its EXIF data. For
                # this, we piggy-back on easy_thumbnails's own utility functions.
                new_image = exif_orientation(image)
                w, h = new_image.size
                if w > 630 or h > 630:
                    new_image.thumbnail((630, 630))
                try:
                    new_image.save(result_bytes, format=image.format)
                except OSError:
                    # could be a "cannot write mode P as JPEG" situation.
                    # let's try http://stackoverflow.com/a/21669827
                    try:
                        new_image.convert('RGB').save(result_bytes, format=image.format)
                    except OSError:
                        # Oh, screw that.
                        cant_read()
        except (FileNotFoundError, OSError):
            # Can't read the image, unset it
            cant_read()

        return SimpleUploadedFile(
            name=image_uploaded_file.name,
            content=result_bytes.getvalue(),
            content_type=image_uploaded_file.content_type,
        )
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号