svg-ultralight 0.35.1__py3-none-any.whl → 0.37.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of svg-ultralight might be problematic. Click here for more details.

@@ -0,0 +1,134 @@
1
+ """Crop an image before converting to binary and including in the svg file.
2
+
3
+ This optional module requires the Pillow library. Create an svg image element with a
4
+ rasterized image positioned inside a bounding box.
5
+
6
+ :author: Shay Hill
7
+ :created: 2024-11-20
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import TYPE_CHECKING
13
+
14
+ from paragraphs import par
15
+
16
+ try:
17
+ from PIL import Image
18
+
19
+ if TYPE_CHECKING:
20
+ from PIL.Image import Image as ImageType
21
+ except ImportError as err:
22
+ msg = par(
23
+ """PIL is not installed. Install it using 'pip install Pillow' to use
24
+ svg_ultralight.image_ops module."""
25
+ )
26
+ raise ImportError(msg) from err
27
+
28
+ import base64
29
+ import io
30
+
31
+ from lxml import etree
32
+
33
+ from svg_ultralight import NSMAP
34
+ from svg_ultralight.bounding_boxes.bound_helpers import bbox_dict
35
+ from svg_ultralight.constructors import new_element
36
+
37
+ if TYPE_CHECKING:
38
+ from pathlib import Path
39
+
40
+ from lxml.etree import (
41
+ _Element as EtreeElement, # pyright: ignore [reportPrivateUsage]
42
+ )
43
+
44
+ from svg_ultralight.bounding_boxes.type_bounding_box import BoundingBox
45
+
46
+
47
+ def _symmetric_crop(
48
+ image: ImageType, center: tuple[float, float] | None = None
49
+ ) -> ImageType:
50
+ """Crop an image symmetrically around a center point.
51
+
52
+ :param image: PIL.Image instance
53
+ :param center: optional center point for cropping. Proportions of image with and
54
+ image height, so the default value, (0.5, 0.5), is the true center of the
55
+ image. (0.4, 0.5) would crop 20% off the right side of the image.
56
+ :return: PIL.Image instance
57
+ """
58
+ if center is None:
59
+ return image
60
+
61
+ if not all(0 < x < 1 for x in center):
62
+ msg = "Center must be between (0, 0) and (1, 1)"
63
+ raise ValueError(msg)
64
+
65
+ xd, yd = (min(x, 1 - x) for x in center)
66
+ left, right = sorted(x * image.width for x in (center[0] - xd, center[0] + xd))
67
+ top, bottom = sorted(x * image.height for x in (center[1] - yd, center[1] + yd))
68
+
69
+ return image.crop((left, top, right, bottom))
70
+
71
+
72
+ def _crop_image_to_bbox_ratio(
73
+ image: ImageType, bbox: BoundingBox, center: tuple[float, float] | None = None
74
+ ) -> ImageType:
75
+ """Crop an image to the ratio of a bounding box.
76
+
77
+ :param image: PIL.Image instance
78
+ :param bbox: BoundingBox instance
79
+ :param center: optional center point for cropping. Proportions of image with and
80
+ image height, so the default value, (0.5, 0.5), is the true center of the
81
+ image. (0.4, 0.5) would crop 20% off the right side of the image.
82
+ :return: PIL.Image instance
83
+
84
+ This crops the image to the specified ratio. It's not a resize, so it will cut
85
+ off the top and bottom or the sides of the image to fit the ratio.
86
+ """
87
+ image = _symmetric_crop(image, center)
88
+ width, height = image.size
89
+
90
+ ratio = bbox.width / bbox.height
91
+ if width / height > ratio:
92
+ new_width = height * ratio
93
+ left = (width - new_width) / 2
94
+ right = width - left
95
+ return image.crop((left, 0, right, height))
96
+ new_height = width / ratio
97
+ top = (height - new_height) / 2
98
+ bottom = height - top
99
+ return image.crop((0, top, width, bottom))
100
+
101
+
102
+ def _get_svg_embedded_image_str(image: ImageType) -> str:
103
+ """Return the string you'll need to embed an image in an svg.
104
+
105
+ :param image: PIL.Image instance
106
+ :return: argument for xlink:href
107
+ """
108
+ in_mem_file = io.BytesIO()
109
+ image.save(in_mem_file, format="PNG")
110
+ _ = in_mem_file.seek(0)
111
+ img_bytes = in_mem_file.read()
112
+ base64_encoded_result_bytes = base64.b64encode(img_bytes)
113
+ base64_encoded_result_str = base64_encoded_result_bytes.decode("ascii")
114
+ return "data:image/png;base64," + base64_encoded_result_str
115
+
116
+
117
+ def new_image_elem_in_bbox(
118
+ filename: Path | str, bbox: BoundingBox, center: tuple[float, float] | None
119
+ ) -> EtreeElement:
120
+ """Create a new svg image element inside a bounding box.
121
+
122
+ :param filename: filename of source image
123
+ :param bbox: bounding box for the image
124
+ :param center: center point for cropping. Proportions of image width and image
125
+ height, so the default value, (0.5, 0.5), is the true center of the image.
126
+ (0.4, 0.5) would crop 20% off the right side of the image.
127
+ :return: an etree image element with the cropped image embedded
128
+ """
129
+ image = _crop_image_to_bbox_ratio(Image.open(filename), bbox, center)
130
+ svg_image = new_element("image", **bbox_dict(bbox))
131
+ svg_image.set(
132
+ etree.QName(NSMAP["xlink"], "href"), _get_svg_embedded_image_str(image)
133
+ )
134
+ return svg_image
@@ -17,13 +17,34 @@ if TYPE_CHECKING:
17
17
  from collections.abc import Iterable
18
18
 
19
19
 
20
+ _MAX_8BIT = 255
21
+ _BIG_INT = 2**32 - 1
22
+
23
+
24
+ def _float_to_8bit_int(clipped_float: float) -> int:
25
+ """Convert a float between 0 and 255 to an int between 0 and 255.
26
+
27
+ :param float_: a float in the closed interval [0 .. 255]. Values outside this
28
+ range will be clipped.
29
+ :return: an int in the closed interval [0 .. 255]
30
+
31
+ Convert color floats [0 .. 255] to ints [0 .. 255] without rounding, which "short
32
+ changes" 0 and 255.
33
+ """
34
+ clipped_float = min(_MAX_8BIT, max(0, clipped_float))
35
+ if clipped_float % 1:
36
+ high_int = int(clipped_float / _MAX_8BIT * _BIG_INT)
37
+ return high_int >> 24
38
+ return int(clipped_float)
39
+
40
+
20
41
  def svg_color_tuple(rgb_floats: tuple[float, float, float]) -> str:
21
42
  """Turn an rgb tuple (0-255, 0-255, 0-255) into an svg color definition.
22
43
 
23
44
  :param rgb_floats: (0-255, 0-255, 0-255)
24
45
  :return: "rgb(128,128,128)"
25
46
  """
26
- r, g, b = (round(x) for x in rgb_floats)
47
+ r, g, b = map(_float_to_8bit_int, rgb_floats)
27
48
  return f"rgb({r},{g},{b})"
28
49
 
29
50
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: svg-ultralight
3
- Version: 0.35.1
3
+ Version: 0.37.0
4
4
  Summary: a sensible way to create svg files with Python
5
5
  Author-email: Shay Hill <shay_public@hotmail.com>
6
6
  License: MIT
@@ -15,6 +15,8 @@ Requires-Dist: pytest; extra == "dev"
15
15
  Requires-Dist: commitizen; extra == "dev"
16
16
  Requires-Dist: pre-commit; extra == "dev"
17
17
  Requires-Dist: tox; extra == "dev"
18
+ Provides-Extra: images
19
+ Requires-Dist: pillow; extra == "images"
18
20
 
19
21
  # svg_ultralight
20
22
 
@@ -1,5 +1,6 @@
1
1
  svg_ultralight/__init__.py,sha256=wUc79mKsG6lGZ1xaYijyJ4Sm9lG5-5XgRArVsCI0niY,2554
2
2
  svg_ultralight/animate.py,sha256=JSrBm-59BcNXDF0cGgl4-C89eBunjevZnwZxIWt48TU,1112
3
+ svg_ultralight/image_ops.py,sha256=PXN_p5GX91UTvhnwwU-bPuj6WzM9wCx1SqfzR5icNnQ,4686
3
4
  svg_ultralight/inkscape.py,sha256=M8yTxXOu4NlXnhsMycvEJiIDpnDeiZ_bZakJBM38ZoU,9152
4
5
  svg_ultralight/layout.py,sha256=FgR45FsHax4xDjGkk9HEVW4OcwhtM8aqw2JUdZs_m7Q,12326
5
6
  svg_ultralight/main.py,sha256=6oNkZfD27UMdP-oYqp5agS_IGcYb8NkUZwM9Zdyb3SA,7287
@@ -21,8 +22,8 @@ svg_ultralight/bounding_boxes/type_padded_text.py,sha256=QA6PfeO_sQYc5pEXuyfyQ3l
21
22
  svg_ultralight/constructors/__init__.py,sha256=XLOInLhzMERWNnFAs-itMs-OZrBOpvQthZJ2T5duqBE,327
22
23
  svg_ultralight/constructors/new_element.py,sha256=8nqmOEgt3j-aOVeRaMLFHqrwKg2Dm5w0AfuK9MP4ak8,3433
23
24
  svg_ultralight/strings/__init__.py,sha256=BMGhF1pulscIgkiYvZLr6kPRR0L4lW0jUNFxkul4_EM,295
24
- svg_ultralight/strings/svg_strings.py,sha256=RYKMxOHq9abbZyGcFqsElBGLrBX-EjjNxln3s_ibi30,1296
25
- svg_ultralight-0.35.1.dist-info/METADATA,sha256=PRuCkp6xtBx_t8pkPEJR00TZRcb82eygu1EQTuROHaM,8867
26
- svg_ultralight-0.35.1.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
27
- svg_ultralight-0.35.1.dist-info/top_level.txt,sha256=se-6yqM_0Yg5orJKvKWdjQZ4iR4G_EjhL7oRgju-fdY,15
28
- svg_ultralight-0.35.1.dist-info/RECORD,,
25
+ svg_ultralight/strings/svg_strings.py,sha256=FQNxNmMkR2M-gCFo_woQKXLgCHi3ncUlRMiaRR_a9nQ,1978
26
+ svg_ultralight-0.37.0.dist-info/METADATA,sha256=wWTDiiOScZrgr_Np0_XCqyJ9WKEAEKHJRXvPU5Qw5-Y,8933
27
+ svg_ultralight-0.37.0.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
28
+ svg_ultralight-0.37.0.dist-info/top_level.txt,sha256=se-6yqM_0Yg5orJKvKWdjQZ4iR4G_EjhL7oRgju-fdY,15
29
+ svg_ultralight-0.37.0.dist-info/RECORD,,