Пример #1
0
    def _transform_mobile_image(
        self, original_image_blob: Blob, new_image_blob: Blob
    ) -> Optional[Blob]:
        """
        Create smaller image size to be served on mobile devices.

        :param Blob original_image_blob: Original image blob.
        :param Blob new_image_blob: New newly created Blob for mobile image.

        :returns: Optional[Blob]
        """
        img_meta = self._get_image_meta(original_image_blob)
        img_bytes = original_image_blob.download_as_bytes()
        if img_bytes:
            stream = BytesIO(img_bytes)
            im = Image.open(stream)
            try:
                with BytesIO() as output:
                    new_image = im.reduce(2)
                    new_image.save(output, format=img_meta["format"])
                    new_image_blob.upload_from_string(
                        output.getvalue(), content_type=img_meta["content-type"]
                    )
                    LOGGER.success(f"Created mobile image `{new_image_blob.name}`")
                    return new_image_blob
            except GoogleCloudError as e:
                LOGGER.error(
                    f"GoogleCloudError while saving mobile image `{new_image_blob.name}`: {e}"
                )
            except Exception as e:
                LOGGER.error(
                    f"Unexpected exception while saving mobile image `{new_image_blob.name}`: {e}"
                )