Base64から画像ファイル生成
Base64エンコードされた文字列から画像ファイルを生成する方法について説明します。
Pythonでの実装
Section titled “Pythonでの実装”基本的なコード例
Section titled “基本的なコード例”import base64
# テキストファイルからBase64エンコードされた文字列を読み込むwith open("base64_string.txt", "r") as file: base64_string = file.read()
# デコードしてバイナリデータに変換image_data = base64.b64decode(base64_string)
# 画像ファイルとして保存with open("output_image.png", "wb") as file: file.write(image_data)
print("画像ファイルが保存されました")エラーハンドリングを含む実装
Section titled “エラーハンドリングを含む実装”import base64import sys
def base64_to_image(base64_file_path, output_image_path): try: # Base64文字列を読み込む with open(base64_file_path, "r") as file: base64_string = file.read().strip()
# データURLスキーム形式の場合、ヘッダー部分を除去 if base64_string.startswith("data:image"): base64_string = base64_string.split(",")[1]
# デコード image_data = base64.b64decode(base64_string)
# 画像として保存 with open(output_image_path, "wb") as file: file.write(image_data)
print(f"画像ファイルが保存されました: {output_image_path}") return True
except FileNotFoundError: print(f"エラー: ファイル '{base64_file_path}' が見つかりません") return False except base64.binascii.Error: print("エラー: 無効なBase64文字列です") return False except Exception as e: print(f"エラー: {str(e)}") return False
# 使用例if __name__ == "__main__": base64_to_image("base64_string.txt", "output_image.png")コマンドラインでの実装
Section titled “コマンドラインでの実装”Bashワンライナー
Section titled “Bashワンライナー”# Base64ファイルから画像を生成base64 -d base64_string.txt > output_image.png
# macOSの場合base64 -D base64_string.txt > output_image.pngデータURLスキーム形式の処理
Section titled “データURLスキーム形式の処理”# data:image/png;base64,... 形式の場合cat base64_string.txt | sed 's/data:image\/[^;]*;base64,//' | base64 -d > output_image.pngNode.jsでの実装
Section titled “Node.jsでの実装”const fs = require('fs');
// Base64文字列を読み込むconst base64String = fs.readFileSync('base64_string.txt', 'utf8');
// データURLスキーム形式の場合の処理const base64Data = base64String.replace(/^data:image\/\w+;base64,/, '');
// バッファに変換const imageBuffer = Buffer.from(base64Data, 'base64');
// ファイルとして保存fs.writeFileSync('output_image.png', imageBuffer);
console.log('画像ファイルが保存されました');画像形式の自動判定
Section titled “画像形式の自動判定”import base64import imghdr
def base64_to_image_with_detection(base64_file_path, output_filename_prefix="output"): with open(base64_file_path, "r") as file: base64_string = file.read().strip()
# データURLスキーム形式の処理 if base64_string.startswith("data:image"): base64_string = base64_string.split(",")[1]
# デコード image_data = base64.b64decode(base64_string)
# 画像形式を判定 image_type = imghdr.what(None, image_data) if not image_type: image_type = "png" # デフォルト
# 適切な拡張子で保存 output_path = f"{output_filename_prefix}.{image_type}" with open(output_path, "wb") as file: file.write(image_data)
print(f"画像ファイルが保存されました: {output_path} (形式: {image_type})")
# 使用例base64_to_image_with_detection("base64_string.txt", "output_image")- 改行の処理: Base64文字列に改行が含まれている場合は、適切に処理する必要があります
- データURLスキーム:
data:image/png;base64,のようなヘッダーが含まれている場合は除去が必要 - ファイル形式: 出力ファイルの拡張子は、元の画像形式に合わせる必要があります
- エラーハンドリング: 無効なBase64文字列の場合のエラー処理を実装することを推奨