如何使用 API V2(在 python 中)在 Dropbox 上上传图片?

How to upload an image on dropbox using its API V2 (in python)?

我需要创建一个管道,从保管箱中获取图像,对其进行处理并将其上传回(可以是不同的文件夹)。前两个步骤很简单,但似乎没有办法使用较新的 API V2 将图像上传到保管箱。我尝试上传本地图片 - 从计算机读取并将其保存到保管箱,但没有成功。问题似乎是文件的格式,我收到以下错误:

expected request_binary as binary type

文本文件有很多示例并且效果很好,而对于图像,相同的解决方案失败了

import dropbox
from PIL import Image

dbx = dropbox.Dropbox('access_token') # Connecting to the account
metadata,file=dbx.files_download('/PATH_TO_IMAGE') # Getting the image from DropBox
im=Image.open(io.BytesIO(file.content)) # Getting the image to process

dbx.files_upload(im, '/PATH', mode=WriteMode('overwrite'))

也尝试过:

dbx.files_upload_session_start(im)

Python3, 保管箱 SDK 9.4.0 实际上我已经尝试过以各种格式放置文件,所以除了 im 之外还有 im.read(), np.array(im.getdata()).encode(), io.BytesIO (),来自我的计算机的本地图像,但没有任何效果。而且我不明白如何将图像数据转换为 'request_binary as binary type'。

所以据我所知,需要的是一种将任何文件转换为 'request_binary'

的方法
TypeError: expected request_binary as binary type, got <class --SMTH ELSE-->

多亏了 Greg,我找到了一个解决方案,比示例中写的要简单一些

import dropbox
from PIL import Image
import numpy as np
import io


def load_image(filepath: str) -> bytes:
    image = Image.open(filepath)  # any image
    l = np.array(image.getdata())

    # To transform an array into image using PIL:
    channels = l.size // (image.height * image.width)
    l = l.reshape(image.height, image.width, channels).astype(
        "uint8"
    )  # unit8 is necessary to convert
    im = Image.fromarray(l).convert("RGB")

    # to transform the image into bytes:
    with io.BytesIO() as output:
        im.save(output, format="PNG")
        contents = output.getvalue()
    return contents

contents = load_image("1.png")
dbx = dropbox.Dropbox("access_token")  # Connecting to the account
dbx.files_upload(
    contents, "/FOLDER/IMAGE.png", dropbox.files.WriteMode.add, mute=True
)

我会这样做:

import dropbox


def load_image(filepath: str) -> bytes:
    with open(filepath, "rb") as fp:
        contents = fp.read()
    return contents

contents = load_image("1.png")
dbx = dropbox.Dropbox("access_token")  # Connecting to the account
dbx.files_upload(
    contents, "/FOLDER/IMAGE.png", dropbox.files.WriteMode.add, mute=True
)