3

I want to make an ebook using ebooklib that imports a cover in Python 3.4.

In Python 2 it works fine like this:

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

In Python 3.4 it fails with:

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

Apparently reading an image via the open method no longer works but I cannot find how to do it otherwise in Python3.

I tried using codecs module:

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

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

I tried using Pillow:

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

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

I also tried various other Pillow operation but I could not find anything to make it work.

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Vimala
  • 61
  • 4
  • which version of **Pillow** did you use? It seems to work on both Python 2 and 3 – Swastik Padhi Oct 30 '15 at 10:05
  • It seems that the latest version of Pillow supported for python 3 is 3.0.0 and you are using 3.4 – Swastik Padhi Oct 30 '15 at 10:15
  • Pillow 2.7 but Pillow itself works fine, also in Python 3.4, but it just does not work as content in the .set-cover method of ebooklib.epub. I cannot find what would work as content. – Vimala Nov 02 '15 at 12:56

2 Answers2

2

The library seems to have some unicode problems. Here's a shim that monkey patches the library and makes the problem go away; at the start of the script, after importing the library, include this code:

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
Vimala
  • 61
  • 4
1

Don't mean to necro an old post but this is the only post I found relating to a problem I had, so figured I'd throw this here for anybody else who stumbles on this post.

I also had a lot of problems dealing with images and the ebooklib library. I stumbled across this question regarding the charmap encoder with JPEG files,. JPEGs are saved as binary and need to be read as such, so instead of calling

im = open('image.jpg').read()

You need to call

im = open('image.jpg', 'rb').read()

This is probably something that changed between Python 2 and 3.

Community
  • 1
  • 1
Yovarni Yearwood
  • 53
  • 1
  • 1
  • 6