【问题标题】:How to upload an image file to Github using PyGithub?如何使用 PyGithub 将图像文件上传到 Github?
【发布时间】:2022-10-12 21:21:34
【问题描述】:

我想使用 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)

但我收到以下错误:

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?

【问题讨论】:

    标签: python github github-pages github-api pygithub


    【解决方案1】:

    希望你一切顺利。

    刚刚测试了我的解决方案,它正在工作??

    解释:
    断言错误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 以有趣的方式

    file_path = "Image.png"
    message = "My 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)
    

    我对这个答案的参考。

    1. Converting Images to ByteArray
    2. Programmatically Update File PyGithub (StringFile Not Image)

      希望这个答案有帮助。 祝你有美好的一天?

    【讨论】:

      【解决方案2】:

      您收到的错误与您要上传的图像文件的错误打开有关。尝试使用 cv2 库打开它并将 img 参数传递给 GitHub create_file() 函数:

      f=cv2.imread("1.png")
      img=f
      

      【讨论】:

      • utf8 正在编码人物.使用utf8 编码打开图像没有意义。
      • LookupError: 'base64' is not a text encoding; use codecs.open() to handle arbitrary codecs 你甚至在回答或随机编写你的第一个代码之前测试你的代码吗猜测?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-01
      • 2020-01-10
      • 1970-01-01
      相关资源
      最近更新 更多