我有一个base64编码的jpeg图像,我希望使用API将其作为Google Contact照片推送,如下所述:Updating a photo for a contact。
查看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?
答案 0 :(得分:2)
Python为您提供内存中类文件对象。在Python 2上,使用cStringIO.StringIO
(在极少数情况下回退到StringIO.StringIO
,缺少C优化版本):
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
中是直接编码的,而不是data URI。