Thumbnail

Updating Thumbnail of File on Google Drive using Python

Gists

This sample script is for updating thumbnail of file on Google Drive using Python.

This sample supposes that quickstart is used and default quickstart works fine. In order to use this sample, please carry out as follows.

  • Replace main() of the default quickstart to this sample.

Script :

import base64 # This is used for this sample.

def main():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive', 'v3', http=http)

    with open("./sample.png", "rb") as f:
        res = service.files().update(
            fileId="### file ID ###",
            body={
                "contentHints": {
                    "thumbnail": {
                        "image": base64.urlsafe_b64encode(f.read()).decode('utf8'),
                        "mimeType": "image/png",
                    }
                }
            },
        ).execute()
        print(res)

contentHints.thumbnail.image is URL-safe Base64-encoded image. So an image data that you want to use as new thumbnail has to be converted to URL-safe Base64-encoded data. For this, it uses base64.urlsafe_b64encode() at Python.