ScreenshotNeo

BlogHow-to

How to Convert PNG Images to HTML

Learn how to put a PNG in HTML, embed it as Base64, use CSS backgrounds, export canvas images, and know when conversion is not possible.

By the ScreenshotNeo team1 October 20267 min read

Short answer: HTML does not turn PNG pixels into editable HTML elements. It displays the PNG as an image resource. For a normal page, reference the file with an <img> element:

<img src="images/example.png" alt="Describe the image" width="1200" height="800">

If the HTML must be completely self-contained, encode the PNG bytes as Base64 and use a data: URL. For decorative artwork, use CSS background-image. If you need editable shapes, you are asking for vectorization or manual reconstruction, not a normal PNG-to-HTML conversion.

What “convert PNG to HTML” can mean

The phrase usually describes one of four different jobs:

Need Use Trade-off
Show an image on a web page <img src> Simple, cacheable, and supports alternative text
Deliver one self-contained HTML file Base64 data URL Longer markup and image bytes stored as text
Use artwork as decoration CSS background-image Not the same content semantics as an HTML image
Make pixels editable shapes Rebuild or trace as SVG/HTML Requires suitable artwork or manual/vector work

The <img> element embeds an image; src or srcset identifies the resource, and alt supplies its textual replacement. See the MDN image element reference.

Method 1: Reference a PNG file with HTML

This is the standard solution when you control the website files.

  1. Put the PNG in your project, for example images/example.png.
  2. Use a relative or absolute URL in src.
  3. Write useful alternative text for meaningful images. Use alt="" for purely decorative images.
  4. Add the intrinsic width and height when known so the browser can reserve the correct aspect ratio before loading.
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>PNG example</title>
</head>
<body>
  <h1>Product diagram</h1>
  <img
    src="images/example.png"
    alt="Diagram showing the three stages of an image pipeline"
    width="1200"
    height="800"
  >
</body>
</html>

Relative, absolute, and responsive paths

<!-- Relative to the current HTML file -->
<img src="images/example.png" alt="Example diagram">

<!-- Root-relative on the same site -->
<img src="/assets/example.png" alt="Example diagram">

<!-- Complete URL -->
<img src="https://cdn.example.com/example.png" alt="Example diagram">

For responsive images, provide alternatives with srcset and let the browser select an appropriate resource:

<img
  src="images/example-1200.png"
  srcset="images/example-480.png 480w,
          images/example-800.png 800w,
          images/example-1200.png 1200w"
  sizes="(max-width: 600px) 100vw, 800px"
  alt="Example diagram"
  width="1200"
  height="800"
>

Method 2: Embed the PNG as Base64 in one HTML file

A data URL has the form data:[media-type][;base64],data. For a PNG, the prefix is data:image/png;base64,. The bytes remain PNG data; they are simply embedded inside HTML.

Generate the value on the command line

base64 -w 0 images/example.png > example.b64

On systems whose base64 does not support -w, remove line breaks before inserting the value:

base64 images/example.png | tr -d '\n' > example.b64

Use the data URL in HTML

<img
  src="data:image/png;base64,PASTE_BASE64_DATA_HERE"
  alt="Example diagram"
  width="1200"
  height="800"
>

Keep the comma between the metadata and payload. Do not URL-encode arbitrary Base64 incorrectly or paste line breaks into a context that rejects them. Large data URLs make source files and in-memory strings much larger, so a normal file URL is usually easier to cache, inspect, and maintain.

Method 3: Use a PNG as a CSS background

Use a background when the image is presentation, such as a texture or decorative hero artwork. Content that conveys information should normally remain an HTML image with alternative text.

.hero {
  min-height: 24rem;
  background-image: url("images/hero.png");
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

/* The same idea with an inline data URL */
.hero-inline {
  background-image: url("data:image/png;base64,PASTE_BASE64_DATA_HERE");
}

Method 4: Put a PNG in a canvas and export it

Canvas is useful when JavaScript must draw or modify pixels. toDataURL() returns a data URL, PNG by default when no supported format is specified.

<canvas id="preview" width="1200" height="800"></canvas>
<script>
  const canvas = document.querySelector('#preview');
  const context = canvas.getContext('2d');
  const image = new Image();

  image.onload = () => {
    context.drawImage(image, 0, 0, canvas.width, canvas.height);
    const pngDataUrl = canvas.toDataURL('image/png');
    document.querySelector('#output').href = pngDataUrl;
  };

  image.src = 'images/example.png';
</script>
Download export

For larger output, prefer toBlob() and URL.createObjectURL(). This avoids materializing the entire image as one large in-memory string. MDN documents this recommendation in the canvas toDataURL() reference.

canvas.toBlob((blob) => {
  if (!blob) throw new Error('PNG encoding failed');
  const objectUrl = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = objectUrl;
  link.download = 'export.png';
  link.click();
  URL.revokeObjectURL(objectUrl);
}, 'image/png');

Canvas security errors

If you draw an image loaded from another origin without suitable CORS permission, the canvas may become not origin-clean. Reading it with toDataURL() or toBlob() can then throw a SecurityError. Serve the image from the same origin or configure the image server’s CORS policy before drawing it.

When SVG or editable HTML is the real goal

SVG describes drawing commands such as paths and shapes. It is a good fit for diagrams, icons, and artwork that can be represented as vectors. A photograph or detailed raster illustration generally cannot be converted into faithful, editable HTML elements automatically. Embedding a PNG inside SVG still leaves the visual content as a bitmap. See MDN’s image format guide for the distinction.

Or skip the browser setup

If your goal is to capture a web page as a PNG, JPEG, WebP, or PDF rather than place an existing PNG in HTML, ScreenshotNeo provides a single HTTP request. The API can capture full pages or one CSS-selected element, wait for a selector, delay, or network idle, load lazy images, apply custom CSS or JavaScript, set device and viewport options, and return image or PDF output. See the ScreenshotNeo API documentation for all parameters.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Cookie and consent banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

Troubleshooting

Symptom Likely cause Fix
Broken image icon Wrong path, filename, or server URL Open the image URL directly, check case sensitivity, and inspect the browser network panel.
Image appears stretched Only one dimension is constrained or the declared dimensions are wrong Use the real intrinsic ratio; set one dimension to auto when resizing with CSS.
Alt text is missing alt was omitted Add a concise description, or use alt="" when decorative.
Base64 image does not render Missing comma, wrong media type, corrupted payload, or inserted line breaks Start with data:image/png;base64,, regenerate the value, and keep the payload intact.
Canvas export throws SecurityError Cross-origin pixels tainted the canvas Use same-origin assets or configure CORS before drawing.
HTML file is unexpectedly huge PNG was inlined as Base64 Use a normal asset URL, compress or resize the source, or use toBlob() for generated output.
CSS background has no accessible description Backgrounds do not provide image semantics Use <img> for meaningful content and reserve backgrounds for decoration.

Performance, reliability, and cost notes

  • Separate PNG files can be cached independently and keep HTML small.
  • Base64 is convenient for a small self-contained snippet, but every copy of the HTML carries the image bytes.
  • Declare width and height to reserve layout space and reduce layout shifts.
  • Use appropriately sized PNGs; do not send a multi-megapixel source when the rendered slot is small.
  • For canvas output, use toBlob() and object URLs for larger images, and revoke object URLs after use.
  • For ScreenshotNeo, choose caching with a TTL when repeated captures are acceptable, use wait conditions for dynamic pages, and inspect X-Page-Verdict and X-Billed to understand each response. Failed loads and cache hits cost nothing.

FAQ

Does converting PNG to HTML make the image editable?

No. HTML references or embeds the PNG. Editable geometry requires recreating the artwork as HTML/SVG or another drawing representation.

Is Base64 better than a normal image URL?

Only when self-containment is important. Otherwise, a separate PNG is usually easier to cache, debug, and maintain.

Can I put a PNG in an HTML email?

You can reference a hosted image or use a data URL, subject to the email client and message-size policies. Test the target clients before relying on embedded data.

What is the correct MIME prefix for a PNG data URL?

Use data:image/png;base64, followed by the Base64-encoded bytes.

Should a logo use alt text?

Yes when it communicates the organization or destination. If it is purely decorative beside an equivalent text label, an empty alt may be appropriate.