Encode the JPG file’s binary bytes as Base64, then add the JPEG data URL prefix data:image/jpeg;base64,. Put the complete value in an image element’s src attribute:
<img src="data:image/jpeg;base64,PASTE_BASE64_TEXT_HERE" alt="Description of image">
The prefix and comma are required; replace the placeholder with the encoded text. For large images or pages with many images, use a regular image file URL instead of embedding a long data URL. RFC 2397 describes data URLs as suited to short values and notes that applications may impose length limits, but it does not set one universal modern browser limit.
What you need to convert
Start with the actual JPG or JPEG file. Base64 is a text representation of the file’s bytes; it is not an image URL by itself. After encoding, prepend data:image/jpeg;base64, and use the whole string as the image source. For JPEGs, image/jpeg is the appropriate media type, as described in MDN’s data URL reference.
Keep the distinction between the three parts clear:
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11#1 Best Overall
- Data URL scheme:
data: - Media type and encoding marker:
image/jpeg;base64 - Separator and encoded data: a comma followed immediately by the Base64 text
RFC 2397 gives the general pattern as data:[<mediatype>][;base64],<data> and demonstrates an inline image in HTML. The comma is part of the URL, not part of the encoded file data. RFC 2397
Convert a JPG with JavaScript in a browser
If the image is on your computer and you want to create the data URL without uploading it to a conversion site, a file input and FileReader can read it in the browser. Save this as an HTML file and open it in a browser. Choose a JPG; the page displays it and puts its complete data URL in the text area, ready to copy.
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>JPG to Base64 data URL</title>
<label for="image-file">Choose a JPG image</label>
<input id="image-file" type="file" accept="image/jpeg,.jpg,.jpeg">
<p id="status" role="status">Choose a file to convert.</p>
<img id="preview" alt="Selected image preview" style="max-width: 100%; display: none;">
<label for="output">Complete JPEG data URL</label>
<textarea id="output" rows="8" style="width: 100%;" readonly></textarea>
<script>
const input = document.querySelector("#image-file");
const output = document.querySelector("#output");
const preview = document.querySelector("#preview");
const status = document.querySelector("#status");
input.addEventListener("change", () => {
const file = input.files[0];
output.value = "";
preview.removeAttribute("src");
preview.style.display = "none";
if (!file) {
status.textContent = "Choose a file to convert.";
return;
}
if (file.type !== "image/jpeg") {
status.textContent = "This file is not identified by the browser as a JPEG.";
return;
}
const reader = new FileReader();
reader.addEventListener("load", () => {
if (typeof reader.result !== "string") {
status.textContent = "The file could not be read as a data URL.";
return;
}
output.value = reader.result;
preview.src = reader.result;
preview.style.display = "block";
status.textContent = "Conversion complete. Copy the full value, including its prefix.";
});
reader.addEventListener("error", () => {
status.textContent = "The browser could not read this file.";
});
reader.readAsDataURL(file);
});
</script>
</html>
What the browser code returns
readAsDataURL() returns the prefix and encoded data together. Copy the entire contents of the text area, beginning with data:image/jpeg;base64,. Do not prepend a second prefix. The preview is a useful check: if it displays, the value can be used directly as an image source in HTML.
The file input’s accept value helps users select JPEG files, and the code checks the browser-reported media type before reading. That check is a convenience, not proof that a file’s contents are a valid JPEG; if a file is mislabeled or damaged, test the resulting image in the target browser.
Rank #2
- HTML CSS Design and Build Web Sites
- Comes with secure packaging
- It can be a gift option
Encode a local file with Python
For a build script or other local workflow, Python’s standard library can read the file as bytes, encode those bytes, and assemble the data URL. Save as jpg_to_data_url.py, change the input path, and run python jpg_to_data_url.py (or use the Python command installed on your system).
from base64 import b64encode
from pathlib import Path
image_path = Path("photo.jpg")
image_bytes = image_path.read_bytes()
encoded = b64encode(image_bytes).decode("ascii")
data_url = f"data:image/jpeg;base64,{encoded}"
Path("photo-data-url.txt").write_text(data_url, encoding="ascii")
print(f"Wrote data URL for {image_path} to photo-data-url.txt")
The output text file contains the complete value, including the prefix. You can paste that value into an HTML src attribute or generate markup in your application. Do not treat the contents of the text file as an image file: it is text representing an inline image URL.
Encode a local file with Node.js
Node.js can read the file into a buffer and convert the bytes to Base64. Save this as jpg-to-data-url.js, put photo.jpg alongside it, and run node jpg-to-data-url.js.
const fs = require("node:fs");
const imageBytes = fs.readFileSync("photo.jpg");
const encoded = imageBytes.toString("base64");
const dataUrl = `data:image/jpeg;base64,${encoded}`;
fs.writeFileSync("photo-data-url.txt", dataUrl, "ascii");
console.log("Wrote photo-data-url.txt");
For a file with a different name or location, update the path passed to readFileSync. Both examples deliberately encode the original file bytes rather than decode the image and re-encode it through a canvas.
Rank #3
Put the value in HTML
Once you have the full data URL, assign it to src. Use a meaningful alt value for the image’s purpose:
<img
src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ..."
alt="A red bicycle leaning against a brick wall"
>
The shortened sample above illustrates the location only; its ellipsis is not valid Base64. In your page, replace it with the entire data URL produced by your encoder. Keep the value inside the quotes and do not insert explanatory text, additional quotation marks, or line breaks into it.
If you are assembling the markup programmatically, assign the value as a string rather than trying to parse the encoded text as HTML. For example, a JavaScript-created image can use img.src = dataUrl; the same complete URL can be used as a CSS image value when appropriate. In a static HTML file, ensure the generated text is not truncated by an editor, templating step, or database field before relying on the image.
Choose between a data URL and a separate image file
An inline data URL can be convenient for a short, one-off image that belongs directly in a document. It avoids a separate image path in the markup, but it also makes the HTML value large and embeds the image data in the page. The format is not a universal improvement over an ordinary file URL.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Rank #4
| Use a data URL when… | Use a separate image URL when… |
|---|---|
| The inline value is short and the image is a one-off part of the document. | The JPG is large, the page has many images, or the image should be cached and reused separately. |
| You specifically need the image bytes represented inside the HTML value. | You want to keep the HTML smaller and refer to an image asset by its normal URL. |
| You have checked that the target application accepts the resulting data URL. | The consuming application imposes a length limit or handles data URLs differently. |
RFC 2397 describes the scheme as useful for short values, says larger data URLs are likely to be inappropriate, and notes that applications may impose length limits. It does not define one current size cutoff that applies to every browser or application, so do not rely on a purported universal maximum. RFC 2397
For a large JPG, a page with many inline images, or an image you want to share and cache independently, keep the image as a separate file and use its normal URL. If you choose Base64, check the actual HTML size and test it in the browser and context where it will be used.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Canvas is useful, but it does not preserve the original file
If an image has already been loaded into a browser canvas and your goal is to export the canvas content, HTMLCanvasElement.toDataURL() can produce a data URL. That is different from encoding the original file: canvas serializes the pixels in the canvas, so its output represents canvas content rather than guaranteeing the original file’s bytes or encoding. Apple’s documentation describes the MIME-type argument and notes format-support caveats for JPEG output. Apple Developer Documentation: toDataURL()
Use direct byte-to-Base64 conversion when you need to embed the original JPG data. Use canvas export when you intentionally want a canvas image output, and verify the returned format in the browser you target; requesting JPEG does not remove the need to account for browser support.
Free tools Windows power users keep installed
One-click scans. No signup required.
Best Value
Troubleshooting
- The image does not render: Check that the value starts exactly with
data:image/jpeg;base64,, includes the comma, and contains the full output rather than a truncated copy. Confirm thatsrccontains the entire value and that the browser console does not report an issue. - The source begins with Base64 text but not
data:: Add the complete prefixdata:image/jpeg;base64,. Plain Base64 characters alone are not the complete HTML image URL. - The wrong media type is specified: For a JPEG, use
image/jpeg. A filename ending in.jpgor.jpegdoes not change the required media type in the data URL. MDN’s data URL reference - The browser says the file is not a JPEG: Check that you selected the intended file and that it is actually a JPEG, rather than relying only on its extension. The browser example checks the reported MIME type and stops if it is not
image/jpeg. - The encoded text was altered when copied: Copy the whole value from its beginning through its final Base64 character. Remove any placeholder text or ellipsis used in an example, and do not add spaces or explanatory punctuation.
- The page or consuming tool rejects the value: The HTML may be valid while the target application imposes its own data URL or input-length limit. RFC 2397 acknowledges application limits but does not give a universal present-day browser threshold; use a separate image URL when the inline value is too large. RFC 2397
- A canvas export is not an exact copy: That is expected when you are exporting canvas content. Use file-byte conversion instead if the task requires the original JPG rather than a serialized rendering. Apple Developer Documentation: toDataURL()
Or skip the browser setup
If your actual goal is to capture a webpage as an image rather than convert a JPG you already have, ScreenshotNeo is a website screenshot API and MCP server. One GET request returns a screenshot or PDF; for an image response, save the returned bytes as an image file. This is a different task from Base64-encoding a local JPG.
For example, save a webpage screenshot as WebP with cURL:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo documentation for API details. Its capture options include PNG, JPEG or WebP output; it can accept cookie and consent banners before capture and remove 60+ known consent platforms, newsletter popups and chat widgets, with each step switchable. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits cost nothing, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info and capture_pdf tools for AI agents and MCP clients.
The Free plan includes 1,000 shots a month with no card; paid plans start at $5 for 3,000 shots. Every feature is on every plan. Sign up for ScreenshotNeo free: 1,000 screenshots a month, no card required.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteQuick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




