如何为存储在Google云端硬盘中的文件设置图像缩略图

时间:2017-08-18 06:11:56

标签: python google-drive-api

使用Google Drive API我可以使用files.update()方法更新任何可写文件的属性:

import datetime
data = {'modifiedTime': datetime.datetime.utcnow().isoformat() + 'Z'}
drive_service.files().update(fileId=file_id, body=data, fields='id').execute()

假设我在网络上的某处发布了PNG图片:'image':'http://pngimg.com/uploads/eagle/eagle_PNG1228.png'或保存在本地驱动器"/Users/username/Downloads/my_image.png"上的png文件。

如何将已发布在网页上的PNG文件或保存在本地驱动器上的PNG文件设置为存储在Google云端硬盘上的文件的缩略图?

这是我到目前为止所尝试的内容。 保存在我的本地驱动器上的source.png文件后,我继续使用此代码将其编码为base64_encoded.png文件(我不确定我是否正确执行):

import base64

src = '/source.png'
dst = '/base64_encoded.png'

image = open(src, 'rb')
image_read = image.read()
encodestring = base64.encodestring(image_read)
image_result = open(dst, 'wb') 
image_result.write(encodestring)

我将此base64_encoded.png文件上传到Google云端硬盘。我复制了其网址:https://drive.google.com/open?id=1234567890abcdefgh

我将此网址设置为Google云端硬盘上文件的thumbnail元数据属性:

metadata =  { "contentHints": { 'thumbnail':{'image':'https://drive.google.com/open?id=1234567890abcdefgh'}}}
result = drive_service.files().update(fileId='abcdefgh1234567', body=metadata).execute()

但我收到错误:...returned "Invalid value for ByteString: https://drive.google.com/open?id=1234567">

错误在哪里?

2 个答案:

答案 0 :(得分:2)

这个示例脚本怎么样? contentHints.thumbnail.image是URL安全的Base64编码图像。因此,您要用作新缩略图的图像数据必须转换为URL安全的Base64编码数据。为此,它在Python上使用base64.urlsafe_b64encode()

更新缩略图有一些限制。请查看https://developers.google.com/drive/v3/web/file#uploading_thumbnails上的详细信息。

我使用zip文件作为样本。 Zip文件在Google云端硬盘上没有缩略图。当使用drive.files.get确认时,hasThumbnail为false。所以这可以用。虽然我将此脚本用于Google文档和图片,但更新的图片并未反映给他们。这可能会触及限制。缩略图被赋予zip文件时,hasThumbnail变为真。在我的环境中,在第一次更新时,更新有时会失败。但当时,第二次更新工作正常。我不知道原因。对不起。

示例脚本:

import base64  # Use this

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

结果:

enter image description here

如果这对你没用,我很抱歉。

答案 1 :(得分:0)

您的网址不符合网址安全的Base64编码图片(请参阅RFC 4648 section 5

尝试使用任何localhost然后上传您的图像,然后使用缩略图的路径。我找到了jsfiddle,如果这是URL安全的Base64编码,您可以在其中试用您的网址。

测试了您的驱动器网址:

enter image description here

经过测试的 www.localhost:8080/image/dog.png 网址

enter image description here

希望这有帮助。

相关问题