我有一个base64编码的jpeg图像,我想使用API将其推送为Google联系人照片,此处解释:更新联系人的照片。
查看 ChangePhoto 方法的文档给出了以下内容:
Type: instancemethod
String form: <bound method ContactsClient.change_photo of <gdata.contacts.client.ContactsClient object at 0x104756090>>
File: /Library/Python/2.7/site-packages/gdata/contacts/client.py
Definition: a.ChangePhoto(self, media, contact_entry_or_url, content_type=None, content_length=None, auth_token=None, **kwargs)
Docstring:
Change the photo for the contact by uploading a new photo.
Performs a PUT against the photo edit URL to send the binary data for the
photo.
Args:
media: filename, file-like-object, or a gdata.data.MediaSource object to send.
contact_entry_or_url: ContactEntry or str If it is a ContactEntry, this
method will search for an edit photo link URL and
perform a PUT to the URL.
content_type: str (optional) the mime type for the photo data. This is
necessary if media is a file or file name, but if media
is a MediaSource object then the media object can contain
the mime type. If media_type is set, it will override the
mime type in the media object.
content_length: int or str (optional) Specifying the content length is
only required if media is a file-like object. If media
is a filename, the length is determined using
os.path.getsize. If media is a MediaSource object, it is
assumed that it already contains the content length.
我的问题是,我没有类似文件的对象。我想我唯一的选择是创建一个gdata.data.MediaSource对象。这样做的问题是我找不到任何关于如何正确构造这样一个对象的好文档。
如何从我的base64编码图像构造这样的gdata.data.MediaSource对象。如何正确指定content_type和content_length?
Python 为您提供了类似内存文件的对象。在 Python 2 上,使用 cStringIO.StringIO
(在极少数情况下,缺少 C 优化版本,回退到 StringIO.StringIO
):
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
image_data = your_image_data.decode('base64')
image_file = StringIO(image_data)
a.ChangePhoto(
image_file, contact_url, content_type='image/jpg',
content_length=len(image_data))
我确实假设您的 Base64 编码图像数据(存储在 your_image_data
中是直接编码的,而不是数据 URI。