How to Embed Images in an HTML File
Learn the standard <img> pattern, self-contained base64 images, responsive formats, accessibility, troubleshooting, and practical performance tips.
Use an <img> element and point its src attribute at the image file:
<img src="images/photo.jpg" alt="A red canoe beside a wooded shore" width="1200" height="800">
This is the normal way to embed one image in HTML. The browser loads the image as a separate resource. Use a relative path for an image in your project or an absolute URL for an image hosted elsewhere. The HTML Standard specifies the img element with src when there is one image resource (HTML Standard).
1. Add an image from your project
Place the image where your project can serve it, then make the path relative to the HTML file.
my-site/
├── index.html
└── images/
└── photo.jpg
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Image example</title>
</head>
<body>
<main>
<h1>A canoe by the shore</h1>
<img
src="images/photo.jpg"
alt="A red canoe beside a wooded shore"
width="1200"
height="800"
>
</main>
</body>
</html>
If the HTML file is inside a directory, use ../ to move up one level. A leading slash such as /images/photo.jpg is resolved from the website origin, not from the directory containing the HTML file. An absolute URL such as https://example.com/images/photo.jpg points to another host.
2. Use correct alternative text and dimensions
Write an alt value that conveys the image’s purpose. For an informative image, describe the useful content. For a decorative image, use an empty value:
<img src="divider.svg" alt="">
Include the intrinsic width and height when you know them. The browser can reserve the correct aspect ratio while the file loads, reducing layout movement. The HTML Standard and MDN cover alt and image dimensions in the img element definition and MDN’s img reference.
3. Make a standalone HTML file with a data URL
If the HTML file must carry a small image with it, encode the image bytes as base64 and place them in a data: URL:
<img
src="data:image/png;base64,PASTE_THE_BASE64_ENCODED_IMAGE_DATA_HERE"
alt="A small decorative blue circle"
width="32"
height="32">
The syntax is data:[media-type][;base64],data. The comma separates the metadata from the encoded bytes. Declare the real MIME type, such as image/png or image/jpeg, and keep ;base64 when the bytes are base64 encoded. A missing media type defaults to text, so an omitted or incorrect type can stop the image from rendering (MDN data URLs).
Generate the value on common systems
# macOS or Linux
base64 -i photo.png | tr -d '\n'
# GNU/Linux alternative
base64 -w 0 photo.png
# PowerShell
[Convert]::ToBase64String([IO.File]::ReadAllBytes("photo.png"))
Prefix the output with data:image/png;base64, and paste the complete value into src. The placeholder above is not an image until you replace it with the encoded data.
When data URLs are appropriate
Use one for a tiny icon, a self-contained example, or a document that must travel as one file. Referenced files are easier to edit, cache, reuse, and serve for normal page assets. Browsers do not have one guaranteed maximum data-URL length; practical limits vary, so avoid embedding large photos (MDN data URLs). Data URLs also do not inherit the surrounding page’s origin and should not be treated as a way to bypass origin or security boundaries.
4. Serve responsive images
Offer multiple widths with srcset and tell the browser how much layout space the image normally occupies with sizes:
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
sizes="(max-width: 700px) 100vw, 800px"
alt="A red canoe beside a wooded shore"
width="1600"
height="1067">
The w descriptors describe file widths and are used with sizes. Do not mix width descriptors and pixel-density (1x, 2x) descriptors in the same srcset. For fixed-density variants, use:
<img
src="logo.png"
srcset="logo.png 1x, logo@2x.png 2x"
alt="Example logo"
width="200"
height="60">
See MDN’s responsive images guide for the selection rules.
5. Provide format or art-direction fallbacks with picture
Use <picture> when you need modern-format sources, alternate crops, or media-specific images. Keep the fallback <img> last and keep its alt there:
<picture>
<source srcset="photo.avif" type="image/avif">
<source srcset="photo.webp" type="image/webp">
<img
src="photo.jpg"
alt="A red canoe beside a wooded shore"
width="1200"
height="800">
</picture>
JPEG is commonly used for photographic images, PNG for lossless detail or transparency, SVG for scalable vector artwork, and WebP or AVIF for modern compression. Choose based on the image and the browser environments you support; keep a fallback when compatibility requires it (MDN image file type guide).
6. Embed an image returned by a screenshot service
A screenshot API can produce a normal PNG, JPEG, or WebP file that you then serve with <img>. For example, after saving shot.webp in images/:
<img src="images/shot.webp" alt="Screenshot of the pricing page" width="1440" height="900">
7. Troubleshooting checklist
| Symptom | Likely cause | Fix |
|---|---|---|
| Broken-image icon | Wrong relative path or filename case | Resolve the path from the HTML file’s directory and check capitalization. Confirm the file is included in the deployed build. |
| Works locally, fails after deployment | Local filesystem path or different public root | Use a URL served by the site, inspect the browser Network panel, and avoid C:\ or /Users/... paths. |
| Data URL shows text or nothing | Missing comma, MIME type, or base64 marker | Use data:image/png;base64,...; remove line breaks from the encoded value and verify the source file is not corrupt. |
| Image is distorted | CSS forces both dimensions independently | Set one dimension to auto, or preserve the source aspect ratio with matching width and height attributes. |
| Wrong responsive file | Incorrect sizes or mixed descriptor types |
Use w descriptors with sizes, or use only x descriptors for density variants. |
| Image is inaccessible | Missing or meaningless alt |
Describe informative content; use alt="" for decoration. |
| Remote image blocked | Host unavailable, hotlink protection, or a restrictive policy | Serve an image you control, check the response status and Content-Type, and review your site’s CSP and the remote server’s policy. |
8. Performance, reliability, and security
- Use appropriately sized files and responsive sources so a phone does not download a desktop-sized photo.
- Set
widthandheightto reserve layout space. - Use a stable, cacheable file URL for images reused across pages. Data URLs duplicate bytes in every HTML document and cannot be independently cached.
- Lazy-load below-the-fold images with
loading="lazy"; keep the main above-the-fold image eager unless measurement shows otherwise. - Use
decoding="async"when asynchronous decoding is suitable for your page. - Serve the correct
Content-Type, use HTTPS for remote images, and avoid user-controlled URLs when they could expose private resources. - Remember that a remote image can disappear or change. For durable documents, store a copy under your control.
<img
src="images/article-photo.webp"
alt="A red canoe beside a wooded shore"
width="1200"
height="800"
loading="lazy"
decoding="async">
9. File URL versus data URL
| Requirement | Use a file or URL | Use a data URL |
|---|---|---|
| Normal website asset | Best choice | Usually unnecessary |
| One standalone HTML file | Requires shipping the image separately | Useful for a small image |
| Many pages reuse the image | Browser and CDN caching work well | Bytes are repeated in each page |
| Large photograph | Easier to update and optimize | Source becomes unwieldy |
| Responsive variants | srcset and picture work naturally |
Possible, but difficult to maintain |
Or skip the browser setup
ScreenshotNeo returns a clean PNG, JPEG, WebP, or PDF from one GET request, so you can save the response and reference it with a normal <img>. Its consent step accepts cookie banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed. Responses identify the result with X-Page-Verdict and X-Billed headers. It also provides an MCP server for AI agents and supports custom capture settings.
Read the ScreenshotNeo API documentation for all options.
cURL
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
Node.js
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const buffer = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', buffer));
You get 1,000 screenshots a month free with no card. Paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
FAQ
Can I use a local file path in src?
Use a project-relative path for a file that will be served with the page. A machine-specific filesystem path will not work for visitors after deployment.
Does base64 improve image quality?
No. It changes representation, not the underlying pixels. It makes the HTML larger and is mainly useful for small self-contained assets.
Should every image have descriptive alt text?
Informative images need meaningful alternative text. Decorative images generally use an empty alt value so assistive technology can skip them.
Can I embed SVG the same way?
Yes. Reference an SVG with <img src="icon.svg" alt="...">, or use a correctly encoded data URL. Inline SVG markup is a separate technique with different accessibility and styling considerations.
Why is my image stretched on mobile?
Keep the intrinsic ratio with correct width and height attributes and CSS such as max-width: 100%; height: auto;. Use srcset and sizes when different source widths are needed.


