Dekoder File Base64
Mendekode string base64 kembali ke file yang dapat diunduh.
Pertanyaan yang Sering Diajukan
Implementasi Kode
import base64
def decode_base64_file(b64_string: str, output_path: str) -> None:
"""Decode a base64 string (with or without data URL prefix) and write to file."""
# Strip data URL prefix if present: data:image/png;base64,...
if "," in b64_string:
b64_string = b64_string.split(",", 1)[1]
# Remove whitespace
b64_string = b64_string.strip().replace("\n", "").replace("\r", "")
data = base64.b64decode(b64_string)
with open(output_path, "wb") as f:
f.write(data)
print(f"Decoded {len(data)} bytes → {output_path}")
# Encode a file to base64
def encode_file_to_base64(path: str) -> str:
with open(path, "rb") as f:
return base64.b64encode(f.read()).decode("utf-8")
# Round-trip example
encoded = encode_file_to_base64("example.png")
decode_base64_file(encoded, "decoded_example.png")
Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.