如何从 Pythonista 拍摄照片并将它们导出到我的 iOS 设备上已有的特定相册中

问题描述

我已经有了我的代码主体,我可以在其中创建相册,然后直接从 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 图像添加到设备库的一种复杂方法,但它似乎是执行此操作的预期方法。在 Photo Library Access on iOS 中,文档说:

要将新图像资产添加到照片库,请使用 create_image_asset() 函数,提供您之前保存到磁盘的图像文件的路径。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...