我已经有了我的代码主体,我可以在其中创建一个相册,然后直接从 Pythonista 拍照。在那之后,我想把这张最近拍的照片转移到我刚刚创建的相册中。这就是我所拥有的:
import photos
import console
console.clear()
nom_album = contacts
photos.create_album(nom_album)
img=photos.capture_image()
我已经有了我的代码主体,我可以在其中创建一个相册,然后直接从 Pythonista 拍照。在那之后,我想把这张最近拍的照片转移到我刚刚创建的相册中。这就是我所拥有的:
import photos
import console
console.clear()
nom_album = contacts
photos.create_album(nom_album)
img=photos.capture_image()
该photos.create_album
方法返回一个Asset-Collection
对象。Asset-Collections 有一个方法,add_assets
,它获取“资产”列表,即照片。具体来说,当我读到它时,资产是已经在 iOS 设备的照片库中的照片。要将照片添加到相册,照片必须已经在设备的照片库中。
但是,该capture_image
方法不返回 Asset 对象。也就是说,它不会自动将新照片添加到设备的照片库中。您可以在自己的代码中验证这一点:您使用该代码拍摄的图像不应出现在您设备的“最近”相册中。
相反,capture_image
返回一个 PIL 图像。我看不到任何将 PIL 图像直接添加到设备照片库的方法。我能够做的是在本地保存 PIL 图像,然后将保存的文件转换为资产。即 (1) 将保存的文件添加到设备的照片库中,使用create_image_asset
; 然后 (2) 然后可以将该资产添加到资产集合中。
这是一个例子:
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])
如果您不想在 Pythonista 安装中保留该文件,则可以使用os.remove
将其删除。
import os
os.remove(testFile)
虽然首先将 PIL 图像保存到本地文件,然后将文件添加到设备库似乎是一种将 PIL 图像添加到设备库的复杂方法,但它似乎是执行此操作的预期方法。在iOS 上的 Photo Library Access 中,文档说:
要将新图像资源添加到照片库,请使用 create_image_asset() 函数,提供您之前保存到磁盘的图像文件的路径。