From 8e6ee68bd85e8276ac64e28b280a63e8a98d2380 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Thu, 2 Jan 2014 09:24:51 +0530 Subject: [PATCH] Modernize code in t4b.py Fixes #1265225 [Update Orizon driver](https://bugs.launchpad.net/calibre/+bug/1265225) --- src/calibre/devices/cybook/t4b.py | 29 +++++++++++++---------------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/src/calibre/devices/cybook/t4b.py b/src/calibre/devices/cybook/t4b.py index 1eddca70df..b1759efb8d 100644 --- a/src/calibre/devices/cybook/t4b.py +++ b/src/calibre/devices/cybook/t4b.py @@ -1,20 +1,18 @@ +# vim:fileencoding=utf-8 +from __future__ import (unicode_literals, division, absolute_import, + print_function) __license__ = 'GPL v3' __copyright__ = '2013, Jellby ' ''' Write a t4b file to disk. ''' -import StringIO +from io import BytesIO -DEFAULT_T4B_DATA = '' +DEFAULT_T4B_DATA = b'' def reduce_color(c): - if (c < 0): - return 0 - elif (c > 255): - return 15 - else: - return c//16 + return max(0, min(255, c))//16 def write_t4b(t4bfile, coverdata=None): ''' @@ -22,21 +20,20 @@ def write_t4b(t4bfile, coverdata=None): coverdata is a string representation of a JPEG file. ''' from PIL import Image - if coverdata != None: - coverdata = StringIO.StringIO(coverdata) + if coverdata is not None: + coverdata = BytesIO(coverdata) cover = Image.open(coverdata).convert("L") cover.thumbnail((96, 144), Image.ANTIALIAS) t4bcover = Image.new('L', (96, 144), 'white') x, y = cover.size - t4bcover.paste(cover, ((96-x)/2, (144-y)/2)) + t4bcover.paste(cover, ((96-x)//2, (144-y)//2)) pxs = t4bcover.getdata() - t4bfile.write('t4bp') - for i in range(0,len(pxs),2): - byte = reduce_color(pxs[i]) - byte = 16*byte + reduce_color(pxs[i+1]) - t4bfile.write(chr(byte)) + t4bfile.write(b't4bp') + data = (16 * reduce_color(pxs[i]) + reduce_color(pxs[i+1]) + for i in xrange(0, len(pxs), 2)) + t4bfile.write(bytes(bytearray(data))) else: t4bfile.write(DEFAULT_T4B_DATA)