Convert base 64 image to media object

Hello again,

I have some base 64 images that I used an uplink script to scrape from other websites and store them in my data table. I can display them fine.

But now I want to allow users to download them, which isn’t possible with anvil.media.download which requires the object to be a Media Object. What would you guys do?

Many thanks,

*Edit, I’m on a free plan. I’m wondering if there is a way to convert base 64 image to Anvil Media Object.

have you tried using either the Media, URLMedia, or BlobMedia components?

https://anvil.works/docs/media

If you have the data in a datatable have you tried sending the file to the client?
I think sending the file to the client from the server will return a media object

pseudo code

@anvil.server.call
get_64_image():
  return app_tables.my_table.search()[0]['file'] 
  # send a file to the client from the datatable
def button_click(self, **event_args):
  my_file = anvil.server.call('get_64_image')
  print(type(my_file))

Hi @stucork,

Thanks for the response. In my data table, I have two columns that I use for picture data, a normal “image” column with the data type of Media object and the “image_b64” with the data type of Text. When the first column with normal picture is not present, I use the second column to display the picture, which is a string of Base 64 text. How do I use Media, URL media, BlobMedia on Text?

Good morning, @thai.

The answer is actually in your topic title: convert the base-64 text into your desired media object. This is a two-stage process:

  1. Convert the text to binary. There is a Python Standard Library module for conversions like these. See base64 — Base16, Base32, Base64, Base85 Data Encodings
  2. Convert the resulting bytes object into a Media Object (subtype: BlobMedia). See Constructing Media Objects.

Tip: Once you’ve converted the text into a usable Media Object, you may want to store that object in the row’s image column. Otherwise, the conversion work will have to be done all over again, the next time.

1 Like

Surely, that is my plan of attack. However, I cannot import the base64 package into my Anvil. Maybe because I’m on the free plan?

*Edit: actually I might have tried to import the base64 package on the client-side which is more limited. I will try to do that on the server-side to see if it works.

A post was split to a new topic: Jpeg corrupts when adding to data table