How to upload an image file to Github using PyGithub?

Viewed 247

I want to upload an image file to my Github Repository using 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)

But I am getting the following Error:

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>

This method is working fine for text files. But I am not able to upload image files to my repository.

When I use open-CV to read the image file I get the following error:

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

My Code while using cv2 is:

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)

I think createFile() only takes string as an arguement and thus these errors are showing up.

Is there any way to upload the image file to Github using Pygithub(or any library) ?

1 Answers

The error you are getting is related to a wrong opening of the image file you want to upload. Try to open it with cv2 library and passing img argument to the GitHub create_file() function:

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