|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# ----------------------------------------------------------------------------- |
| 3 | +# |
| 4 | +# P A G E B O T E X A M P L E S |
| 5 | +# # Copyright (c) 2017 Thom Janssen <https://github.com/thomgb> |
| 6 | +# www.pagebot.io |
| 7 | +# Licensed under MIT conditions |
| 8 | +# |
| 9 | +# Supporting DrawBot, www.drawbot.com |
| 10 | +# Supporting Flat, xxyxyz.org/flat |
| 11 | +# ----------------------------------------------------------------------------- |
| 12 | +# |
| 13 | +# E01_ScalingAnImage.py |
| 14 | +# |
| 15 | + |
| 16 | +import os |
| 17 | +import sys |
| 18 | + |
| 19 | +from pagebot import getContext |
| 20 | +from pagebot.filepaths import getResourcesPath |
| 21 | +from pagebot.toolbox.units import pt |
| 22 | +from pagebot.toolbox.transformer import path2FileName |
| 23 | + |
| 24 | +FILENAME = path2FileName(__file__) |
| 25 | +IMAGENAME = 'cookbot1' |
| 26 | + |
| 27 | +def draw(contextName): |
| 28 | + context = getContext(contextName) |
| 29 | + path = getResourcesPath() + "/images/%s.jpg" % IMAGENAME |
| 30 | + w, h = context.imageSize(path) |
| 31 | + |
| 32 | + # Let's say we want to scale it to 50%. The 0.5 is the multiplication |
| 33 | + # factor. |
| 34 | + newScale = 0.5 |
| 35 | + |
| 36 | + # Make a page with the size of the scaled image, rounded to whole pixels. |
| 37 | + context.newPage(pt(int(w*newScale)), pt(int(h*newScale))) |
| 38 | + |
| 39 | + # Saves the “graphics state“, just in case the script is extended later, |
| 40 | + # where other operation need to work in 100%. |
| 41 | + context.save() |
| 42 | + # Make all drawing scale to 50% |
| 43 | + context.scale(newScale) |
| 44 | + # Draw the scaled image at the bottom-left corner. It fills the whole page. |
| 45 | + context.image(path, pt(0, 0)) |
| 46 | + |
| 47 | + # Saves the page as png file (and also do conversion from jpg to png this |
| 48 | + # way). |
| 49 | + if not os.path.exists('_export/'): |
| 50 | + os.makedirs('_export/') |
| 51 | + |
| 52 | + # Note that resulting images may look sharper, but has 4.5x the size of the .jpg. |
| 53 | + # 944Kb size |
| 54 | + context.saveImage('_export/%s-%s-%d-%s.png' % (FILENAME, IMAGENAME, newScale*100, contextName)) |
| 55 | + # 168Kb size |
| 56 | + context.saveImage('_export/%s-%s-%d-%s.jpg' % (FILENAME, IMAGENAME, newScale*100, contextName)) |
| 57 | + # 346Kb size |
| 58 | + context.saveImage('_export/%s-%s-%d-%s.gif' % (FILENAME, IMAGENAME, newScale*100, contextName)) |
| 59 | + |
| 60 | + # Restores the graphics state, so context scaling is back to 100% after this. |
| 61 | + context.restore() |
| 62 | + |
| 63 | +for contextName in ('DrawBot', 'Flat'): |
| 64 | + draw(contextName) |
0 commit comments