将 base64 编码图像推送到 Google 联系人 Python

Pushing base64 encoded image to Google Contacts with Python

我有一张 base64 编码的 jpeg 图片,我想使用 API 作为 Google 联系人照片推送,这里有解释: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?

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