如何使用 PyGithub 将图像文件上传到 Github?

Ksh*_*a_7 4 python github github-api github-pages pygithub

我想使用 Pygithub 将图像文件上传到我的 Github 存储库。

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)
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

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>
Run Code Online (Sandbox Code Playgroud)

此方法对于文本文件效果很好。但我无法将图像文件上传到我的存储库。

当我使用 open-CV 读取图像文件时,出现以下错误:

    assert isinstance(content, (str, bytes))
    AssertionError
Run Code Online (Sandbox Code Playgroud)

我使用 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)
Run Code Online (Sandbox Code Playgroud)

我认为 createFile() 仅将字符串作为参数,因此会出现这些错误。

有没有办法使用 Pygithub(或任何库)将图像文件上传到 Github?

Jiy*_*iya 7

刚刚测试了我的解决方案并且它有效

解释:
AssertionErrorassert isinstance(content, (str, bytes))
告诉我们它只需要stringbytes

所以我们只需将图像转换为字节即可。

#1 将图像转换为字节数组

file_path = "1.png"
with open(file_path, "rb") as image:
    f = image.read()
    image_data = bytearray(f)
Run Code Online (Sandbox Code Playgroud)

#2 通过将数据转换为字节来将图像推送到 Github Repo

repo.create_file("1.png","commit", bytes(image_data))
Run Code Online (Sandbox Code Playgroud)

#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)
Run Code Online (Sandbox Code Playgroud)

我的这个答案的参考资料。

  1. 将图像转换为 ByteArray
  2. 以编程方式更新文件 PyGithub (字符串文件而不是图像)