The Least You Need to Know About GitHub Pages
The least you need to know about GitHub Pages is laser-focused on one thing: showing how to get a working informational website up and running as fast as possible using GitHub Pages, using only the GitHub website.
Adding images to your GitHub Pages site
The Jekyll publishing system used by GitHub Pages expects you to have an assets directory, and that’s where image files should be placed. By convention they go into an images subdirectory (full path /docs/assets/images but that’s not a firm requirement. They can be anywhere in the /docs/assets path.
Create a directory called /docs/assets
- If you haven’t yet created an assets directory, read Adding an assets directory to GitHub Pages and follow those steps to create a directory at /docs/assets .
Upload images to the /docs/assets directory
On GitHub, navigate to the /docs/assets directory.
Click the Add file button, then choose Upload files
How to add images to GitHub readme
I remember when I first started learning to code and had to upload my first project to Github, I wanted to add images or screenshots of my app to the readme section. I kept on searching the internet, and I actually found a way that was suggested by some developers to store your images in your git repo and then refer to them, but this option would take a lot of steps for every screenshot image and was kind of overwhelming for me. That’s why I decided to write this article to show you how to add images to your GitHub readme.
Use Imgur as an External Free Cloud Hosting Website
I have found this way to add images to the Github readme. First, I would upload the screenshot image to my account on Imgur website. For those of you who don’t know Imgur:
Imgur is an American online image sharing community and image host. The service has been popular with hosting viral images and memes, particularly those posted on Reddit.
So here is Imgur link if you want to check it out:
Imgur
Discover the magic of the internet at Imgur, a community powered entertainment destination. Lift your spirits with…
You go to Imgur and create an account. Then after signing up, you will be redirected to a page like this shown below.
Then right click on your account image and you’ll be presented with the shown menu.
Click on images and you’ll be redirected to the following page where you can add your own images. Click on “add images” and then browse your image from your device or paste the image url.
Now all the images you have uploaded will appear in this section.
Click on the image you’ve just uploaded and copy the “Direct link”, the second link with “.png” at the end.
Use Markdown Syntax to add the image url to the GitHub readme
Now if you want to make use of this copied direct link from imgur and show an image in the GitHub readme file, you will need to use the Markdown syntax. For those of you who don’t know what is Markdown. Markdown is a plain text formatting syntax for writers. It allows you to quickly write structured content for the web, and have it seamlessly converted to clean, structured HTML.
If you want to learn more about Markdown syntax and all the different types of content that you can include in the Github readme using this syntax including headings, quotes, lists, images, etc, then check out this great blog article at ghost.
What you have to do now is go back to Github, open the readme section, and paste the following markdown in your post including the url you’ve just copied. Make sure you specify the width like giving it a value of 300 or so, or the screenshot image will be huge!
And Voila here is the readme file with the screenshots’ images added:
How to add three images to GitHub readme in one row?
If you want to include more than one screenshot image in the same row, you just write the markdown in your readme file as following:
This will add three images into one row as shown below:
And this is how we can easily add images to the Github readme file. If you want to know how to add gifs to Github readme, then you can check out this article.
Добавьте изображения в README.md на GitHub
Недавно я присоединился к GitHub. Я принимал там несколько проектов.
Мне нужно включить некоторые изображения в мой файл README. Я не знаю, как это сделать.
Я искал об этом, но все, что я получил, было несколько ссылок, которые говорят мне «размещать изображения в Интернете и указывать путь к изображению в файле README.md».
Есть ли способ сделать это без размещения изображений на сторонних веб-хостингах?
24 ответа
Попробуйте эту уценку:
Я думаю, вы можете напрямую ссылаться на необработанную версию изображения, если она хранится в вашем репозитории. то есть.
Изменить: только что заметил комментарий, ссылающийся на статью, в которой предлагается использовать gh-страницы. Кроме того, относительные ссылки могут быть лучше, чем абсолютные URL-адреса, опубликованные выше.
Вы также можете использовать относительные пути, такие как
- Вы можете создать новый выпуск
- загружать (перетаскивать) изображения на него
- Скопируйте URL-адрес изображения и вставьте его в файл README.md.
Вот подробное видео YouTube, объясняющее это подробно:
Это намного проще.
Просто загрузите изображение в корне репозитория и укажите ссылку на имя файла без какого-либо пути, например:
Вы также можете добавить изображения с простыми тегами HTML:
Многие из опубликованных решений являются неполными или не соответствуют моему вкусу.
- Внешний CDN, такой как imgur, добавляет еще один инструмент в цепочку. Мех.
- Создание фиктивной проблемы в трекер-проблеме — это взлом. Это создает беспорядок и смущает пользователей. Это боль, чтобы перенести это решение на вилку или с GitHub.
- Использование ветки gh-страниц делает URL-адреса хрупкими. Другой человек, работающий над проектом, поддерживающим gh-страницу, может не знать, что что-то внешнее зависит от пути к этим изображениям. В ветке gh-pages есть особое поведение в GitHub, которое не обязательно для размещения изображений CDN.
- Отслеживание активов в контроле версий — это хорошо. По мере роста проекта и изменения его более устойчивого способа управления и отслеживания изменений несколькими пользователями.
- Если изображение относится к конкретной версии программного обеспечения, может быть предпочтительнее связать неизменяемое изображение. Таким образом, если изображение будет обновлено позже, чтобы отразить изменения в программном обеспечении, любой, кто читает эту версию readme, найдет правильное изображение.
Мое предпочтительное решение, вдохновленное этот смысл, заключается в использовании ветки активов с permalinks до конкретные изменения.
Построить «постоянную ссылку» на эту ревизию изображения и обернуть ее в Markdown:
Чтобы всегда показывать последнее изображение в ветки активов, используйте assets вместо шага:
/Downloads , /tmp и т. Д.).
Зафиксируйте ваше изображение (image.png) в папке ( myFolder) и добавьте следующую строку в README. md:

- Создайте проблему с добавлением изображений
- Добавить изображение путем перетаскивания или выбора файла
Затем скопируйте источник изображения
Теперь добавьте  в ваш файл README.md
В качестве альтернативы вы можете использовать сайт для размещения изображений, например imgur , и получить его url и добавить его в свой файл README.md, или вы можете использовать некоторый статический хостинг файлов.
Основной синтаксис
Здесь:
- my-image-alt-tag: текст, который будет отображаться, если изображение не отображается.
- url-to-image: независимо от вашего ресурса изображения. URI изображения
Пример:
Это будет выглядеть следующим образом:

Просто добавьте <img> в ваш README.md с относительным src в ваш репозиторий. Если вы не используете относительный src, убедитесь, что сервер поддерживает CORS.
Это работает, потому что GitHub поддерживает inline-html
Мне нужно включить некоторые изображения в мой файл README. Я не знаю, как сделайте это.
Я создал небольшой мастер, который позволяет создавать и настраивать простые галереи изображений для вашего репозитория GitHub: см. ReadmeGalleryCreatorForGitHub.
Мастер использует тот факт, что GitHub позволяет создавать теги img в README.md . Кроме того, мастер использует популярный трюк для загрузки изображений в GitHub путем drag’n’dropping их в области проблем (как уже упоминалось в одном из ответов в этом потоке).
В моем случае я использую imgur и использую прямую ссылку таким образом.
Вы можете ссылаться на изображения в вашем проекте из README.md (или извне), используя альтернативную ссылку на github CDN.
URL будет выглядеть так:
У меня есть изображение SVG в моем проекте, и когда я ссылаюсь на него в документации по проекту Python, оно не отображается.
Ссылка на проект
Вот ссылка проекта на файл (не отображается как изображение):
Пример встроенного изображения:
Необработанная ссылка
Вот RAW-ссылка на файл (по-прежнему не отображается как изображение):
Пример встроенного изображения:
CDN ссылка
Используя ссылку CDN, я могу связать файл, используя (отображает как изображение):
Пример встроенного изображения:
Вот как я могу использовать изображения из своего проекта как в файле README.md , так и в моем проекте reStructredText в PyPi (здесь)
Я решил эту проблему. Вам нужно только обратиться к другому файлу readme.
Сначала вы должны загрузить файл изображения в библиотеку кодов github! Затем прямая ссылка на адрес файла изображения.


Обычно я размещаю изображение на сайте, это может быть ссылка на любой размещенный образ. Просто бросьте это в readme. Работает для файлов .rst , не уверен в .md
В случае, если вам нужно загрузить несколько картинок для документации, хорошим подходом является использование git-lfs. Предполагая, что вы установили git-lfs, выполните следующие действия:
Внедрите git lfs для каждого типа вашего изображения:
Создайте папку, которая будет использоваться в качестве местоположения изображения, например. doc . В системах на основе GNU/Linux и Unix это можно сделать с помощью:
Скопируйте и вставьте любые изображения в папку с документами. Затем добавьте их с помощью команды git add .
Передайте и нажмите.
Изображения общедоступны по следующему адресу:
https://media.githubusercontent.com/media/ ^ github_username ^/^ repo ^/^ филиал ^/^ image_location в репозитории ^
Где: * ^github_username^ — имя пользователя в github (вы можете найти его на странице профиля) * ^repo_name^ — имя репозитория * ^branch^ — ветка репозитория, куда загружается изображение * ^image_location in the repo^ — местоположение, включая папку, в которой хранится изображение.
Кроме того, вы можете сначала загрузить изображение, а затем зайти в папку на странице проектов github и перемещаться по ней, пока не найдете изображение, затем нажать кнопку download , а затем скопировать и вставить URL-адрес из адресной строки браузера.
Посмотрите это из моего проекта в качестве ссылки.
Затем вы можете использовать URL, чтобы включить их, используя синтаксис уценки, упомянутый выше:
Например: давайте предположим, что мы используем эту фотографию. Затем вы можете использовать синтаксис уценки:
3 Ways to Add an Image to GitHub README
Images often come in handy alongside documentation. Here are a few methods for adding them to your README and other markdown files.
Images can be a great way to enhance your documentation in README files or other markdown documentation. While there is a standard way to add an image in markdown, the nuance is in the image's source. Here are three methods for adding images to markdown files in a GitHub repository.
Markdown Syntax
The original documentation specifies that images should be written like so:
HTML code is also valid within most markdown renderers, including GitHub's flavor. That means you could also render an the image above like this:
This is a great option if you want to add a little custom styling to your image. For example, if you want to control the size or alignment of the image, you might do something like this:
Method #1: Local File
The first method is to commit the image directly to your GitHub repository. When you do that, you can use a path to that file for the src , which should be relative from the markdown file.
In other words, if you place an image file in the root your project as my-image.jpg , you could then render the image in your projects main README.md file like this ( title omitted for simplicity):
Let's say the image file was instead in an images directory. Then your code in the project's main README file would look like this:
Now, let's say that you have another README file in your src directory, but your image is still in the images directory. Then your relative path looks like this:
This approach is a quick and easy option, as long as you don't have too many images to manage. If you end up using a lot of images, I'd consider another route .
Method #2: Remote File
Another option is to use some external file hosting service to provide your image, such as S3 or Dropbox. In this case, you could get the direct and full URL to the image and then use that.
Method #3: Uploaded File
Lastly, you could use GitHub to host the image for you. This one is a little goofy, but it totally works!
The trick is to add them to some comment — an issue, pull request or discussion — and then grab the resulting URL.
You can drag and drop the image from your computer to a comment field in GitHub. Wait for the file to upload and then the URL to the image is right there! You don't even have to submit the issue if you don't want to (although that may limit the image's lifespan).
Unlike the other two options, I see two issues with this approach:
- On its own, it becomes difficult to know the source of the image. Maybe that's not a big deal, or maybe you have a way to streamline it — e.g. all your images go into a single "Images" issue that stays open.
- The purpose of images in comments is technically to serve the comment. It's possible GitHub changes these URLs without notifying you.
Inspiration & Resources
This post was originally inspired by this tweet from @DavidDarnes:
Haha nice! FYI if you upload those readme images in a new GitHub comment and it'll give you the image paths back to put them in your readme, then you won't have them cluttering the repo 😶
— Dave 🧱 (@DavidDarnes) January 18, 2021
I ended up being more comprehensive than just this singular suggestion, which came to be more in-line with this StackOverflow question.