微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Rasterio MemoryFile 到 Pillow 图像或 base64 输出

如何解决Rasterio MemoryFile 到 Pillow 图像或 base64 输出

我正在尝试编写一个 AWS Lambda 函数,该函数接受 TIFF,将其转换为 JPEG,然后以 base64 格式输出,以便 lambda 可以为其提供服务。但我一直遇到格式错误的响应,或者 reshape_as_image 说轴与数组不匹配的问题。

我的理解是 memfile.read() 的返回将允许我使用 reshape_as_image,但是我的逻辑似乎有问题。

不保存到磁盘,如何从 memfile 获取 base64 jpeg 表示,以便 lambda 可以为其提供服务?我也试过枕头,但我认为必要的步骤是我失败的地方。

    def get_image(self,driver="jpeg"):
        data = self.get_image()

        with MemoryFile() as memfile:
            # Change the driver for output
            data[1]['driver'] = driver
        with MemoryFile() as memfile:
            # Change the driver for output
            data[1]['driver'] = driver

            with memfile.open(**data[1]) as dataset:
                dataset.write(data[0])
                
            image = memfile.read()
            image = reshape_as_image(image)
            im = Image.open(io.BytesIO(image))
            b64data = base64.b64encode(im.tobytes()).decode('utf-8')
            return b64data

解决方法

出于某种原因,这似乎不是必需的,假设是因为 memfile.read() 给出了图像的实际字节。

    def get_image(self,store=False,driver="GTiff"):
        data = self.crop_ortho(store)

        with MemoryFile() as memfile:
            # Change the driver for output
            data[1]['driver'] = driver

            with memfile.open(**data[1]) as dataset:
                dataset.write(data[0])

            image = memfile.read()
            im = Image.open(io.BytesIO(image))
            im = im.convert('RGB')
            # Save bytes to a byte array
            imgByteArr = io.BytesIO()
            im.save(imgByteArr,format='jpeg')

            b64data = base64.b64encode(imgByteArr.getvalue())
            
            return b64data

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。