Blog / Tutorial

Convert Image to Base64: HTML, CSS & Code Examples

Convert any image or PNG to a Base64 data URI: embed inline in HTML, CSS, and email, weigh the size tradeoffs, and copy ready-to-use JavaScript and Python code.

BBestPNG··9 min read

You need to embed an image directly in your HTML, CSS, or API payload without hosting it as a separate file. Base64 encoding does exactly that — turning any image into a text string you can paste inline wherever text is accepted.

This guide covers what Base64 encoding is, how it works, the data URI scheme, how to embed Base64 images in HTML and CSS, the size and performance tradeoffs, and how to convert images with BestPNG — including code examples in JavaScript and Python.

What Is Base64 Encoding?

Base64 is a method of encoding binary data (like image files) as plain ASCII text. It takes the raw bytes of an image and converts them into a string built from a 64-character alphabet: A-Z, a-z, 0-9, +, and /, with = used for padding. The name "base64" refers to those 64 characters.

For example, a tiny 1x1 red pixel PNG becomes:

iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==

This string can be used directly in HTML or CSS without needing a separate image file or an HTTP request to load it.

How the Encoding Process Works

Under the hood, converting an image to Base64 is a simple transformation:

  1. The image file is read as raw binary data (a sequence of bytes)
  2. The bytes are grouped into chunks of 3 (24 bits)
  3. Each 24-bit chunk is split into four 6-bit groups
  4. Each 6-bit group maps to one of the 64 Base64 characters
  5. If the final chunk has fewer than 3 bytes, it's padded with = characters

Because every 3 bytes become 4 characters of text, the output is always about 33% larger than the original. The process is deterministic — the same image always produces the same string — and decoding reverses it exactly, with no loss.

The Data URI Scheme

Base64 on its own is just a string. To use it as an image in HTML or CSS, you wrap it in a data URI — a special URL format that embeds the data inline instead of pointing to an external file.

The format is:

data:[MIME-type];base64,[encoded-data]

For example:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB...

The MIME type tells the browser what kind of image to render. Common types:

FormatMIME Type
PNGimage/png
JPEGimage/jpeg
WebPimage/webp
GIFimage/gif
SVGimage/svg+xml

Embedding Base64 Images in HTML and CSS

Once you have a data URI, you can drop it anywhere text is accepted. Here are the contexts you'll use most.

In HTML (the <img> Tag)

The simplest use — replace the src URL with a data URI:

<!-- Regular image (external file) -->
<img src="/images/icon-check.png" alt="Checkmark" />

<!-- Base64 embedded image (inline) -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAA
AQCAYAAAAf8/9hAAAAM0lEQVR42mNk+M9Qz0BhwMRAYcBIbQMA..." alt="Checkmark" />

Everything else stays the same — alt text, width, height, CSS classes, and event handlers all work identically whether the source is a URL or a data URI.

In HTML Email (Inline Images)

Email templates are the most common use case for Base64 images. Many clients block external images by default and show a "Click to load images" prompt, but inline Base64 images display immediately.

<table>
  <tr>
    <td>
      <img src="data:image/png;base64,iVBORw0KGgo..."
           alt="Company Logo" width="200" height="50" />
    </td>
  </tr>
</table>

Important: Some clients (notably Outlook desktop) have limited support for Base64 images. Test across clients before deploying, and consider CID (Content-ID) attachments as a fallback.

In CSS (Background Image)

Base64 data URIs work anywhere you'd normally use url() in CSS:

/* Regular background image */
.icon-success {
  background-image: url('/images/check-green.svg');
}

/* Base64 embedded background */
.icon-success {
  background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0i
  aHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIg...);
}

This is especially useful for CSS-only icon systems, avoiding JavaScript sprite loading or extra HTTP requests.

In CSS Custom Properties

Store Base64 images in CSS custom properties (variables) for reuse:

:root {
  --icon-arrow: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0i...);
}

.button-next::after {
  content: '';
  background-image: var(--icon-arrow);
}

.link-external::after {
  content: '';
  background-image: var(--icon-arrow);
  transform: rotate(45deg);
}

As Cursor Images

Custom cursors can also use Base64:

.draggable {
  cursor: url(data:image/png;base64,iVBORw0KGgo...) 12 12, grab;
}

In API Requests (JSON Payload)

When sending images through JSON APIs (e.g., a small avatar or signature), Base64 lets you include the data as a text field without multipart form handling:

{
  "avatar": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg...",
  "name": "User"
}

In Markdown (Limited Support)

![alt text](data:image/png;base64,iVBORw0KGgo...)

Note: most Markdown platforms (GitHub, Reddit) block data URIs for security reasons, so this rarely works outside your own renderer.

SVG: A Special Case

SVG images can be inlined without Base64 encoding. Since SVG is already text-based (XML), you can URL-encode it instead:

/* Base64 SVG (works, but wasteful) */
background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0i...);

/* URL-encoded SVG (smaller, no decoding overhead) */
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'
  width='24' height='24'%3E%3Cpath d='M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4z'
  fill='%234CAF50'/%3E%3C/svg%3E");

For SVG, the URL-encoded version is typically 20-30% smaller than the Base64 version because it skips the binary-to-text encoding overhead.

When to Use Base64 Images

Base64 encoding makes sense in specific situations:

Good use cases:

  • Small icons and decorative elements (under 2-5 KB) — eliminates extra HTTP requests and improves perceived load time
  • Email templates — inline images display without the recipient needing to "load external images"
  • Single-file HTML documents — self-contained reports, invoices, or docs with no broken image links
  • API payloads — when an API expects image data as a text field rather than a file upload
  • CSS sprites replacement — small icons embedded directly in your stylesheet
  • Offline applications — storing images as text in databases or config files

Bad use cases:

  • Large images — the ~33% overhead makes big files even bigger
  • Frequently changing images — every change regenerates the string and invalidates the document cache
  • Images that benefit from caching — embedded Base64 can't be cached independently
  • Performance-critical pages — long strings inflate page size and delay parsing

The Size Tradeoff

Base64 encoding increases the data size by approximately 33%, because it represents every 3 bytes of binary data using 4 ASCII characters.

Original Image SizeBase64 String SizeIncrease
1 KB~1.37 KB+37%
5 KB~6.85 KB+37%
10 KB~13.7 KB+37%
50 KB~68.5 KB+37%
100 KB~137 KB+37%

Real-world overhead runs slightly above the theoretical 33% because the data:image/png;base64, prefix adds ~26 bytes, line breaks add more if the string is wrapped, and Base64 text doesn't gzip-compress as efficiently as a separately served binary file.

For a 2 KB icon, the overhead (about 740 bytes) is trivial and worth it to save an HTTP request. For a 500 KB photo, it adds ~185 KB of pure bloat to your HTML or CSS file.

Rule of thumb: Base64-encode images under 5 KB; host anything larger separately and reference it with a URL. On HTTP/2, the break-even point where a separate file wins is roughly 2-5 KB, and HTTP/3 shifts it lower still, since modern protocols handle many small requests efficiently.

How to Convert Images to Base64 with BestPNG

BestPNG's Base64 converter makes it simple to encode any image:

  1. Go to bestpng.com/tools/base64
  2. Upload your image (PNG, JPG, WebP, GIF, SVG, and more)
  3. The tool generates the Base64 string instantly
  4. Copy it — with or without the data: URI prefix

It outputs formats ready for HTML, CSS, or raw Base64, and shows both the original and Base64 sizes so you can see the overhead. Everything runs in your browser; your image is never uploaded to a server.

Practical Code Examples

Favicon as Base64

Instead of hosting a favicon file, embed it directly in your HTML head:

<link rel="icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUg..." />

JavaScript Conversion

If you need to convert images programmatically in the browser:

// Convert a File object to Base64
function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

// Usage
const base64String = await fileToBase64(imageFile);

Python Conversion

import base64

with open("image.png", "rb") as f:
    encoded = base64.b64encode(f.read()).decode("utf-8")

data_uri = f"data:image/png;base64,{encoded}"

Automating It with Build Tools

Modern build tools (Webpack, Vite, Rollup) can inline images below a size threshold automatically, so you never decide by hand:

// vite.config.js
export default {
  build: {
    assetsInlineLimit: 4096 // Inline files under 4 KB as Base64
  }
}

Small images become Base64; larger images stay as separate, cacheable files.

Converting Base64 Back to an Image

Sometimes you receive a Base64 string and need the original file back — extracting an image from HTML email source, an API response, or embedded data. BestPNG's Base64 tool works both directions:

  1. Go to bestpng.com/tools/base64
  2. Paste the Base64 data URI string
  3. The tool decodes it and shows a preview
  4. Download the reconstructed image file

Base64 vs File URL: When to Use Which

CriteriaBase64 InlineExternal File URL
HTTP requestsNone (embedded)1 per image
CachingCannot be cached separatelyBrowser caches independently
File size overhead+33%None
Best for sizeUnder 5 KBOver 5 KB
MaintenanceHarder to updateEasy to replace
SEONot indexed by image searchCan be indexed
Loading behaviorLoads with the documentLoads in parallel

Frequently Asked Questions

Does Base64 encoding change image quality?

No. Base64 is a lossless encoding, not compression. The decoded output is byte-for-byte identical to the original, so image quality is unchanged.

What image formats can be converted to Base64?

Any format — PNG, JPG, WebP, SVG, GIF, and more. The format is preserved inside the string via the MIME type in the data URI prefix.

Can I decode a Base64 string back to an image?

Yes. Base64 is fully reversible. Paste the string into BestPNG's Base64 tool and download the original file with no data loss.

Is Base64 encoding secure?

No. It's a reversible encoding, not encryption — anyone can decode it. Never use it to protect sensitive images, and be cautious rendering Base64 from untrusted sources, as it could contain malicious content.

Is there a size limit for Base64 images in browsers?

Modern browsers (Chrome, Firefox, Safari, Edge) handle data URIs of several megabytes, though performance degrades with very large strings. Internet Explorer 8 and earlier had a 32 KB limit.

Are Base64 images SEO-friendly?

Search engines can render Base64 images but can't independently crawl, index, or reverse-search them. For SEO-important images (product photos, infographics), always use regular <img> tags with external URLs and descriptive alt text.

Can I use Base64 for animated GIFs?

Yes, but GIFs are large, so the string is very long and rarely practical. For animated content, use a regular file URL or a modern format like WebP or AVIF.

How do I use Base64 images in React or Next.js?

In React, use the data URI directly in the src attribute, just like a regular URL:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUg..." alt="icon" />

In Next.js, the <Image> component needs the unoptimized prop for data URIs, since image optimization doesn't apply to inline Base64.

Conclusion

Base64 encoding is a targeted technique for embedding small images in HTML, CSS, or API payloads. It eliminates extra HTTP requests and creates self-contained documents, but adds roughly 33% to the data size.

Keep it simple: encode small icons and decorative images under 5 KB, and use regular file URLs for anything larger.

Convert images to Base64 free →

Selling on Amazon, Shopify or Etsy?

Turn your product photos into studio-grade shots — white-background main images, model try-on, full listing suites. 5 free generations.

Try AI Product Photos →

Continue reading

Product
PhotoRoom Alternatives: 9 Product Photo Tools Compared
10 min read
Tutorial
Watermark Maker — Custom Watermarks for Photographers
7 min read
Tutorial
AI Prompts for Product Photos: ChatGPT, Amazon & Flux
10 min read