How to Paste an Image into HTML
Learn the correct <img> syntax, responsive images, Base64 data URLs, accessibility, troubleshooting, and automated screenshots for HTML pages.
To add one image to an HTML page, use an <img> element with a web-accessible src URL and useful alt text:
<img src="images/photo.jpg" alt="A red bicycle leaning against a brick wall" width="800" height="600">
The img element is a void element, so it has no closing tag. Use a normal file URL for most websites. If you need the image bytes inside the HTML itself, use a Base64 data URL instead.
1. Add an image with a file URL
The src attribute identifies the image resource. It can be a relative URL on your site or an absolute URL hosted elsewhere.
Relative URL
<img src="images/photo.jpg" alt="A red bicycle leaning against a brick wall">
If the page is at /about/team.html, this example looks for the file at /about/images/photo.jpg. Use an absolute-root path when the asset is relative to the site root:
<img src="/images/photo.jpg" alt="A red bicycle leaning against a brick wall">
Absolute URL
<img src="https://example.com/images/photo.jpg" alt="A red bicycle leaning against a brick wall">
The visitor’s browser must be able to request the URL. A path on your own computer, such as C:\\Users\\you\\Pictures\\photo.jpg, will not work for people visiting a public website.
Complete HTML page
<!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>Our bicycle</h1>
<img
src="images/photo.jpg"
alt="A red bicycle leaning against a brick wall"
width="800"
height="600"
>
</main>
</body>
</html>
2. Write useful alt text and dimensions
alt is the text alternative used when an image cannot be seen or loaded and by assistive technology. Describe the image’s meaningful content or function.
- Meaningful image:
alt="A red bicycle leaning against a brick wall" - Functional image link:
alt="Return to the home page" - Pure decoration:
alt=""
Do not put the filename, “image,” or a long paragraph in alt. If the image contains essential information, provide that information in nearby text too.
Set width and height when you know the intrinsic dimensions:
<img src="photo.jpg" width="800" height="600" alt="A red bicycle leaning against a brick wall">
These attributes let the browser reserve the correct aspect ratio while the image loads, reducing layout movement. CSS can still make the image responsive:
img {
max-width: 100%;
height: auto;
display: block;
}
3. Paste the image bytes with a Base64 data URL
If “paste” means embedding the bytes directly in the markup, set src to a data URL. Include the correct MIME type and the complete Base64 payload:
<img
src="data:image/png;base64,BASE64_IMAGE_DATA"
alt="A small red icon"
>
Replace BASE64_IMAGE_DATA with the encoded bytes; the placeholder itself is not an image. Common MIME types include image/png, image/jpeg, image/gif, image/webp, and image/svg+xml.
Generate a data URL on the command line
On macOS or Linux, this shell command prints a PNG data URL:
printf 'data:image/png;base64,'
base64 -w 0 icon.png
printf '\\n'
On systems whose base64 command has no -w option, remove line breaks before inserting the result:
printf 'data:image/png;base64,'
base64 icon.png | tr -d '\\n'
printf '\\n'
When data URLs make sense
- Small icons or self-contained HTML documents.
- Email or an offline artifact where a separate request is undesirable.
- A generated document that must carry its assets in one file.
For ordinary site content, a separate image URL is easier to edit, cache, compress, and reuse. Embedding a large image makes the HTML much larger and repeats the bytes whenever the document is downloaded.
4. Use responsive image sources
For multiple resolutions, provide srcset and sizes so the browser can choose an appropriate resource:
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
sizes="(max-width: 600px) 100vw, 800px"
width="800"
height="600"
alt="A red bicycle leaning against a brick wall"
>
The width descriptors (400w, 800w) describe the files’ intrinsic widths. sizes tells the browser how wide the image will appear; it is not a CSS rule.
Offer a modern format with picture
<picture>
<source srcset="photo.webp" type="image/webp">
<img
src="photo.jpg"
width="800"
height="600"
alt="A red bicycle leaning against a brick wall"
>
</picture>
The img remains the fallback. Use picture when you need format or art-direction alternatives; use srcset when the same image is available at several resolutions. See the WHATWG HTML images specification, MDN’s img reference, and MDN’s picture reference.
5. Control loading and presentation
Lazy-load below-the-fold images
<img
src="gallery/photo.jpg"
width="1200"
height="800"
loading="lazy"
alt="Mountain trail at sunrise"
>
Do not lazy-load the main above-the-fold image by default; let it start downloading immediately.
Provide a decoding hint
<img src="photo.jpg" alt="Mountain trail at sunrise" decoding="async">
decoding is a hint, not a guarantee. Keep dimensions and sensible file sizes as the primary safeguards.
Prevent unwanted upscaling
.card-image {
width: 100%;
max-width: 800px;
height: auto;
object-fit: cover;
}
Use object-fit: cover only when cropping is intentional; otherwise use height: auto to preserve the complete image.
6. Capture an HTML page as an image
If your goal is to turn a finished HTML page into a PNG, JPEG, WebP, or PDF, a browser must render the page first. A headless browser can load the URL, wait for fonts and images, then save a screenshot.
Playwright with Node.js
import { chromium } from 'playwright';
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 800 } });
await page.goto('https://example.com', { waitUntil: 'networkidle' });
await page.screenshot({ path: 'page.png', fullPage: true });
await browser.close();
For a single element, wait for it and capture that locator:
const card = page.locator('.product-card').first();
await card.waitFor({ state: 'visible' });
await card.screenshot({ path: 'product-card.png' });
Browser automation needs a runtime, browser binaries, timeouts, handling for consent banners, and a strategy for pages that never become idle. If you only need a reliable image from a URL, an API can remove that setup.
7. Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server. It accepts one GET request and returns a PNG, JPEG, WebP, or PDF. Before capture it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response reports the result in X-Page-Verdict and X-Billed headers.
See the ScreenshotNeo API documentation for all options, including full-page and element capture, device presets, dark mode, retina scale, custom CSS and JavaScript, clicks, waits, blocked resources, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, caching, signed links, asynchronous jobs, bulk capture, usage, and the OpenAPI specification.
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 bytes = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', bytes));
ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
8. Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Broken-image icon | Wrong relative path or filename case | Open the exact URL directly, check the page’s directory, and match case. |
| Image works locally but not online | Using a local computer path | Upload the file to a web-accessible host or embed it intentionally as a data URL. |
| Image has no accessible description | Missing or meaningless alt |
Describe the content or function; use alt="" for decoration. |
| Page jumps while loading | No intrinsic dimensions | Add accurate width and height attributes. |
| Data URL does not render | Wrong MIME type, truncated Base64, or inserted line breaks | Use the image’s actual type and complete Base64 output; remove unintended whitespace. |
| Image is cropped | CSS object-fit: cover or fixed height |
Use height: auto or adjust the crop deliberately. |
| Screenshot misses content | Capture occurred before lazy images or fonts loaded | Wait for a selector, a delay, or network idle before capture. |
| Automated capture times out | Third-party requests never settle | Set a bounded timeout, block unnecessary resource types, or use an API with verdict headers and caching. |
9. Performance, reliability, and cost
- Use separate files for reusable images. Browsers and CDNs can cache them independently, while data URLs enlarge every HTML response.
- Serve the smallest suitable variant. Combine
srcset,sizes, modern formats, and correct dimensions. - Reserve layout space. Accurate dimensions reduce cumulative movement and make pages feel stable.
- Cache generated screenshots. A stable cache key avoids repeating browser work. ScreenshotNeo lets you choose a cache TTL; cache hits are not billed.
- Inspect verdict headers. With ScreenshotNeo,
X-Page-VerdictandX-Billeddistinguish clean captures from bot checks, blank pages, timeouts, failed loads, and cache hits. - Control concurrency. For bulk jobs, use bounded parallelism and retries with backoff rather than launching unlimited browsers or requests.
10. FAQ
Can I use an image without an img tag?
For a normal HTML image resource, use img. CSS background-image is better for decorative backgrounds and does not provide the same text alternative.
Does Base64 improve image speed?
It can avoid a separate request for a small asset, but it also increases HTML size and prevents independent caching. Measure it for your page; do not use it automatically.
Should alt text include the image title?
Usually no. Write the useful visual content or action. Avoid repeating nearby text.
What is the safest way to show a remote image?
Use an HTTPS URL you control or trust, ensure the server returns the correct content type, and give the image dimensions and an appropriate alt.
Can I paste an image from my clipboard directly into HTML?
A clipboard image must first be saved or converted to bytes. Then reference the saved file with src or convert the bytes to a complete data URL.
Which source should I consult for the element rules?
The WHATWG HTML Living Standard defines the img and responsive-image behavior; MDN provides practical references for img and picture.


