Skip to main content
 首页 » 编程设计

python之在 Python 3.4 中将图像读入 Ebooklib.Epub

2024年10月24日14over140

我想使用在 Python 3.4 中导入封面的 ebooklib 制作一本电子书。

在 Python 2 中,它像这样工作得很好:

im = open('image.jpg').read()   
book.set_cover(file_name=image.jpg',content=im,create_page=True) 

在 Python 3.4 中它失败了:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte.

显然,通过 open 方法读取图像不再有效,但我无法在 Python3 中找到其他方法。

我尝试使用编解码器模块:

im = codecs.open("image.jpg",'r', 'encoding='utf-8')   

Result: TypeError: 'str' does not support the buffer interface

我尝试使用 Pillow:

im=Image.open(path+'mn_epub.jpg').load()   

Result: TypeError: object of type 'PixelAccess' has no len()

我还尝试了其他各种 Pillow 操作,但我找不到任何让它工作的东西。

请您参考如下方法:

库似乎有一些 unicode 问题。 这是一个 shim,猴子可以修补库并解决问题;在脚本的开头,在导入库之后,包含以下代码:

from ebooklib import epub 
original_get_template = epub.EpubBook.get_template 
def new_get_template(*args, **kwargs): 
    return original_get_template(*args, **kwargs).encode(encoding='utf8') 
epub.EpubBook.get_template = new_get_template