0

I'm trying to write an AWS Lambda function that takes a TIFF, converts it to JPEG, then outputs it in base64 so that lambda can serve it. But I keep running into malformed response, or issues with reshape_as_image saying axes doesn't match array.

My understanding was that the return of memfile.read() would allow me to use reshape_as_image, however my logic seems faulty.

Without saving to disk, how can I get from memfile to a base64 jpeg representation so that lambda can serve it? I've also tried pillow but I think the necessary step is where I'm failing.

    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
Kevin Redman
  • 459
  • 4
  • 15

1 Answers1

1

It seems this isn't necessary for some reason, assuming because memfile.read() gives the actual bytes of the image.

    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
Kevin Redman
  • 459
  • 4
  • 15