首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用python中的api将图像从驱动器插入幻灯片

使用python中的api将图像从驱动器插入幻灯片
EN

Stack Overflow用户
提问于 2020-04-20 17:00:52
回答 1查看 286关注 0票数 2

我正在尝试将google drive中的图像插入到现有幻灯片演示文稿中,但出现错误

代码语言:javascript
复制
Invalid requests[0].createImage: The provided image was not found

我已经尝试了几种方法来生成一个可以工作的链接(fig_url 2-8)。此外,我手动设置文件夹,幻灯片文件和图像文件的权限为“任何人与此链接可以查看”。但是,唯一有效的链接仍然是在线链接(fig_url1)。

此外,如果有一种方法可以在不运行flow (打开浏览器)的情况下完成这项工作,那将是最好的。

代码语言:javascript
复制
def insert_figure_image_to_slides(user_login_dict, figure_url, page_id):
    presentation_id = user_login_dict["presentation_id"]
    jsonFile = user_login_dict["api_login_json"]
    scope = 'https://www.googleapis.com/auth/presentations'#, 'https://www.googleapis.com/auth/drive.file'
    seed(randint(page_id,101))
    id=randint(1, 100000)
    image_id = "Figure" + str(id)

    try:
        working_folder = os.getcwd()
        os.chdir("..")
        os.chdir(user_login_dict["certificates_folder"])
        credentials = service_account.ServiceAccountCredentials.from_json_keyfile_name(jsonFile, scopes=scope)
        os.chdir(working_folder)

        service = build('slides', 'v1', http=credentials.authorize(httplib2.Http()), cache_discovery=False)
        slides = service.presentations().get(presentationId=presentation_id,
                                         fields='slides').execute().get('slides')
        page_ids = []
        for slide in slides:
            page_ids.append(slide['objectId'])

        emu4M = {
            'magnitude': 4000000,
            'unit': 'EMU'
        }
        requests=[]
        requests.append({
            'createImage': {
                'objectId': image_id,
                'elementProperties': {
                    'pageObjectId': page_ids[page_id]
                },
                'url': figure_url
            }
        })

        body = {
        'requests': requests
    }
        response = service.presentations().batchUpdate(presentationId=presentation_id,
                                                   body=body).execute()
        create_image_response = response.get('replies')[0].get('createImage')

        print('Created image with ID: {0}'.format(
            create_image_response.get('objectId')))

    except:
        os.chdir(working_folder)
        print("Image insertion into presentation failed")


def export_figures_to_drive(user_login_dict, figure_name, figure_no):
    drive_folder_id = user_login_dict["drive_folder_id"]
    file_name = figure_name + ".png"
    scopes = (
        'https://www.googleapis.com/auth/drive',
        'https://www.googleapis.com/auth/presentations',
    )


    os.chdir("Output_files")
    output_dir = os.getcwd()
    os.chdir("..")

    try:
        working_folder = os.getcwd()
        os.chdir("..")
        os.chdir(user_login_dict["certificates_folder"])
        g_login = GoogleAuth(user_login_dict["drive_login_yaml"])
        g_login.LocalWebserverAuth()

        store = Storage(user_login_dict["drive_login_json"])
        flow = client.flow_from_clientsecrets(user_login_dict["drive_login_json"], scopes)

        os.chdir(working_folder)
        drive = GoogleDrive(g_login)
        file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
        for file in file_list:
            if file['title'] == user_login_dict["result_file_name"]:
                folder_id = file.get('id')

        file_list = drive.ListFile({'q': "'%s' in parents and trashed=false" % folder_id}).GetList()
        for file1 in file_list:
            if file1['title'] == file_name:
                file1.Delete()

        os.chdir(output_dir)
        file_on_drive = drive.CreateFile({'parents': [{'id': drive_folder_id}]})
        file_on_drive.SetContentFile(file_name)
        file_on_drive.Upload()
        os.chdir(working_folder)
        print('Graph Export to drive complete - %s' % (file_name))
        metadata = file_on_drive.attr["metadata"]
        fig_url4 = metadata["alternateLink"]
        fig_url5 = metadata['selfLink']
        fig_url6 = metadata['webContentLink']
        fig_url7 = metadata['downloadUrl']
    except:
        os.chdir(working_folder)
        print("Error uploading file to drive")

    creds = tools.run_flow(flow, store) #opens browser identificaiton page
    HTTP = creds.authorize(httplib2.Http())
    DRIVE = discovery.build('drive', 'v3', http=HTTP)
    rsp = DRIVE.files().list(q="name='%s'" % file_name).execute().get('files')[0]

    fig_url1 = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png'
    fig_url2 = "https://drive.google.com/uc?export=download&id=" + rsp["id"]
    fig_url3 = '%s&access_token=%s' % (DRIVE.files().get_media(fileId=rsp['id']).uri, creds.access_token)
    fig_url8="https://drive.google.com/file/d/1AmCmoc8Xrv706yJeWCmCuQw0HQkkYHpQ/view?usp=sharing"

    insert_figure_image_to_slides(user_login_dict=user_login_dict, figure_url=fig_url1, page_id=figure_no)
EN

回答 1

Stack Overflow用户

发布于 2020-04-20 19:39:00

你需要做两件事

  1. documentation指定必须将图像设置为可公开访问(您已经这样做了)
  2. 此外,需要指定为documentation的图像的链接是
  3. url

两者的组合应该使您能够将图像插入到幻灯片中。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61318669

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档