# 用 ebooklib 来制作 EPUB 电子书

**URL:** <https://forum.freemdict.com/t/topic/4098>\
**Category:** 技术交流与词典编修\
**Created:** [2020 年11 月 17 日 09:52 UTC](https://forum.freemdict.com/t/topic/4098 "2020-11-17T09:52:45Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

作者： ![lurker](https://forumcdn.freemdict.com/user_avatar/forum.freemdict.com/lurker/32/16016_2.png) [@lurker](https://forum.freemdict.com/u/lurker)\
发布日期： [2020 年11 月 17 日 09:52 UTC](https://forum.freemdict.com/t/topic/4098/1 "2020-11-17T09:52:45Z")

</div>

EbookLib is a Python library for managing EPUB2/EPUB3 files. It’s capable of reading and writing EPUB files **programmatically**.

> **[GitHub - aerkalov/ebooklib: Python E-book library for handling books in...](https://github.com/aerkalov/ebooklib)**
>
> Python E-book library for handling books in EPUB2/EPUB3 format - - GitHub - aerkalov/ebooklib: Python E-book library for handling books in EPUB2/EPUB3 format -

遗憾的是，官方示例很多地方没讲清楚，比如怎么添加图片等。只能自己琢磨了，以下是我的方案。还有大量问题待解决。

```

# add images
    with open("img.txt", "r") as frit:
        for line in frit:
            path = line.strip()
            img_name = "images/"+path.split("/")[-1]
            img_uid = "img_"+path.split("/")[-2]
            ext_name = path.split(".")[-1]
            if ext_name == "jpg":
                img_type = "image/jpeg"
            if ext_name == "png":
                img_type = "image/png"
            with open(path, "rb") as frp:
                content_img = frp.read()
            img_item = epub.EpubItem(uid=img_uid, file_name=img_name, media_type=img_type, content=content_img)
            book.add_item(img_item)

```

---

<div class="post-metadata">

作者： ![蚂蚁小兵](https://forumcdn.freemdict.com/letter_avatar_proxy/v4/letter/%E8%9A%82/dbc845/32.png) [@蚂蚁小兵](https://forum.freemdict.com/u/%E8%9A%82%E8%9A%81%E5%B0%8F%E5%85%B5)\
发布日期： [2023 年7 月 1 日 09:59 UTC](https://forum.freemdict.com/t/topic/4098/2 "2023-07-01T09:59:59Z")

</div>

# 设置电子书的封面

book.set\_cover(“cover.jpg”, open(“cover.jpg”, “rb”).read())
