我想要上传一个图像文件到我的Github仓库使用Pygithub。
from github import Github
g=Github("My Git Token")
repo=g.get_repo("My Repo")
content=repo.get_contents("")
f=open("1.png")
img=f.read()
repo.create_file("1.png","commit",img)
但我得到了以下错误:
File "c:\Users\mjjha\Documents\Checkrow\tempCodeRunnerFile.py", line 10, in <module>
img=f.read()
File "C:\Program Files\Python310\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 119: character maps to <undefined>
对于文本文件,此方法运行良好。但是我无法将图像文件上传到我的存储库。
当我使用open-CV读取图像文件时,我会得到以下错误:
assert isinstance(content, (str, bytes))
AssertionError
我使用cv2的代码是:
from github import Github
import cv2
g=Github("")
repo=g.get_repo("")
content=repo.get_contents("")
f=cv2.imread("1.png")
img=f
repo.create_file("1.png","commit",img)
我认为createFile()只使用字符串作为论证,因此出现了这些错误。
是否有任何方法可以使用Pygithub(或任何库)将图像文件上传到Github?
发布于 2022-10-12 13:21:34
希望你做得很好。
刚刚测试了我的解决方案,它起作用了
解释:
AssertionError assert isinstance(content, (str, bytes))
告诉我们它只需要字符串和字节。
因此,我们只需将图像转换为字节。
#1将图像转换为字节数组
file_path = "1.png"
with open(file_path, "rb") as image:
f = image.read()
image_data = bytearray(f)
#2通过将数据转换为字节()将图像推送给Github
repo.create_file("1.png","commit", bytes(image_data))
#CompleteCode以一种有趣的方式
from github import Github
g=Github("Git Token")
repo=g.get_repo("Repo")
file_path = "Image.png"
message = "Commit Message"
branch = "master"
with open(file_path, "rb") as image:
f = image.read()
image_data = bytearray(f)
def push_image(path,commit_message,content,branch,update=False):
if update:
contents = repo.get_contents(path, ref=branch)
repo.update_file(contents.path, commit_message, content, sha=contents.sha, branch)
else:
repo.create_file(path, commit_message, content, branch)
push_image(file_path,message, bytes(image_data), branch, update=False)
我对这个答案的参考资料.
希望这个答案有帮助。祝你过得愉快,
发布于 2022-06-18 09:50:22
所获得的错误与要上载的图像文件的打开错误有关。尝试使用cv2
库打开它,并将img
参数传递给GitHub create_file()
函数:
f=cv2.imread("1.png")
img=f
https://stackoverflow.com/questions/72668275
复制相似问题