Cropper+Snapshot

Here are the Custom Components I used in the App above/

The first component, ‘Cropper’ allows cropping of images and returning the result

To crop an image, add the custom component to your app and call it

self.cropper_1.crop() #This works by mentioning the aspect ratio

You can also do freecropping by using

self.cropper_1.freecrop() #free cropping of image without any ratio

Then you can call the getresult or downloadresult method

The second component ‘Snapshot’ returns a screenshot of an anvil component

You can use the

Snapshot.get_snapshot() #b64 string of image

or

Snapshot.downloadsnapshot() #download result

I used the following Javascript libraries for it

GitHub - tsayen/dom-to-image: Generates an image from a DOM node using HTML5 canvas

6 Likes

Hey @divyeshlakhotia,

For the cropper - is it possible to somehow directly use the file from self.file_loader.file without having to save it to a table first?

Nevermind, ChatGPT came to the rescue :joy:

Here is the solution if anybody else is curious:

def file_loader_1_change(self, file, **event_args):
    if file is not None:
        # Read file content and convert to base64 Data URL
        from base64 import b64encode
        
        file_bytes = file.get_bytes()
        b64_string = b64encode(file_bytes).decode('utf-8')
        mime_type = file.content_type or "image/png"  # fallback
        data_url = f"data:{mime_type};base64,{b64_string}"

        # Call the cropper
        self.cropper_1.crop(data_url, 1, 1)

I’m surprised it actually worked lol

3 Likes