Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

""" 

@file 

@brief Helpers around images and :epkg:`SVG`. 

 

.. versionadded:: 1.7 

""" 

import xml.etree.ElementTree as ET 

try: 

from io import BytesIO 

except ImportError: 

# Python 2.7 

from StringIO import StringIO as BytesIO 

 

from .excs import PYQImageException 

 

 

def guess_svg_size(svg): 

""" 

Guesses the dimension of a :epkg:`SVG` image. 

 

@param svg :epkg:`SVG` description 

@return size (x, y) 

""" 

mx, my = 0, 0 

tree = ET.fromstring(svg) 

for elt in tree.iter(): 

for k, v in elt.attrib.items(): 

if k in ('x', 'cx', 'width'): 

mx = max(0, int(v)) 

elif k in ('rx',): 

mx = max(0, 2 * int(v)) 

elif k in ('y', 'cy', 'height'): 

my = max(0, int(v)) 

elif k in ('ry',): 

my = max(0, 2 * int(v)) 

return (mx, my) 

 

 

def svg2img(svg, dpi=None, scale=1., **kwargs): 

""" 

Converts an image in :epkg:`SVG` format. 

 

@param svg svg 

@param dpi image resolution 

@param scale scale 

@param kwargs additional parameters 

@return image 

 

The module relies on the following dependencies: 

 

* :epkg:`cairosvg` 

* :epkg:`Pillow` 

""" 

kwargs = {} 

if dpi: 

kwargs['dpi'] = dpi 

if scale not in (None, 1., 1): 

kwargs['scale'] = scale 

from cairosvg import svg2png 

img = BytesIO() 

try: 

svg2png(svg, write_to=img, **kwargs) 

except OSError as e: 

if svg.startswith('<svg>'): 

size = guess_svg_size(svg) 

head = '<svg width="{}" height="{}">'.format(*size) 

svg = head + svg[5:] 

return svg2img(svg, dpi=dpi, scale=scale, **kwargs) 

else: 

raise PYQImageException( 

"width and height must be specified. This might be the error.") from e 

png = img.getvalue() 

st = BytesIO(png) 

from PIL import Image 

return Image.open(st)