View Single Post
Old 12-04-2015, 05:33 AM   #31
Doitsu
Grand Sorcerer
Doitsu ought to be getting tired of karma fortunes by now.Doitsu ought to be getting tired of karma fortunes by now.Doitsu ought to be getting tired of karma fortunes by now.Doitsu ought to be getting tired of karma fortunes by now.Doitsu ought to be getting tired of karma fortunes by now.Doitsu ought to be getting tired of karma fortunes by now.Doitsu ought to be getting tired of karma fortunes by now.Doitsu ought to be getting tired of karma fortunes by now.Doitsu ought to be getting tired of karma fortunes by now.Doitsu ought to be getting tired of karma fortunes by now.Doitsu ought to be getting tired of karma fortunes by now.
 
Doitsu's Avatar
 
Posts: 5,747
Karma: 24032915
Join Date: Dec 2010
Device: Kindle PW2
Quote:
Originally Posted by rubeus View Post
For example inserting images. I dont want them to blow up on hires screens over the "natural" size so i have a common code snippet and to make it individual to each image i'm applaying the with via inline stylesheet [...]:
You should be able to this with beautifulsoup4 and PIL. I.e. grab all img tags with BS4, get the dimensions with PIL and then add a style attribute with BS4.

The following edit plugin code, which requires Sigil 0.9 (and higher) and the bundled interpreter, should work.

Spoiler:
Code:
#!/usr/bin/env python
# -*- coding: utf-8 -*- 
from sigil_bs4 import BeautifulSoup
from PIL import Image
import os

def run(bk):

    for (html_id, linear) in bk.getspine():
        mime = bk.id_to_mime(html_id)
        
        if mime == 'application/xhtml+xml':
            html = bk.readfile(html_id)
            soup = BeautifulSoup(html)
            orig_soup = str(soup)
            images = soup.find_all('img')

            for image in images:
                image_path = os.path.join(bk._w.ebook_root, 'OEBPS', 'Images', os.path.basename(image['src']))
                img = Image.open(image_path)
                width, height = img.size
                image['style'] = 'max-width: ' + str(width) + 'px'
                
            if str(soup) != orig_soup:
                bk.writefile(html_id, str(soup.prettyprint_xhtml(indent_level=0, eventual_encoding="utf-8", formatter="minimal", indent_chars="  ")))
                print(bk.id_to_href(html_id) + ' updated')
    
    return 0

def main():
    print ('I reached main when I should not have\n')
    return -1

if __name__ == "__main__":
    sys.exit(main())
Attached Files
File Type: zip German Dictionary Test.zip (6.3 KB, 275 views)

Last edited by Doitsu; 02-04-2016 at 05:46 AM.
Doitsu is offline   Reply With Quote