Created
February 14, 2023 13:29
-
-
Save x86-69/849360c4fed954feaa14563d74171204 to your computer and use it in GitHub Desktop.
Transform directory of images into a unique epub file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import io | |
from PIL import Image | |
from ebooklib import epub | |
# defines the direcotry where the images will be read | |
img_dir = input("> images directory: ") | |
# create an EpubBook object | |
book = epub.EpubBook() | |
# create a new item for each image in directory | |
files = os.listdir(img_dir) | |
files.sort() | |
for img_file in files: | |
file_extension = img_file.split(".")[-1] | |
if file_extension in ["jpg", "jpeg", "png"]: | |
print(f"[*] loading file: {img_file}", end="\r") | |
if file_extension in ["jpg", "jpeg"]: | |
media_type = "image/jpeg" | |
pillow_extension = "jpeg" | |
else: | |
media_type = "image/png" | |
pillow_extension = "png" | |
# it creates an Image object to work with the image | |
img_path = os.path.join(img_dir, img_file) | |
image = Image.open(img_path) | |
b = io.BytesIO() | |
image.save(b, pillow_extension) | |
b_image = b.getvalue() | |
# defines the archive name to the image inside the EPUB file | |
img_filename = img_file | |
# add the image as a new EpubItem object to the book | |
img_item = epub.EpubItem(uid=img_file, file_name=img_filename, media_type=media_type, content=b_image) | |
book.add_item(img_item) | |
# creates a new EpubHtml object to represent the page with the image | |
html = f"<html><body><img src=\"{img_filename}\"/></body></html>" | |
item = epub.EpubHtml(title=img_file, file_name=img_file + ".html", lang="pt") | |
item.content = html | |
# adds the EpubHtml object as an iten to the book | |
book.add_item(item) | |
book.spine.append(item) | |
print() | |
# defines the book metadata | |
book.set_identifier("1337 h4x0r") | |
title = input("> book's title: ") | |
book.set_title(title) | |
book.set_language("en") | |
# defines the book cover | |
try: | |
with open(os.path.join(img_dir, "cover.jpg"), 'rb') as cover_file: | |
cover_data = cover_file.read() | |
except FileNotFoundError: | |
with open(os.path.join(img_dir, files[0]), 'rb') as cover_file: | |
cover_data = cover_file.read() | |
book.set_cover("cover.jpg", cover_data) | |
# create the EPUB file | |
book.toc = (epub.Link("Cover", "cover.html", "cover"), (epub.Section("Images"), tuple(book.items))) | |
book.add_item(epub.EpubNcx()) | |
book.add_item(epub.EpubNav()) | |
print("[*] writing to file") | |
epub.write_epub(f"{title}.epub", book, {}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment