Kshitij_Jha_7
Kshitij_Jha_7

Reputation: 73

How to upload an image file to Github using PyGithub?

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 argument and thus these errors are showing up.

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

Upvotes: 4

Views: 1858

Answers (2)

Jiya
Jiya

Reputation: 875

Just Tested my solution and it's working

Explanation:
The AssertionError assert isinstance(content, (str, bytes))
Tells us that it only takes string and bytes.

So we just have to convert our image to bytes.

#1 Converting image to bytearray

file_path = "1.png"
with open(file_path, "rb") as image:
    f = image.read()
    image_data = bytearray(f)

#2 Pushing image to Github Repo by converting the data to bytes

repo.create_file("1.png","commit", bytes(image_data))

#CompleteCode in a Fun way

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)

My References For this Answer.

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

Upvotes: 8

Cardstdani
Cardstdani

Reputation: 5223

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

Upvotes: -1

Related Questions