Converts an image to JPEG

Takes an image as string and converts it to JPEG and lets user see it and download it

Script windmill

by henri186 ยท 4/17/2024

  • Submitted by henri186 Python3
    Created 755 days ago
    1
    import base64
    2
    from PIL import Image, UnidentifiedImageError
    3
    import io
    4
    
    
    5
    
    
    6
    # Define the main function with the specified parameter types
    7
    def main(image_base64: str):
    8
        try:
    9
            # Decode the base64 encoded image
    10
            image_data = base64.b64decode(image_base64)
    11
    
    
    12
            # Convert the binary data to an image
    13
            image = Image.open(io.BytesIO(image_data))
    14
    
    
    15
            # Convert the image to JPEG format
    16
            # Note: We use BytesIO to handle the conversion in memory
    17
            with io.BytesIO() as output:
    18
                image.convert("RGB").save(output, format="JPEG")
    19
                jpeg_data = output.getvalue()
    20
    
    
    21
            # Encode the JPEG image to base64
    22
            jpeg_base64 = base64.b64encode(jpeg_data).decode("utf-8")
    23
    
    
    24
            # Return the base64 encoded JPEG image
    25
    
    
    26
            return { "render_all": [ { "file": { "content": jpeg_base64, "filename": "image.jpg" } }, { "jpeg": jpeg_base64 } ]}
    27
    
    
    28
        except UnidentifiedImageError:
    29
            # Handle the case where the image cannot be identified
    30
            return "Error: The provided data does not represent a valid image."
    31