Skip to content

Instantly share code, notes, and snippets.

@Bogd-an
Last active October 2, 2024 18:02
Show Gist options
  • Save Bogd-an/b4aaf5a36c276b90b47a6275eaafdaca to your computer and use it in GitHub Desktop.
Save Bogd-an/b4aaf5a36c276b90b47a6275eaafdaca to your computer and use it in GitHub Desktop.
python replace dataIMG to img files
import re
import base64
import os
import sys
def save_images_from_md(md_file_path, output_dir):
# Переконайтеся, що вихідна директорія існує
os.makedirs(output_dir, exist_ok=True)
# Читання вмісту MD файлу
with open(md_file_path, 'r', encoding='utf-8') as file:
content = file.read()
# Знайти всі data:image зображення
images = re.findall(r'\[image\d+\]: <(data:image/png;base64,[^>]+)>', content)
if not images:
print("Не знайдено зображень.")
for index, image_data in enumerate(images):
# Витягування base64 даних з рядка
base64_data = image_data.split(',')[1]
# Декодування даних
image_bytes = base64.b64decode(base64_data)
# Створення імені файлу
file_name = f'image_{index + 1}.png'
file_path = os.path.join(output_dir, file_name)
# Збереження зображення
with open(file_path, 'wb') as img_file:
img_file.write(image_bytes)
# Заміна у MD файлі на посилання на файл
content = content.replace(f"[image{index + 1}]: <{image_data}>", file_path)
# Запис перезаписаного вмісту назад в MD файл
with open(md_file_path, 'w', encoding='utf-8') as file:
file.write(content)
# Використання функції
output_directory = 'output_images' # Вкажіть директорію для зображень
md_file_path = sys.argv[1]
save_images_from_md(md_file_path, output_directory)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment