How do I export a photo from apple photos using JXA?

22 Views Asked by At

I'm trying to use javascript-for-automation on my Mac to export images from Apple Photos but I can't get around a Can't convert types error.

The problematic line in my code is Photos.export( { export: matchingPhotos, to: destination } ) but I don't know how to fix it. I really only want to export randomPhoto, not the whole list of matching_photos, but I'm trying to get this to work first, because matching_photos is definitely a list of media items. I think the problem is the type of the destination, which should be a 'file'.

This is what I have from the Photos Dictionary in Apple's Script Editor

exportmethod : Export media items to the specified location as files
 export list of [MediaItem](#) : The list of media items to export.
  to: file : The destination of the export.
  [usingOriginals: boolean] : Export the original files if true, otherwise export rendered jpgs. defaults to false.

My code, which I'm running from the command line with echo "$(osascript -l JavaScript <<'EOT'...:

const posix_path="/Users/erik/dev/temp/"
const destination=Path(posix_path)
const Photos=Application("Photos")
Photos.includeStandardAdditions = true //  What does this accomplish?
matchingPhotos=Photos
    .search({for:"ravens"})
    .filter(x=>x.filename().match(/(jpeg|jpg|heic)$/i)
)
if (matchingPhotos.length>0){
    const randomPhoto = matchingPhotos[
        Math.floor(Math.random() * matchingPhotos.length)
    ]
    console.log("foo")
    Photos.export({ export: matchingPhotos, to: destination } )
    console.log("bar")
    randomPhoto.size()
} else {
    0
}

The output:

foo
execution error: Error: Error: Can't convert types. (-1700)

I've also tried Photos.export( { export: matchingPhotos, to: posix_path } ) to see if that would work but it doesn't.

I can't find any relevant documentation or examples about using JXA to export from photos. Pointers to such material would be very helpful.

I managed to export a photo using AppleScript but I couldn't manage the list-filtering and got frustrated with the syntax.

Any ideas? Thanks!

1

There are 1 best solutions below

1
On

The line causing the problem

Photos.export( { export: matchingPhotos, to: destination } )

should read

Photos.export( matchingPhotos, { to: destination } )

and to get only one photo it would be

Photos.export( [randomPhoto], {to: destination} )