The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →To convert an image URL to Base64, download the image bytes first, then encode those bytes. In browser JavaScript, use fetch(), convert the response to a Blob, and pass it to FileReader.readAsDataURL(). In Python or Node.js, read the response as bytes and encode them with Base64. Do not encode the URL text itself.
Your choice of method depends mainly on where the code runs and whether the image server permits browser access. Cross-origin browser requests require CORS permission; a server-side process can retrieve the image without that browser response-reading restriction, while still needing URL, timeout, size, and content checks.
What Base64 output should you produce?
There are two commonly confused forms:
- Data URL: a complete value such as
data:image/png;base64,iVBORw0.... It includes the media type, thebase64marker, and the encoded payload. - Raw Base64: only the encoded characters, without the
data:image/png;base64,declaration.
FileReader.readAsDataURL() returns a complete data URL. Keep the prefix when assigning the result to an HTML img element or another API that expects a data URL. Remove everything through the first comma only when the destination explicitly requires raw Base64:
const base64Only = dataUrl.slice(dataUrl.indexOf(",") + 1);
Python’s base64.b64encode() and Node.js’s Buffer methods return the raw encoded payload; add a media-type prefix yourself if a data URL is required.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
#1 Best Overall
Browser JavaScript: URL to a Base64 data URL
This function retrieves the image, checks the HTTP status, converts the body to a Blob, and asks FileReader for a data URL. The method and return form are documented by MDN’s readAsDataURL reference.
async function imageUrlToDataUrl(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Image request failed: ${response.status}`);
}
const blob = await response.blob();
return await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(blob);
});
}
const imageUrl = "https://example.com/photo.png";
const dataUrl = await imageUrlToDataUrl(imageUrl);
document.querySelector("img").src = dataUrl;
// Only if an API requires the payload without the declaration:
const base64Only = dataUrl.slice(dataUrl.indexOf(",") + 1);
How the browser flow works
fetch(url)makes the HTTP request.response.okrejects HTTP errors such as 404 or 500.response.blob()exposes the downloaded binary as aBlob.readAsDataURL(blob)produces the media type and Base64 payload together.
The browser’s default Fetch mode is cors. For an image on another origin, that server must return a suitable Access-Control-Allow-Origin response header before JavaScript can read the body. An image may still display in an <img> element while JavaScript is forbidden to inspect its bytes.
Why mode: "no-cors" does not fix it
no-cors creates an opaque response. Script cannot read its body or useful headers, so it cannot turn that response into Base64. If you do not control the image host, use a server-side retrieval endpoint you control, or ask the host to allow your origin. See MDN’s Fetch guide and the WHATWG Fetch Standard.
Python: download bytes and encode them
Python’s standard library keeps retrieval and encoding separate. urllib.request.urlopen() opens the URL, and base64.b64encode() accepts bytes-like input, as described in the Base64 documentation and urllib.request documentation.
import base64
from urllib.request import urlopen
image_url = "https://example.com/photo.png"
with urlopen(image_url, timeout=15) as response:
image_bytes = response.read()
base64_text = base64.b64encode(image_bytes).decode("ascii")
data_url = f"data:image/png;base64,{base64_text}"
print(base64_text) # raw Base64
print(data_url) # complete data URL
The example uses a PNG prefix because the example URL is a PNG. For other formats, use the response’s validated media type (for example, image/jpeg or image/webp) rather than assuming every image is PNG.
Saving the result to a file
from pathlib import Path
Path("image.base64.txt").write_text(base64_text, encoding="ascii")
Do not decode arbitrary user input into a data URL without checking what your consumer expects. A raw payload sent where a data URL is required will not render, and a data URL sent where raw Base64 is required may be rejected as malformed.
Rank #2
- HTML CSS Design and Build Web Sites
- Comes with secure packaging
- It can be a gift option
Node.js: fetch, ArrayBuffer, and Buffer
On current Node.js releases that provide the standard fetch, read the response as an ArrayBuffer and convert it to a Buffer:
const imageUrl = 'https://example.com/photo.png';
const response = await fetch(imageUrl);
if (!response.ok) {
throw new Error(`Image request failed: ${response.status}`);
}
const contentType = response.headers.get('content-type') || 'application/octet-stream';
const bytes = Buffer.from(await response.arrayBuffer());
const base64Only = bytes.toString('base64');
const dataUrl = `data:${contentType};base64,${base64Only}`;
console.log(base64Only);
console.log(dataUrl);
If your Node runtime does not provide global fetch, use an HTTP client supported by your project, then apply the same rule: obtain the binary bytes and call Buffer.toString('base64').
Command line with cURL
cURL can retrieve the binary file; a separate Base64 utility can encode it. GNU/Linux commonly provides base64:
curl --fail --location "https://example.com/photo.png" -o image.bin
base64 < image.bin > image.base64.txt
On systems where the command differs, use your platform’s Base64 encoder or one of the Python/Node.js examples. The output from this pipeline is raw Base64, not a data URL.
Browser versus server: which route fits?
| Question | Browser JavaScript | Server-side Python or Node.js |
|---|---|---|
| Where it runs | Inside the user’s browser | Your server, worker, or script |
| Cross-origin requirement | Image host must permit readable CORS responses | No browser same-origin restriction, but normal network errors still apply |
| Typical output | readAsDataURL() returns a data URL |
Raw Base64; construct a data URL when needed |
| Policy controls | Limited to browser security policy | You can enforce host allowlists, schemes, timeouts, size ceilings, and content validation |
Common failures and fixes
“TypeError: Failed to fetch” or a CORS console error
Cause: the image server did not grant your page permission to read the response, or the request failed before a response was available.
Fix: configure the image host’s CORS policy, proxy the request through a server you control, or perform the conversion server-side. Do not switch to no-cors; an opaque body cannot be encoded.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problemsRank #3
The image displays but conversion fails
Cause: browsers can display cross-origin images without exposing their bytes to script.
Fix: obtain a CORS-enabled response or move retrieval to a trusted backend.
HTTP 404, 403, or 500
Cause: the URL is wrong, access requires authentication, or the origin returned an error page.
Fix: check the URL and credentials, call response.ok (JavaScript/Node), and catch HTTPError or URLError in Python. Never Base64-encode an HTML error page as though it were an image.
The result is rejected as invalid Base64
Cause: you supplied a data URL where raw Base64 was required, or the reverse.
Fix: retain data:image/...;base64, for a data-URL consumer; strip that declaration only for a raw-payload consumer.
Rank #4
- Brand: Wiley
- Set of 2 Volumes
- A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers
Memory or request-size problems
Cause: Base64 is text containing the entire image, and data URLs duplicate the image in memory. Large values can exceed an API, database, browser, or header limit.
Fix: keep the original binary in object storage or upload it as a file when possible. Follow the destination’s documented limits; there is no universal safe maximum established by the references here.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Production safety for user-supplied URLs
A URL submitted by a user is untrusted input. Before fetching it in a service:
- Permit only schemes you intend to support, normally
https(andhttponly when explicitly needed). - Apply an allowlist or network-access policy so the fetcher cannot reach unintended internal services.
- Set connection and read timeouts and enforce a response-size ceiling before storing or encoding.
- Validate the final response’s media type and, where appropriate, inspect the file signature rather than trusting a filename or header.
- Limit redirects or re-check the destination after redirects according to your policy.
- Do not log complete data URLs if they may contain sensitive images.
These controls are application guidance, not universal numeric limits. Choose values that match your infrastructure and the destination API’s constraints.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Or skip the browser setup
If what you actually need is a clean image of a web page before converting it to Base64, ScreenshotNeo can return a PNG, JPEG, WebP, or PDF from one request. It accepts cookie and consent banners, removes more than 60 known consent platforms plus newsletter popups and chat widgets before capture, and reports whether a response was billed. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed. Its MCP server lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf.
Use the API response as the binary input to the Base64 code above. The complete API reference is at screenshotneo.com/docs/.
Recommended Free Tools
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
There is a free allowance of 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 screenshots; every feature is included on every plan. Sign up for the free ScreenshotNeo plan.
Best Value
FAQ
Does Base64 make an image smaller?
No. It is an encoding for transporting binary bytes as text and generally increases the representation’s size. Use it when the receiving format requires text, not as compression.
Can I convert an image URL without downloading the image?
No. Base64 represents the image bytes, so those bytes must be retrieved or otherwise supplied before encoding.
Can I use a Base64 data URL directly in CSS?
Yes, when the CSS property and destination support data URLs, use the complete data:image/...;base64,... value rather than the raw payload.
Frequently Asked Questions
Why is my Base64 string different each time?
Equivalent image bytes produce the same standard Base64 payload, but a changed source file, media-type prefix, line wrapping, or URL-safe alphabet can make the visible text differ.
Should I use standard or URL-safe Base64?
Use the alphabet required by your destination. Python documents both standard and URL-safe variants; do not substitute one for the other without checking the receiving API.
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.

