To display a JPG inline in HTML, encode the image’s bytes as Base64, prepend data:image/jpeg;base64,, and put the complete data URL in an <img> element’s src attribute. The prefix and comma are required; Base64 text by itself is not an image URL.
What the HTML image value needs
A JPEG data URL has three parts: the data: scheme, the media type and Base64 indicator, and the encoded image data. For a JPG or JPEG, the prefix is data:image/jpeg;base64,. The comma separates that prefix from the Base64 text.
<img src="data:image/jpeg;base64,PASTE_BASE64_TEXT_HERE" alt="Description of image">
Replace PASTE_BASE64_TEXT_HERE with the encoded bytes, keeping the prefix, comma, and surrounding HTML quotes. Do not add another pair of quotation marks around the Base64 text inside the attribute. RFC 2397 defines the general data URL form and demonstrates using one for an inline HTML image: RFC 2397, “The ‘data’ URL scheme”. The JPEG media type is image/jpeg, as identified in MDN’s Data URLs reference.
Convert a JPG in the browser
This option uses a file picker and the browser’s FileReader API. It produces a data URL from the selected file, then displays it in an image element. The page does not need to upload the selected file to a server for this conversion.
PC 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 & 11Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware match#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
-
Save the following as
jpg-to-base64.htmland open it in a browser. -
Select a JPG or JPEG file.
-
Copy the complete value shown in the text area if you need to paste it into another HTML document.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>JPG to Base64 data URL</title>
</head>
<body>
<label for="jpg-file">Choose a JPG or JPEG image:</label>
<input id="jpg-file" type="file" accept="image/jpeg,.jpg,.jpeg">
<p id="status" role="status"></p>
<textarea id="data-url" rows="8" cols="80" readonly
aria-label="Complete JPEG data URL"></textarea>
<img id="preview" alt="Selected JPEG preview">
<script>
const picker = document.querySelector('#jpg-file');
const output = document.querySelector('#data-url');
const preview = document.querySelector('#preview');
const status = document.querySelector('#status');
picker.addEventListener('change', () => {
const file = picker.files[0];
output.value = '';
preview.removeAttribute('src');
if (!file) {
status.textContent = 'Choose an image file.';
return;
}
if (file.type !== 'image/jpeg') {
status.textContent = 'The selected file is not identified as a JPEG.';
return;
}
const reader = new FileReader();
reader.addEventListener('load', () => {
if (typeof reader.result !== 'string') {
status.textContent = 'The browser did not return a data URL.';
return;
}
output.value = reader.result;
preview.src = reader.result;
status.textContent = 'JPEG data URL created.';
});
reader.addEventListener('error', () => {
status.textContent = 'The file could not be read.';
});
reader.readAsDataURL(file);
});
</script>
</body>
</html>
readAsDataURL() returns the complete string, including the prefix and comma, so do not prepend a second prefix to its result. The file input’s accept value helps narrow the picker, but the example also checks the browser-reported MIME type before reading the file. File extensions and MIME labels are not a substitute for verifying that the value actually renders as an image.
Convert a JPG with Python
For a local script or build step, Python’s standard library can encode the file bytes without changing the image. Save this as jpg_to_data_url.py, then run it with the input and output paths as arguments. It writes a small HTML file containing the image and a data URL.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
from base64 import b64encode
from pathlib import Path
import sys
if len(sys.argv) != 3:
raise SystemExit("Usage: python jpg_to_data_url.py input.jpg output.html")
image_path = Path(sys.argv[1])
output_path = Path(sys.argv[2])
image_bytes = image_path.read_bytes()
encoded = b64encode(image_bytes).decode("ascii")
data_url = f"data:image/jpeg;base64,{encoded}"
html = (
'<!doctype html>n'
'<html lang="en">n'
'<meta charset="utf-8">n'
'<title>Inline JPEG</title>n'
f'<img src="{data_url}" alt="Image from {image_path.name}">n'
'</html>n'
)
output_path.write_text(html, encoding="utf-8")
print(f"Wrote {output_path}")
Run it with python jpg_to_data_url.py photo.jpg inline-image.html. The script reads the original bytes, encodes them, decodes the Base64 result as ASCII for HTML text, and adds the JPEG data URL prefix. If you only need the Base64 text rather than an HTML file, print or save encoded instead of constructing data_url.
Convert a JPG with Node.js
Node.js can do the same byte-for-byte encoding with its built-in Buffer. Save as jpg-to-data-url.js and run node jpg-to-data-url.js photo.jpg inline-image.html.
const fs = require('node:fs');
const [inputPath, outputPath] = process.argv.slice(2);
if (!inputPath || !outputPath) {
console.error('Usage: node jpg-to-data-url.js input.jpg output.html');
process.exit(1);
}
const imageBytes = fs.readFileSync(inputPath);
const encoded = imageBytes.toString('base64');
const dataUrl = `data:image/jpeg;base64,${encoded}`;
const html = `<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Inline JPEG</title>
<img src="${dataUrl}" alt="Image from ${inputPath}">
</html>
`;
fs.writeFileSync(outputPath, html, 'utf8');
console.log(`Wrote ${outputPath}`);
Both command-line examples encode the file bytes rather than rendering and re-encoding the image. That is useful when the goal is to embed the existing JPEG as-is. If your input is actually a PNG or another format, use its real MIME type instead of labeling it image/jpeg.
When a canvas data URL is appropriate
If an image is already loaded into a browser canvas and you want a data URL for the canvas content, call HTMLCanvasElement.toDataURL() with a JPEG MIME type:
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
const canvas = document.querySelector('canvas');
const jpegDataUrl = canvas.toDataURL('image/jpeg');
This is not the same operation as Base64-encoding the original file. Canvas serialization represents the canvas content, so it may not preserve the original file’s bytes or exact encoding. Apple’s documentation describes the MIME-type argument and notes format-support caveats for JPEG output: HTMLCanvasElement.toDataURL(). Use direct byte encoding when the original JPG is what you intend to embed; use canvas when you need the canvas result.
Or skip the browser setup
If your task is to capture a webpage as an image or PDF rather than convert an existing JPG, ScreenshotNeo is a separate option: it takes a webpage URL and returns a screenshot or PDF. For example, save a webpage screenshot as WebP with one GET request:
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 API documentation for request options. It can remove cookie/consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are not billed; and its MCP server lets AI agents take screenshots. The Free plan includes 1,000 screenshots a month with no card, and paid plans start at $5 for 3,000. Sign up for 1,000 free screenshots a month with no card.
Check the result and avoid common mistakes
-
The image icon appears instead of the image: Check that the string starts with
data:image/jpeg;base64,, includes the comma, and has no extra characters inserted into the Base64 portion. Copy the complete data URL, not just its encoded tail.The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy. -
The string is rejected or does not render: Confirm the image really is a JPEG and the media type is
image/jpeg. A file named.jpgis not enough to establish its actual format. A different format needs its matching media type.Rank #4
SaleUGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
-
The browser-side example reports a non-JPEG: The browser may report an empty or different file MIME type. The sample deliberately stops rather than labeling unknown content as JPEG. If you know the file is a JPEG, use the Python or Node.js byte-encoding method and ensure the supplied file is the intended image.
-
The selected file cannot be read: Try selecting it again and verify that it is accessible and not damaged. The browser example reports read failures through its status message.
-
The HTML page becomes unwieldy or slow to work with: A data URL places the image data directly in the HTML value. RFC 2397 describes data URLs as useful for short values and notes that applications may impose length limits; it does not define one current, universal browser threshold. For a large JPG, many images, or an image that should be reused and cached separately, use a normal image file URL instead.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Choose between inline data and a separate image file
| Use a JPEG data URL | Use a separate image URL |
|---|---|
| A short, one-off image belongs directly in the HTML and embedding it is useful for the page’s purpose. | The image is large, there are many images, or the same image should be reused separately. |
| You want the HTML document itself to contain the image data. | You want an image file with its own URL rather than a long value embedded in markup. |
You have correctly identified the source as JPEG and use image/jpeg. |
The source format is not JPEG, or the content should remain a distinct image resource. |
Base64 is text encoding, not image compression. It makes binary bytes representable as text but does not make the JPEG smaller; the resulting data URL also carries its prefix and is embedded in the document. Since the RFC cautions that larger data URLs may be inappropriate and gives no universal current browser limit, decide based on the image size and whether inline embedding is actually useful rather than relying on a supposedly safe fixed cutoff.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Final verification
-
Check that the source is a JPEG, not merely a file with a JPG extension.
-
Check that the value begins with
data:image/jpeg;base64,and contains the encoded output after the comma. -
Paste the entire value into a quoted
srcattribute and provide meaningful alternative text.Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy. -
Open the page in the target browser and confirm the image loads. If it does not, compare against the original file and regenerate the data URL rather than altering the encoded string by hand.
Frequently Asked Questions
Should the MIME type be written as image/jpg?
No. For a JPEG data URL, use the media type image/jpeg.
Can I use Base64 text in a CSS background instead of an img element?
A data URL can be used in other URL-valued contexts, but this guide’s examples use the complete URL in an img element’s src. Use an img element when the image is content and needs alternative text.
Quick 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.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.

