Reputation: 11
I already have the body of my code in which I can create an album and then take a picture directly from Pythonista. After that, I would want to take this recently took picture and transfer it into the album that I just created. This is what I have:
import photos
import console
console.clear()
nom_album = contacts
photos.create_album(nom_album)
img=photos.capture_image()
Upvotes: 1
Views: 1405
Reputation: 3456
The photos.create_album
method returns an Asset-Collection
object. Asset-Collections have a method, add_assets
, that take a list of “assets”, that is, photos. Specifically, as I read it, an Asset is a photo that is already in the iOS device’s photo library. To add a photo to an album, the photo must already be in the device’s photo library.
The capture_image
method does not return Asset objects, however. That is, it does not automatically add the new photo to the device’s photo library. You can verify this in your own code: the images you take using that code should not be in your device’s “recents” album.
Instead, capture_image
returns a PIL image. I do not see any way to add a PIL image to the device’s photo library directly. What I was able to do was save the PIL image locally and then convert the saved file into an Asset. That is, (1) add the saved file to the device’s photo library, using create_image_asset
; then (2) that Asset can then be added to an Asset-Collection.
Here‘s an example:
import photos
#a test album in the device’s library
#note that multiple runs of this script will create multiple albums with this name
testAlbum = 'Pythonista Test'
#the filename to save the test photograph to in Pythonista
testFile = testAlbum + '.jpg'
#create an album in the device’s photo library
newAlbum = photos.create_album(testAlbum)
#take a photo using the device’s camera
newImage = photos.capture_image()
#save that photo to a file in Pythonista
newImage.save(testFile)
#add that newly-created file to the device’s photo library
newAsset = photos.create_image_asset(testFile)
#add that newly-created library item to the previously-created album
newAlbum.add_assets([newAsset])
If you don’t want to keep the file around in your Pythonista installation, you can use os.remove
to remove it.
import os
os.remove(testFile)
While saving a PIL image to a local file first and then adding the file to the device’s library seems a convoluted means of adding a PIL image to the device’s library, it appears to be the expected means of doing this. In Photo Library Access on iOS, the documentation says:
To add a new image asset to the photo library, use the create_image_asset() function, providing the path to an image file that you’ve saved to disk previously.
Upvotes: 0