Convert image to base64 string in Scriptable

Hi,

I’m trying to convert an image that’s passed to a Scriptable script (from a share sheet in iPadOS) to a base64 encoded string that I can then use in a callback to add an image to a note/sheet in the Ulysses app.

I see an instance method called toBase64String but I’m not sure how to take an image object that’s passed into the script and convert that to a base64 string using this method. Ideally, I’d like to also URL encode this base64 string before sending it to Ulysses. Any pointers would be much appreciated!

FWIW, I had a Shortcuts shortcut that worked perfectly to take images from any app and create a sheet in Ulysses with the images as attachments. iPadOS 14 broke that shortcut! :frowning: So I’m trying to see if I can use a Scriptable script to do this instead.

Thanks!

here’s something quick to encode the image file with base64 and add the data url prefix, in case you’re getting fileURLs via share sheet.

since the data url needs to indicate the type of data, depending on the image type you’ll be using you may need to change that.

let fm, path, file, encoded, dataurl

fm = FileManager.iCloud()
path = fm.bookmarkedPath('bookmark')
file = fm.joinPath(path, 'image.jpg')
encoded = Data.fromFile(file).toBase64String()

dataurl = `data:image/jpeg;base64,${encoded}`

if you’re using receiving images via share sheet, you can use Data.fromJPEG() or Data.fromPNG() instead but i haven’t tried getting an image directly via share sheet.

Thanks for the pointers, that worked! I am indeed passing images from the share sheet into the script. I was able to get it to work w/ the following code (in case anyone runs into this in the future):

  data = Data.fromJPEG(args.images[i]) // running this within a for loop, hence the index i  
  let image_data = data.toBase64String()

Timely - as there’s a discussion over on the Drafts Forum about data: URLs.

Can someone post example output here? I want to see if it is quite in the form we need (and I would want to support in md2pptx). Thanks!