Image to Base64

Image to Base64 converter: choose or drop a PNG, JPEG, GIF, WebP, ICO or SVG and copy it as Base64, a data URI, an HTML img tag or a CSS background. The size before and after is shown. The file is read in your browser and never uploaded.

Image to Base64
or drop a file here. It is read in this browser and never uploaded.

How to convert an image to Base64

Choose an image file or drop it onto the box. The tool reads the file's bytes in your browser, detects the format from the signature at the start of the file, encodes the bytes in Base64 and shows the result in the format you selected. The count under the box gives the file size, the number of characters in the output and the increase over the original. Copy the text or save it as a file.

The format is detected from the content and not from the file name, so a PNG saved with a .jpg extension is still labeled image/png. This matters because the media type goes into the output, and browsers use it to decide how to draw the data. When no image signature is found the tool says so and uses the type your browser reports, so any file can be encoded.

The four output formats

The same bytes are useful in four shapes. The raw Base64 is what APIs and databases take. The data URI adds the prefix that a browser needs to treat it as a file. The HTML form is a complete image tag, and the CSS form is a ready declaration for a background. The table shows each, using the first eight bytes of a PNG as a short stand-in for a file.

One image, four outputs (the 8-byte PNG signature stands in for a file)
FormatOutput
Base64 onlyiVBORw0KGgo=
Data URIdata:image/png;base64,iVBORw0KGgo=
HTML img tag<img src="data:image/png;base64,iVBORw0KGgo=" alt="">
CSS backgroundbackground-image: url("data:image/png;base64,iVBORw0KGgo=");

The HTML output leaves alt empty on purpose, since the right description depends on the picture. Fill it in for images that carry meaning, and keep it empty for decoration. Add width and height as well, so the layout does not shift while the page loads.

When to inline an image as Base64, and when not to

Inlining removes a request and costs size. Both effects are real and their balance depends on the file. A small icon in a stylesheet saves a round trip that would otherwise delay rendering; a large photo in the same stylesheet delays the whole page, cannot be cached by itself and is a third larger. HTTP/2 and HTTP/3 make separate requests cheap, which weakens the main argument for inlining and leaves a narrow range where it pays.

Should this image be inlined?
SituationInline?Reason
Icon under about 2 KB used on every page, in the stylesheetUsually yesSaves a request, and the stylesheet is cached
Small image used once, above the foldSometimesAvoids a late-loading image; measure it
Photograph or any image over about 10 KBNoLarger by a third, not cached separately, delays the page
Image reused on many pagesNoA separate file is cached once
HTML emailOften noMany clients block data URIs; attach or link instead
Single-file HTML report or demoYesThe only way to make one self-contained file
API response that must carry the imageYes, if no URL is possibleJSON has no binary type

How much larger the Base64 is

The text is four thirds the size of the file, rounded up to a multiple of four characters, and a data URI adds the prefix, about 22 characters for a PNG. The table gives the output for typical image sizes. The last column is what the text weighs after a transport compression such as gzip, which for image data approaches the original file size, because the compressed bytes cannot be shrunk further and gzip only recovers the six-in-eight inefficiency of the text.

Base64 size for typical image files
File sizeBase64 charactersExtra charactersApprox. after gzip
1,000 B1,3363361,015 B
2,000 B2,6686682,028 B
5,000 B6,6681,6685,068 B
10,000 B13,3363,33610,135 B
50,000 B66,66816,66850,668 B
100,000 B133,33633,336101,335 B
1,000,000 B1,333,336333,3361,013,335 B

The gzip figure is an estimate: real results depend on the compressor and on how random the bytes are. It explains why inlined images in a gzipped stylesheet are less costly than the raw numbers suggest, and also why they never come out smaller than the file itself.

File size against Base64 size2000 bytes become 2668 characters; 10000 bytes become 13336 characters; 50000 bytes become 66668 characters; 250000 bytes become 333336 characters. The Base64 text is a third longer each time.fileBase642 KB2.7 KBfileBase6410 KB13.3 KBfileBase6450 KB66.7 KBfileBase64250 KB333.3 KB
Each pair: the file (outline) and its Base64 text (filled). The text is always one third longer than the file, whatever the size; the bars are scaled to the largest value.

Build tools that inline small images for you

Many projects never need the tool for routine icons, because the bundler decides at build time. Create React App inlined any image smaller than 10,000 bytes as a data URI by default. Vite does the same below 4 KiB (the assetsInlineLimit setting), and webpack's asset modules switch from a separate file to an inline data URI at 8 KB unless configured otherwise. Raising the limit trades a smaller number of requests for bigger bundles, and it is worth measuring rather than guessing.

Next.js uses the same idea for image placeholders: a blurred preview a few dozen pixels wide, encoded as Base64 and stored with the page, which is shown until the real image arrives. The tool is the manual version of those steps, useful for a single file, for a quick test or for a platform without a bundler, such as an email template, a README or a static HTML page.

A worked estimate: twelve small icons

Suppose a page uses twelve icons of 1,500 bytes each, loaded from separate files. That is 18,000 bytes and twelve requests. Inlined in the stylesheet as Base64, each icon is 2,000 characters, so the stylesheet grows by 24,000 characters. After gzip the growth falls to roughly the original 18,000 bytes, because the compressor recovers the Base64 overhead, and the twelve requests disappear. On HTTP/1.1 with a high-latency connection that is a clear gain. On HTTP/2 or HTTP/3 the requests were cheap in the first place, so the gain is small, and the cost is that the stylesheet is bigger and every icon change invalidates it.

Measure rather than assume: browser developer tools list the size and timing of every request, so the effect of a change is visible in a minute. The same arithmetic for a single 80 KB photograph gives a 107,000-character string that blocks the stylesheet and cannot be cached separately. This is the reasoning behind the thresholds in the table: inlining pays only for files so small that the request costs more than the file itself.

Which image format to encode

The format decides the size before Base64 adds its third, and the biggest saving comes from picking the right one. PNG is best for flat colors, icons and screenshots, and JPEG or WebP for photographs, where they are often a small fraction of the size of an equivalent PNG. GIF is limited to 256 colors and is rarely the best choice outside animation. ICO holds favicons.

SVG deserves separate mention. It is text, so Base64 turns it into a longer string than writing it directly. In a data URI the SVG can be written with percent-encoding for the few characters that need it, and the result is smaller and readable. A common pattern is data:image/svg+xml,%3Csvg … %3E with the angle brackets and # escaped. Use Base64 for SVG only when a tool or an API requires it.

Using the result in CSS, email and JSON

In CSS the declaration goes into a rule such as .logo { background-image: url("data:image/png;base64,…"); }. Put the long string in a stylesheet that is cached, not in an inline style attribute that is sent with every page. For a pseudo-element icon, or a list marker, a short data URI is often cleaner than a file.

HTML email is the least predictable target. Gmail, Outlook and several others block or strip data URI images, so the picture does not appear. The reliable ways are a linked image on a public URL or a MIME attachment referenced by Content-ID. In JSON, the Base64 goes into a string field. Send the bare Base64 and the media type separately where you can, as that keeps the payload clean. For the full syntax of the prefix, see RFC 2397.

Optimize the image before encoding

Encoding does not shrink anything, so shrink the file first. Resize the image to the size it is shown at: a 2000 pixel photo displayed at 200 pixels is a hundred times more data than needed. Re-save photographs as WebP or a JPEG at a sensible quality, and run PNG icons through an optimizer that reduces the palette. Strip metadata such as camera data, location and software tags, which can add tens of kilobytes and carry personal information.

The saving carries through to the Base64 at the same ratio, so a file that drops from 60 KB to 12 KB goes from 80,000 characters to 16,000. The numbers in the tool's status line let you see the effect immediately: encode, optimize the original, encode again and compare. To check an encoded string by looking at the picture it holds, paste it into Base64 to image.

Step by step: an icon in a stylesheet

Take a 16 by 16 pixel PNG icon of 300 bytes. Optimize it first, so it is as small as it can be. Choose it in the tool with the CSS background output and press Copy. The result is a declaration of about 400 characters, which goes into a rule that targets the element: a selector, the declaration, and the size and repeat properties that suit the icon, such as background-repeat: no-repeat and background-size: 16px 16px. Keep the long line in its own rule or file, so the rest of the stylesheet stays readable.

Check the result in the page. If the icon does not show, the usual causes are a missing quote around the URL, a line break introduced in the string by an editor, or a Content Security Policy without data: in img-src. If it shows blurred on a high-density screen, supply a 2x image at double the pixels and scale it down with background-size.

Step by step: a single-file HTML page

A page that must work as one file, for a report, an offline demo or an email attachment, is the clearest case for inlining. Put the styles in a style element and the scripts in a script element, and use the img output of the tool for each picture. Give each image width, height and alt as usual. The file becomes self-contained and can be opened from a disk or a mail client without any other file.

The cost is size and editing. Every image adds a third to its weight, and a page with several photographs reaches megabytes of text, which editors handle poorly. Keep images small (resize to the display size, use JPEG or WebP for photographs), and keep the long strings at the end of the file or in a script block, so the markup stays easy to read. If the page is going to be maintained, a build step that inlines the images from files is easier than pasting strings by hand.

Sending an image in a JSON API

APIs that take an image in JSON usually define a field for the Base64 and sometimes another for the media type and the file name, for example data, contentType and filename. Check whether the API wants the bare Base64 or the full data URI; sending the prefix to an endpoint that does not expect it is the commonest reason for a decode failure on the server. The tool's Base64-only output is the bare form.

Multipart form uploads move the same file with no growth in size and are the better choice when the API offers both. Base64 in JSON suits small files, such as avatars and signatures, and clients that cannot send multipart. The server should decode, check the signature against its allowed types, check the size and re-encode the image before storing or serving it, which also removes embedded metadata.

What is inside the file you encode

An image file carries more than pixels. JPEGs from phones and cameras contain EXIF data with the device, the time and often the GPS position. PNGs may hold text chunks, and editors add their name and settings. All of that is encoded into the Base64, and anyone who decodes the string can read it. Before encoding an image that will be published or sent to someone else, remove metadata with an image editor or a command-line tool, and prefer a version re-saved at its display size.

Re-saving an image in an editor often changes its metadata and its size without any visible difference, so test the effect on the encoded length. The tool does not alter the file. The decoded result is the same bytes you chose, metadata included, and that is deliberate: a converter that changed the image would be a different tool. If you need the original untouched, for example to compare a hash, encode it here and compare the decoded file with the source.

Favicons and fonts as data URIs

Two more file types are often inlined. A favicon can be written in the head of a page as a link element with a data URI in href, which stops the browser requesting /favicon.ico and keeps a single-file page self-contained. An icon of 16 or 32 pixels in PNG is a few hundred bytes, so the Base64 is short. Fonts go in as woff2 data inside an @font-face rule. That works, but a typical font file is tens of kilobytes, and putting it in the stylesheet means the stylesheet cannot finish loading before the font does, so inline only a subset with the characters you use.

Problems with inlined images and their causes

What goes wrong with Base64 images
ProblemLikely causeWhat to do
The page or stylesheet became very largePhotograph or screenshot inlinedUse a file, or shrink the image first
Image missing in emailThe client blocks data URIsAttach it with a Content-ID or link to a public URL
Image missing under a Content Security Policyimg-src does not allow data:Add data: to img-src, or serve the file
Broken image with a long stringLine break or a space inserted inside the attributeKeep the string on one line, or encode without MIME wrapping
Color or size differs from the originalThe image was re-encoded (canvas, editor) before encodingEncode the original file, not a re-saved one
Change of one icon invalidates the whole stylesheet cacheImage inside a shared CSS fileMove large or changing images out of the stylesheet
Search engines cannot index the imageNo image URL to crawlServe a file for images that should be found

Alternatives for small images

For simple graphics, other techniques avoid the encoding altogether. An SVG written inline in the page or as a symbol referenced with use costs only its own text, can be styled with CSS, and compresses well. CSS gradients, borders and shadows replace many decorative images. Icon fonts, once popular, have mostly given way to SVG. A CDN with HTTP/2 or HTTP/3 delivers dozens of small files without the old per-request cost, so the sprite sheets and inlining that were standard practice a decade ago matter much less.

In scripts, an image you have as bytes does not have to become a data URI at all: wrapping the bytes in a Blob and calling URL.createObjectURL gives a short blob: address without the one-third growth. That works only inside the page that created it, so it is no use for content that must be saved or sent, which is when Base64 is the tool.

Testing the result

Paste the output into the Base64 to image tool to confirm that it decodes to the picture you started with. The size and format should match the original file. In a page, check the Network panel of the browser: an inlined image shows up as a data: entry and no separate request. If the page is going to be seen by many people, compare the size of the HTML and CSS before and after, and run a quick speed test; the gain that inlining promises is easy to lose to a heavier file.

Privacy: the file stays on your device

The conversion uses the browser's File API. The browser gives the page the file's bytes, a script encodes them and the text appears on the page. No request carries the image or the result, so photographs and documents can be converted without being shared. You can verify it: open the browser's network panel, convert a file and no request appears, or disconnect from the network after the page loads and the tool still works.

The tool does not store the file either. It is held in memory while the page is open and released when you press Clear or close the tab. The same holds for every converter on this site, as the privacy policy states.

Image to Base64 in JavaScript, Python, PHP and the shell

JavaScript (browser)
const reader = new FileReader();
reader.onload = () => console.log(reader.result);      // 'data:image/png;base64,iVBORw0…'
reader.readAsDataURL(fileInput.files[0]);
Node.js and Python
require("fs").readFileSync("logo.png").toString("base64")

import base64
base64.b64encode(open("logo.png", "rb").read()).decode()
PHP, command line and PowerShell
base64_encode(file_get_contents("logo.png"));

base64 -w0 logo.png                    # GNU base64, one line; macOS: base64 -i logo.png
[Convert]::ToBase64String([IO.File]::ReadAllBytes("logo.png"))

Add the prefix yourself when using these: data:image/png;base64, followed by the string. The browser FileReader call returns it already, and canvas elements offer toDataURL for the same purpose, which also re-encodes the picture and therefore does change the bytes.

Questions about converting an image to Base64

What is the difference between Base64 and a data URI?

Base64 is the encoded text of the file bytes. A data URI wraps that text with a prefix, data:image/png;base64, that names the media type, which is what HTML and CSS need. The tool offers both, plus ready-made img and CSS lines.

Does converting an image to Base64 reduce its quality?

No. Base64 stores the file's exact bytes, so decoding returns the identical file. Any quality loss comes from the image format itself, for example when a JPEG was saved at a low setting before encoding.

Why is the Base64 text larger than my image?

Base64 writes three bytes as four characters, which makes the text about 33% larger than the file. The tool shows the exact numbers: the bytes in, the characters out and the percentage.

Is my image uploaded to a server?

No. The file is read in your browser with the File API, encoded there and shown on the page. Nothing is sent, and the tool works with the network disconnected once the page has loaded.

Which image types can I convert?

Any file. PNG, JPEG, GIF, WebP, BMP, ICO and SVG are recognized from their first bytes and given the matching media type. Other files are encoded too, with the type the browser reports, and the tool tells you that no image signature was found.