Image to Base64 Converter: The Complete Guide to Embedding Images in Code (2026)
Converting an image to a Base64 string is one of the most common tasks in web development — and one of the most commonly misapplied. Done right, it eliminates an HTTP request, simplifies distribution, and makes your code self-contained. Done wrong, it bloats your HTML, breaks browser caching, and slows page loads for every user.
This guide covers everything you need to know: how Base64 encoding works, what a data URI actually is, exactly when inlining images is a good idea, and when it is actively harmful. You will find step-by-step instructions, real code examples for HTML, CSS, and JavaScript, a format reference table, and honest tradeoff analysis so you can make the right call for your use case.
What Is Base64 Image Encoding?
Base64 image encoding is the process of converting a binary image file — a PNG, JPEG, SVG, GIF, or WebP — into a string of printable ASCII characters. The result is a long sequence of letters, numbers, and symbols like iVBORw0KGgoAAAANSUhEUgAA... that represents the exact bytes of the original file.
Why would you do this? Image files are binary data. HTML, CSS, JavaScript, and JSON are text. Embedding raw binary bytes in a text document causes corruption: parsers interpret certain byte sequences as control characters, line endings, or end-of-string markers. Base64 solves this by replacing every byte with a character from a safe 64-character alphabet. The browser can then reverse the process to recover the exact original image.
The result of Base64-encoding an image is called a data URI — a self-contained URL that carries the image data directly instead of pointing to a server. A data URI for a small PNG icon looks like this:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==
That entire string — from data: to the last character — can be dropped into an img src attribute, a CSS background-image property, or a JSON field, and the browser will render it as an image with no server request.
Base64 encoding is not compression — the encoded string is larger than the original file, not smaller. It is not encryption — anyone can decode it instantly. It is purely a way to represent binary image data as text so it can live inside text-based documents and protocols.
How Base64 Encoding Works
The algorithm is elegantly simple. It works on raw bytes, which means it does not care whether the input is a JPEG, a PNG, an SVG, or any other file type. The process is identical regardless of format.
The Core Mechanism
A standard byte is 8 bits. Base64 regroups those bits into 6-bit chunks. Each 6-bit chunk maps to one of 64 characters. Because 8 and 6 share a least common multiple of 24, the algorithm processes input in groups of exactly 3 bytes (24 bits) and outputs exactly 4 Base64 characters (4 × 6 = 24 bits) per group.
The Base64 character set (defined in RFC 4648) maps the 64 possible 6-bit values to safe printable characters:
- Indices 0–25: uppercase letters
A–Z - Indices 26–51: lowercase letters
a–z - Indices 52–61: digits
0–9 - Index 62:
+ - Index 63:
/ - Padding:
=(not a value character — used to pad the output to a multiple of 4)
Padding and the = Character
When an image's byte count is not divisible by 3, the final group is incomplete. The encoder pads it to fill the 3-byte slot and appends = characters at the end of the output to signal how much padding was added. One = indicates one byte of padding; two == indicates two bytes. This is why Base64 strings often end with one or two equals signs.
For a concrete example: the 3-byte ASCII string Man encodes to TWFu — exactly 4 characters with no padding needed. The 2-byte string Ma becomes TWE=, and the 1-byte string M becomes TQ==.
The 33% Size Increase
Every 3 bytes of input become 4 output characters. That is a 4/3 ratio, which is a 33.3% size increase. A 150 KB JPEG becomes roughly 200 KB of Base64 text. For a full explanation with comparison numbers, see the Size Overhead section below.
Data URI Format: The Full Syntax
A data URI is a URL scheme defined in RFC 2397 that allows content to be embedded directly in a URL instead of fetched from a server. For images, the format is:
data:[<mediatype>][;base64],<data>
Breaking down each part:
data:— the URI scheme. This tells the browser (or any URL parser) that what follows is inline data, not a network address.[mediatype]— the MIME type of the content, such asimage/png,image/jpeg,image/svg+xml, orimage/webp. If omitted, it defaults totext/plain;charset=US-ASCII, which is wrong for images — always include the MIME type explicitly.;base64— a literal flag indicating that the data portion is Base64-encoded. If this flag is absent, the data is treated as URL-encoded text (percent-encoding). For binary formats like PNG and JPEG, the;base64flag is mandatory.,— a literal comma that separates the metadata from the data. This comma is required and must not be omitted.data— the Base64-encoded content of the file. For an image, this is the output of the encoding algorithm applied to the raw file bytes.
A complete data URI for a tiny 1×1 PNG looks like this:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==
And an inline SVG (which, because it is text-based, can also be URL-encoded instead of Base64-encoded):
data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCI+PC9zdmc+
One important nuance: data URIs do not support HTTP headers, so you cannot set Cache-Control, ETag, or Content-Encoding on a data URI. The resource is always "inline" and lives entirely within whatever document contains it — with all the caching implications described in the When NOT to Use section.
Convert Any Image to a Data URI in Seconds
Drop a PNG, JPG, SVG, GIF, or WebP into the SnapUtils Image to Base64 tool and get the complete data URI — ready to paste into your HTML, CSS, or JSON — instantly.
Open Image to Base64 ToolWhen to Use Base64 Images
Base64 image inlining is a legitimate technique that solves real problems — in specific, narrow circumstances. Here are the use cases where it is genuinely the right choice.
HTML Email Templates
Email is one of the strongest cases for Base64 images. Many corporate email security proxies and spam filters block or rewrite external image URLs, or simply strip <img> tags that reference remote servers. Embedding small images — logos, decorative icons, signature graphics — as Base64 data URIs in the HTML ensures they appear correctly without a separate network request that may be blocked. Note that some mail clients (particularly Gmail) do strip data URIs from <img src> attributes but honor them in inline CSS background-image properties. Test carefully across your target clients.
Standalone HTML Files and Offline Apps
If you are creating a document or application that must work without a network connection — a downloaded report, a kiosk interface, a single-file HTML tool — Base64 images are the right approach. A self-contained HTML file with embedded images works identically whether opened from a file system, a USB drive, or a local web server. There is no remote dependency to fail.
Small Icons and UI Elements in CSS
For tiny SVG icons or small raster images used as CSS background images, inlining saves an HTTP round-trip with very little size cost. A 200-byte SVG checkmark icon becomes about 270 bytes of Base64 — the overhead is negligible, and you eliminate a network request that could fail or delay rendering. The practical threshold is roughly 4–8 KB: images below that size are good candidates for inlining; images above it should be served as separate files.
Image Thumbnails in JSON APIs
When an API needs to return a small image preview alongside other structured data — a user avatar thumbnail, a product photo at reduced dimensions, a map tile — encoding it as Base64 inside the JSON response is acceptable for small images. It avoids the need for the client to make a second HTTP request for the image. The key constraint is size: stay well under 10 KB of original image data, or the Base64 representation will dominate your JSON payload.
Preventing Mixed-Content Warnings
A page served over HTTPS that loads images from an HTTP origin triggers a mixed-content warning in modern browsers, which can cause images to be blocked entirely. If you cannot change the origin server, converting the image to a Base64 data URI and embedding it directly eliminates the external request and the mixed-content issue with it.
Critical Above-the-Fold Images
Inlining a hero image or logo as Base64 in your HTML can improve Largest Contentful Paint (LCP) metrics by making the image available immediately when the HTML is parsed, without waiting for a separate fetch. This is a performance optimization worth considering for a single critical image, but it trades cacheability for speed. Measure both scenarios before committing.
When NOT to Use Base64 Images
Most Base64 image antipatterns share a common root cause: inlining images that are too large, too numerous, or in a context where caching matters more than eliminating one HTTP request.
Large Images
The 33% size overhead compounds quickly. A 500 KB photograph becomes 667 KB of Base64 text. That text must be included in your HTML every time the page is served, parsed by the HTML parser (which is slower than the browser's native binary image decoder), and decoded back to binary before the image can be displayed. You have made everything worse: larger transfer, slower parsing, and you have prevented the browser from independently caching the image.
Images That Appear on Multiple Pages
A navigation logo, a site icon, or a background pattern that appears on every page of your site is an excellent candidate for browser caching. Serve it once as a separate file with aggressive Cache-Control headers, and returning visitors will never download it again. Inline it as Base64, and every page load — on every page — downloads the full encoded bytes as part of the HTML. You have eliminated caching as a tool entirely.
HTTP/2 and HTTP/3 Environments
The original performance argument for Base64 image inlining was: "saving an HTTP round-trip is worth the size overhead." That argument was largely valid under HTTP/1.1, where browsers limited concurrent connections per host and each new request paid a meaningful latency cost. Under HTTP/2 and HTTP/3, all resources share a single multiplexed connection. Parallel image requests have near-zero setup overhead. The arithmetic no longer favors inlining for performance reasons; the size penalty remains but the latency benefit has largely disappeared.
Dynamic Server-Rendered Pages
If your server renders HTML on each request and that HTML contains Base64 images, the server must include the full encoded image data in every response, every time. For high-traffic pages, this significantly increases response size and bandwidth cost. Separate image resources, by contrast, are cached by CDNs and browsers and cost you almost nothing after the first delivery.
Content Security Policy (CSP) Environments
Strict CSP configurations can block data URIs. The directive img-src 'self' does not allow data URIs; you must explicitly add data: to the allowed sources (img-src 'self' data:). In security-sensitive applications, allowing data: in your CSP is often not acceptable. Know your environment before choosing Base64 inlining.
Practical rule of thumb: Base64 image inlining is appropriate for images under roughly 4–8 KB that are used in email templates, standalone documents, or one-off CSS utilities. For anything else — especially images served to large numbers of users from a web server — link to a separate resource with proper caching headers.
How to Convert an Image to Base64 with SnapUtils
The SnapUtils Image to Base64 converter handles PNG, JPEG, GIF, WebP, and SVG files. It runs entirely in your browser — your image bytes never leave your device — and produces both the raw Base64 string and the complete data URI ready to paste into your code.
Here is the step-by-step process:
- Open the tool. Go to /image-to-base64. No login or signup is required.
- Load your image. Either click the upload area and select a file, or drag and drop your image directly onto the page. The tool accepts PNG, JPG/JPEG, GIF, WebP, and SVG files.
- Wait for encoding. For most images, encoding is instantaneous. Larger files may take a second or two — the encoding runs entirely in your browser using the Web File API.
- Copy the output. The tool displays two outputs: the raw Base64 string (just the encoded data, no prefix) and the complete data URI (including
data:[mimetype];base64,prefix). Copy whichever form your use case needs. Forimg srcand CSSbackground-image, copy the full data URI. For JSON fields or custom code that constructs the data URI separately, copy the raw Base64 string. - Paste and use. Drop the output directly into your code. Examples for every use case — HTML, CSS, JavaScript, JSON — are in the section below.
The tool also shows you the encoded file size so you can confirm whether inlining is worth the overhead for your image. If the Base64 size is over 8–10 KB, consider hosting the image as a separate file instead.
Using Base64 Images in HTML, CSS, and JavaScript
Embedding in HTML with <img>
Replace the src attribute value of any <img> tag with the full data URI. The browser treats it exactly like a URL — fetching from a CDN or embedding inline are transparent to the rendering engine.
<\!-- HTML: embed image directly in src -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..." alt="Embedded image" />
Always include a meaningful alt attribute. Accessibility requirements do not change because the image is inlined. If the image is decorative and carries no information, use an empty alt="" to signal that to screen readers.
Using Base64 in CSS background-image
The CSS url() function accepts data URIs anywhere a regular URL is accepted. This is particularly useful for icon sprites, pattern fills, and decorative elements that are part of the stylesheet rather than the HTML.
/* CSS: background image as Base64 */
.icon {
background-image: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0i...');
}
SVGs embedded in CSS background-image are particularly efficient because SVG is text-based XML. For simple icons, the Base64-encoded SVG is often only slightly larger than the original file. You can also skip Base64 entirely for SVGs and use URL-encoded SVG text — this avoids the 33% overhead for complex SVG files:
/* CSS: URL-encoded SVG (no Base64, no 33% overhead) */
.icon {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http%3A//www.w3.org/2000/svg' viewBox='0 0 24 24'%3E...%3C/svg%3E");
}
Converting an Image File to Base64 in JavaScript
The FileReader API is the standard way to convert a user-selected file to a Base64 data URI in the browser. This is what runs inside tools like the SnapUtils Image to Base64 converter.
// JavaScript: fetch image and convert to Base64 const toBase64 = (file) => new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result); reader.onerror = reject; });
The reader.result value is the complete data URI, including the data:[mimetype];base64, prefix. To get only the Base64 portion — for storing in a database or passing to a server — split on the comma:
// Extract just the Base64 portion (without the data URI prefix) const base64Only = dataUri.split(',')[1]; // Reconstruct a data URI from stored Base64 const reconstructed = `data:image/png;base64,${base64Only}`;
Using an Input Element for User File Selection
Combined with a file input, the FileReader pattern gives you a drag-and-drop or click-to-upload image encoder in about 15 lines:
<input type="file" id="img-upload" accept="image/*" /> <img id="preview" alt="Preview" /> <script> document.getElementById('img-upload').addEventListener('change', async (e) => { const file = e.target.files[0]; if (\!file) return; const dataUri = await toBase64(file); document.getElementById('preview').src = dataUri; // Or store the Base64 string for later use const base64 = dataUri.split(',')[1]; console.log(`Encoded ${file.name}: ${base64.length} characters`); }); </script>
Embedding Base64 Images in JSON
JSON strings can contain any Unicode text, so a Base64 string drops in as a plain string value. The data URI format is commonly used for image fields in API responses:
{
"user_id": "u_abc123",
"name": "Alex Kim",
"avatar": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/..."
}
When consuming such a response in JavaScript, the value can be used directly as an img src with no additional processing:
const data = await fetch('/api/user/profile').then(r => r.json()); document.getElementById('avatar').src = data.avatar; // works immediately
Base64 Image Size: The 33% Overhead Explained
The size increase from Base64 encoding is a direct consequence of the algorithm. Every 3 bytes of binary data become 4 ASCII characters. The ratio is 4/3, which is a 33.3% increase in character count.
There is also a small fixed overhead from the data URI prefix (data:image/png;base64, is about 22 characters), but for any image of meaningful size that prefix is negligible compared to the encoded data itself.
| Original File Size | Base64 Size | Overhead | Recommendation |
|---|---|---|---|
| 500 bytes | ~668 bytes | +168 bytes | Safe to inline |
| 2 KB | ~2.7 KB | +700 bytes | Safe to inline |
| 8 KB | ~10.7 KB | +2.7 KB | Acceptable for one-offs |
| 50 KB | ~66.7 KB | +16.7 KB | Consider separate file |
| 200 KB | ~267 KB | +67 KB | Use separate file |
| 1 MB | ~1.33 MB | +333 KB | Use separate file |
The size overhead has two compounding effects that the table does not capture:
Caching. A 200 KB image served as a separate file with Cache-Control: max-age=31536000 is downloaded once and cached for a year. Embedded as Base64 in your HTML, those 267 KB are transferred on every page load that is not itself cached — and HTML documents are usually not long-term cached because they change frequently.
Parsing overhead. Browsers process HTML as text. A long Base64 string in an img src attribute is part of the document text that the HTML parser must read before it can hand control to the binary image decoder. A separate image resource bypasses the HTML parser entirely and is processed by the dedicated image decoder on its own thread.
Compression partially mitigates the overhead: gzip and Brotli compress Base64-encoded data reasonably well because the alphabet is repetitive. In practice, a gzip-compressed Base64 image is roughly 20–25% larger than the original file rather than 33% — but it is still larger, and the other disadvantages remain.
Supported Image Formats and Their Base64 MIME Types
Every image format that browsers support can be Base64-encoded into a data URI. The MIME type in the data URI prefix tells the browser how to decode and render the image. Using the wrong MIME type will cause the image to fail silently or display as a broken image in some browsers.
| Format | MIME Type | Data URI Prefix | Notes |
|---|---|---|---|
| PNG | image/png |
data:image/png;base64, |
Lossless. Ideal for logos, icons, screenshots with text |
| JPEG / JPG | image/jpeg |
data:image/jpeg;base64, |
Lossy. Best for photos. Use image/jpeg even for .jpg files |
| GIF | image/gif |
data:image/gif;base64, |
Supports animation. Typically larger than WebP for the same content |
| WebP | image/webp |
data:image/webp;base64, |
Modern lossy/lossless. Smaller than JPEG/PNG at equivalent quality |
| SVG | image/svg+xml |
data:image/svg+xml;base64, |
Vector. Can also be URL-encoded without Base64 to avoid 33% overhead |
| AVIF | image/avif |
data:image/avif;base64, |
Next-gen format with excellent compression. Check browser support |
| ICO | image/x-icon |
data:image/x-icon;base64, |
Legacy favicon format. Prefer PNG or SVG for inline use |
A Note on SVG: Skip Base64 When Possible
SVG files are XML text, not binary data. This means they can be embedded in HTML directly as inline <svg> elements, or in CSS as URL-encoded strings without using Base64 at all. URL-encoded SVG avoids the 33% size overhead, though it produces a less readable string:
/* URL-encoded SVG — no Base64, no size overhead */ .icon-check { background-image: url("data:image/svg+xml,%3Csvg xmlns='http%3A//www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'%3E%3Cpath d='M13.5 2l-7.5 9-3.5-4-1.5 1.5 5 5.5 9-10.5z' fill='%2300e599'/%3E%3C/svg%3E"); } /* Base64-encoded SVG — same result, 33% larger, but more portable */ .icon-check { background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgdmlld0JveD0iMCAwIDE2IDE2Ij48cGF0aCBkPSJNMTMuNSAybC03LjUgOS0zLjUtNC0xLjUgMS41IDUgNS41IDktMTAuNXoiIGZpbGw9IiMwMGU1OTkiLz48L3N2Zz4="); }
Both produce identical results. Prefer URL-encoding for SVG in CSS to avoid the size overhead. Use Base64 for binary formats (PNG, JPEG, GIF, WebP) where URL-encoding is not practical.
Frequently Asked Questions
Does converting an image to Base64 reduce its quality?
No. Base64 encoding is completely lossless. The decoded bytes are byte-for-byte identical to the original file. Quality is determined by the source image format — a compressed JPEG stays a compressed JPEG, an uncompressed PNG stays uncompressed. Base64 is purely a transport encoding, not a compression or resampling operation. If you start with a 100 KB JPEG at 80% quality and encode it to Base64, decoding the Base64 will give you back the exact same 100 KB JPEG at exactly 80% quality.
How much larger is a Base64 image compared to the original?
A Base64-encoded image is approximately 33% larger than the original binary file. This is a direct consequence of the encoding algorithm: every 3 bytes of binary input become 4 ASCII characters of output (a 4/3 ratio). A 100 KB PNG becomes roughly 133 KB of Base64 text; a 500 KB JPEG becomes roughly 667 KB. HTTP compression (gzip or Brotli) can reduce this overhead somewhat in transit — compressed Base64 is typically about 20–25% larger than the original rather than 33% — but the stored size and the in-memory size remain fully inflated.
Can I use a Base64 image in an email template?
You can, but results vary by email client. Gmail strips Base64 data URIs from img src attributes as a security measure, which means your image will not appear. However, Base64 images in inline CSS background-image properties have somewhat better (though still inconsistent) support across clients. The most reliable approach for email images is to host them on a publicly accessible server and reference them by URL. If you must inline, test extensively across your target clients — Gmail, Outlook, Apple Mail, and the major mobile apps all handle data URIs differently.
What is the maximum size of a Base64 image that browsers can handle?
There is no hard browser-imposed limit on data URI length, but practical performance degrades quickly with size. Images under 4–8 KB are generally safe to inline as Base64. Images over 8 KB start to noticeably affect page parse time, memory usage, and — most importantly — cacheability. Anything over 50 KB should almost always be a separate file. Some older browsers had limits of around 32 KB or 64 KB on data URI length, but modern browsers (Chrome, Firefox, Safari, Edge) can handle much longer strings without erroring out. The limit you will actually hit is user experience degradation, not a browser hard cap.
Is it safe to embed Base64 images in JSON APIs?
Yes, for small images. Base64 produces a plain ASCII string that JSON handles without issue. A JSON field containing a Base64 image is technically indistinguishable from any other string field. The concern is payload size: a 500 KB image becomes roughly 667 KB of Base64 text inside your JSON response. This inflates transfer size, increases JSON parsing overhead on the client, consumes more memory, and prevents HTTP caching of the image independently. For anything larger than a small thumbnail (roughly 10–20 KB of original data), return an image URL rather than inline Base64. The client can then fetch the image separately with caching and parallel loading.
What MIME type should I use for SVG images in a data URI?
Use image/svg+xml as the MIME type: data:image/svg+xml;base64,[data]. Note that SVG is XML-based text, so you also have the option to skip Base64 entirely and embed the SVG as a URL-encoded string: data:image/svg+xml,[url-encoded-svg]. URL encoding avoids the 33% size overhead of Base64, though it results in a less readable string. For simple SVG icons, URL-encoded SVG in CSS is generally preferable. For complex SVGs with lots of special characters, Base64 tends to produce cleaner, more portable output. Both approaches are fully supported in modern browsers.
Ready to Convert Your Image?
The SnapUtils Image to Base64 converter works entirely in your browser — no uploads, no server, no data retention. Drop in a PNG, JPG, GIF, SVG, or WebP and get your data URI instantly.
Convert Image to Base64