TypeError:预期的str、bytes或os.PathLike对象,而不是Image



我正在尝试使用内存中的图像更新用户的Twitter个人资料图片。以下是我现在的记录:

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
tweets = api.user_timeline(screen_name = QUERY, count = 5, include_rts = False, 
tweet_mode = 'extended'
response = requests.get(tweets[0].user.profile_image_url)
img = Image.open(BytesIO(response.content))
flipped_img = img.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
api.update_profile_image(flipped_img)

当我运行这个时,我遇到了以下错误

File "c:UsersxPythontwitter_bot.py", line 32, in <module>
api.update_profile_image(flipped_img)
File "C:UsersxAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagestweepyapi.py", line 46, in wrapper
return method(*args, **kwargs)
File "C:UsersxAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagestweepyapi.py", line 2912, in update_profile_image
files = {'image': open(filename, 'rb')}
TypeError: expected str, bytes or os.PathLike object, not Image

我已经尝试在线搜索将内存图像转换为操作系统的方法。PathLike对象,但没有找到解决方案。提前感谢您的帮助!

看起来Tweepy API不喜欢内存中的图像,所以使用临时文件:

img = Image.open(BytesIO(response.content))
flipped_img = img.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
with tempfile.NamedTemporaryFile(suffix=".png") as tf:
img.save(tf, format="png")
api.update_profile_image(tf.name)

with块确保临时文件之后被删除。

相关内容

最新更新