首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用PyGithub将图像文件上传到Github?

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

Stack Overflow用户
提问于 2022-06-18 09:45:54
回答 2查看 475关注 0票数 3

我想要上传一个图像文件到我的Github仓库使用Pygithub。

代码语言:javascript
运行
复制
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)

但我得到了以下错误:

代码语言:javascript
运行
复制
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读取图像文件时,我会得到以下错误:

代码语言:javascript
运行
复制
    assert isinstance(content, (str, bytes))
    AssertionError

我使用cv2的代码是:

代码语言:javascript
运行
复制
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?

EN

回答 2

Stack Overflow用户

发布于 2022-10-12 13:21:34

希望你做得很好。

刚刚测试了我的解决方案,它起作用了

解释:

AssertionError assert isinstance(content, (str, bytes))

告诉我们它只需要字符串字节

因此,我们只需将图像转换为字节

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

代码语言:javascript
运行
复制
file_path = "1.png"
with open(file_path, "rb") as image:
    f = image.read()
    image_data = bytearray(f)

#2通过将数据转换为字节()将图像推送给Github

代码语言:javascript
运行
复制
repo.create_file("1.png","commit", bytes(image_data))

#CompleteCode以一种有趣的方式

代码语言:javascript
运行
复制
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)

我对这个答案的参考资料.

  1. 将图像转换为ByteArray
  2. 以编程方式更新文件PyGithub (StringFile非图像)

希望这个答案有帮助。祝你过得愉快,

票数 2
EN

Stack Overflow用户

发布于 2022-06-18 09:50:22

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

代码语言:javascript
运行
复制
f=cv2.imread("1.png")
img=f
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72668275

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档