ddp_utils.base64

import ddp_utils.base64

Base64 bytes/text conversion, file helpers and image data URIs.

Supports standard and URL-safe alphabets. Encoding is not encryption.

Examples

Use this public operation:

import ddp_utils.base64
ddp_utils.base64.encode_bytes(data: bytes, url_safe: bool = False) → str

Encode bytes as an ASCII Base64 string, retaining padding.

Parameters

Name

Type

Description

data

bytes

Bytes-like input accepted by the standard library encoder.

url_safe

bool

True uses ‘-’ and ‘_’ instead of ‘+’ and ‘/’.

Returns

Type

Description

str

ASCII string, or an empty string for empty bytes.

Examples

Use this public operation:

result = ddp_utils.base64.encode_bytes(data=data_value)
ddp_utils.base64.decode_bytes(data: str, url_safe: bool = False) → bytes

Decode Base64 with the standard library’s permissive decoder.

Validation is not strict: some non-alphabet characters are discarded. Padding is not automatically repaired. Do not use this as an input validator.

Parameters

Name

Type

Description

data

str

Base64 ASCII string (bytes-like values are also accepted by the decoder).

url_safe

bool

True enables the URL-safe alphabet.

Returns

Type

Description

bytes

Decoded bytes, possibly empty even for some malformed input.

Raises

Exception

Description

ValueError

A decoder exception occurs, such as invalid padding or non-ASCII text.

Examples

Use this public operation:

result = ddp_utils.base64.decode_bytes(data=data_value)
ddp_utils.base64.encode_string(text: str, encoding: str = 'utf-8', url_safe: bool = False) → str

Encode text to bytes with the selected codec, then encode those bytes as Base64.

Parameters

Name

Type

Description

text

str

Source string; an empty string produces an empty string.

encoding

str

Python text codec, default ‘utf-8’; errors are not suppressed.

url_safe

bool

True selects the URL-safe alphabet while retaining padding.

Returns

Type

Description

str

ASCII Base64 string.

Raises

Exception

Description

LookupError

The codec name is unknown.

UnicodeEncodeError

The text cannot be represented by the codec.

Examples

Use this public operation:

result = ddp_utils.base64.encode_string(text=text_value)
ddp_utils.base64.decode_string(data: str, encoding: str = 'utf-8', url_safe: bool = False) → str

Decode Base64 bytes and then decode text with the selected codec.

Parameters

Name

Type

Description

data

str

Base64 string decoded using decode_bytes’ permissive rules.

encoding

str

Python text codec, default ‘utf-8’.

url_safe

bool

True enables the URL-safe alphabet.

Returns

Type

Description

str

Decoded text, including an empty string for empty data.

Raises

Exception

Description

ValueError

Base64 decoding fails; UnicodeDecodeError (a subclass) may also be raised when the decoded bytes do not match the codec.

LookupError

The codec name is unknown.

Examples

Use this public operation:

result = ddp_utils.base64.decode_string(data=data_value)
ddp_utils.base64.encode_file(input_path: str | Path, output_path: str | Path | None = None, url_safe: bool = False, as_string: bool = False) → str | None

Read an entire file, encode it, and return encoded text or an output path.

All ordinary exceptions, including missing files and write failures, are caught and converted to None. File output overwrites an existing file and prints a completion message; missing parent directories are not created.

Parameters

Name

Type

Description

input_path

str | Path

Source file path; read in binary mode.

output_path

str | Path | None

ASCII output file; None appends ‘.b64’ to the original suffix. Ignored completely when as_string=True.

url_safe

bool

Select the URL-safe alphabet when True.

as_string

bool

True returns text without writing; False writes to disk.

Returns

Type

Description

str | None

Encoded str for as_string=True; str(output_path) after a successful write otherwise; None on error. Empty input can produce an empty string.

Raises

Exception

Description

FileNotFoundError

If the input file does not exist.

Examples

Use this public operation:

result = ddp_utils.base64.encode_file(input_path=input_path_value)
ddp_utils.base64.decode_file(input_path: str | Path, output_path: str | Path | None = None, url_safe: bool = False, as_bytes: bool = False) → bytes | None

Decode an ASCII Base64 file into bytes or a binary output file.

Unlike encode_file, errors propagate. Leading/trailing whitespace is stripped before decoding. File output overwrites existing content, does not create parents, and prints a completion message.

Parameters

Name

Type

Description

input_path

str | Path

ASCII Base64 file to read in full.

output_path

str | Path | None

Output path, ignored if as_bytes=True. If None, a final ‘.b64’ suffix is removed; otherwise ‘<stem>_decoded’ is used.

url_safe

bool

True enables the URL-safe alphabet.

as_bytes

bool

True returns bytes without writing; False writes a binary file.

Returns

Type

Description

bytes | None

Bytes if as_bytes=True; None after a successful file write.

Raises

Exception

Description

FileNotFoundError

Input or an output parent is missing.

ValueError

Decoding fails; decoding is permissive, not strict validation.

OSError

Reading or writing fails.

Examples

Use this public operation:

result = ddp_utils.base64.decode_file(input_path=input_path_value)
ddp_utils.base64.encode_image_to_data_uri(image_path: str | Path, mime_type: str | None = None) → str

Read file bytes and build a Base64 data URI without validating image content.

Parameters

Name

Type

Description

image_path

str | Path

Existing file, read entirely into memory.

mime_type

str | None

Explicit MIME text; None infers from the case-insensitive suffix: png, jpg/jpeg, gif, bmp, webp or svg. Other suffixes use ‘application/octet-stream’. An explicit empty string is preserved.

Returns

Type

Description

String of the form ‘data

<mime>;base64,<encoded bytes>’.

Raises

Exception

Description

FileNotFoundError

The input does not exist.

OSError

The file cannot be read.

Examples

Use this public operation:

result = ddp_utils.base64.encode_image_to_data_uri(image_path=image_path_value)
ddp_utils.base64.get_base64_from_url(image_url: str, headers: dict | None = None, *, timeout: float | Tuple[float, float] = (5.0, 30.0), max_bytes: int | None = 26214400, chunk_size: int = 65536) → str | None

Stream an HTTP response into memory and encode its body as Base64.

Despite the name, the body need not contain an image. After streaming it is joined in memory; max_bytes bounds body size, not total process memory.

Parameters

Name

Type

Description

image_url

str

URL passed to requests.get with stream=True.

headers

dict | None

Optional request headers; None or {} sends an empty mapping.

timeout

float | Tuple[float, float]

Requests timeout in seconds, scalar or (connect, read) pair. This is not a total download deadline.

max_bytes

int | None

Positive integer body-size cap; None disables it. Checked against Content-Length when parseable and against streamed bytes.

chunk_size

int

Positive integer streaming chunk size. Booleans are rejected for both size arguments; empty chunks are skipped.

Returns

Type

Description

str | None

Base64 string without a data-URI prefix, or None on invalid size options, HTTP errors, size-limit failures, timeouts or other ordinary errors. Failures print a message. An empty successful response returns ‘’.

Raises

Exception

Description

ImportError

requests cannot be imported (not converted to None).

Examples

Use this public operation:

result = ddp_utils.base64.get_base64_from_url(image_url=image_url_value)
ddp_utils.base64.save_base64_data(base64_data: str, output_path: str | Path, remove_header: bool = True) → None

Decode standard Base64 and overwrite a binary file, creating its parents.

Parameters

Name

Type

Description

base64_data

str

Base64 string, optionally with a data-URI header.

output_path

str | Path

Target filename; parents are created before decoding.

remove_header

bool

True discards everything through the first comma when one exists, without checking whether it is a valid data-URI header. False decodes the entire string using permissive Base64 rules.

Returns

Type

Description

None

None after a successful write.

Raises

Exception

Description

ValueError

Decoding fails. Parent directories may already have been created.

OSError

Creating parents or writing the file fails.

Examples

Use this public operation:

result = ddp_utils.base64.save_base64_data(base64_data=base64_data_value, output_path=output_path_value)
ddp_utils.base64.save_base64_image(base64_data: str, output_path: str | Path, format: str = 'png', filename: str | None = None, remove_header: bool = True) → str | None

Save decoded bytes with a chosen filename extension; return its path or None.

This does not transcode or validate an image. Every ordinary exception is caught and converted to None. Existing output files are overwritten.

Parameters

Name

Type

Description

base64_data

str

Base64 text, optionally with a data-URI header.

output_path

str | Path

If it has a suffix, use its parent and stem, replacing the suffix. Otherwise an existing directory is used as the directory; a non-directory/nonexistent path supplies its parent and filename.

format

str

Literal output extension appended after a dot, default ‘png’. Use an extension without a dot; the value is not format-validated.

filename

str | None

Explicit basename overriding the derived stem. None uses the derived stem or ‘unknown’ for an existing suffixless directory. Not sanitized: use trusted names without traversal components.

remove_header

bool

Forwarded to save_base64_data.

Returns

Type

Description

str | None

Output path string on success, or None on decoding/filesystem errors.

Examples

Use this public operation:

result = ddp_utils.base64.save_base64_image(base64_data=base64_data_value, output_path=output_path_value)