AbeerTrial commited on
Commit
8a58cf3
1 Parent(s): 3cf8814

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +37 -0
  2. Docs/General.txt +3 -0
  3. Include/site/python3.11/greenlet/greenlet.h +164 -0
  4. Lib/site-packages/Jinja2-3.1.2.dist-info/INSTALLER +1 -0
  5. Lib/site-packages/Jinja2-3.1.2.dist-info/LICENSE.rst +28 -0
  6. Lib/site-packages/Jinja2-3.1.2.dist-info/METADATA +113 -0
  7. Lib/site-packages/Jinja2-3.1.2.dist-info/RECORD +58 -0
  8. Lib/site-packages/Jinja2-3.1.2.dist-info/WHEEL +5 -0
  9. Lib/site-packages/Jinja2-3.1.2.dist-info/entry_points.txt +2 -0
  10. Lib/site-packages/Jinja2-3.1.2.dist-info/top_level.txt +1 -0
  11. Lib/site-packages/MarkupSafe-2.1.3.dist-info/INSTALLER +1 -0
  12. Lib/site-packages/MarkupSafe-2.1.3.dist-info/LICENSE.rst +28 -0
  13. Lib/site-packages/MarkupSafe-2.1.3.dist-info/METADATA +93 -0
  14. Lib/site-packages/MarkupSafe-2.1.3.dist-info/RECORD +14 -0
  15. Lib/site-packages/MarkupSafe-2.1.3.dist-info/WHEEL +5 -0
  16. Lib/site-packages/MarkupSafe-2.1.3.dist-info/top_level.txt +1 -0
  17. Lib/site-packages/PIL/BdfFontFile.py +122 -0
  18. Lib/site-packages/PIL/BlpImagePlugin.py +472 -0
  19. Lib/site-packages/PIL/BmpImagePlugin.py +471 -0
  20. Lib/site-packages/PIL/BufrStubImagePlugin.py +73 -0
  21. Lib/site-packages/PIL/ContainerIO.py +120 -0
  22. Lib/site-packages/PIL/CurImagePlugin.py +75 -0
  23. Lib/site-packages/PIL/DcxImagePlugin.py +79 -0
  24. Lib/site-packages/PIL/DdsImagePlugin.py +291 -0
  25. Lib/site-packages/PIL/EpsImagePlugin.py +466 -0
  26. Lib/site-packages/PIL/ExifTags.py +380 -0
  27. Lib/site-packages/PIL/FitsImagePlugin.py +73 -0
  28. Lib/site-packages/PIL/FliImagePlugin.py +171 -0
  29. Lib/site-packages/PIL/FontFile.py +110 -0
  30. Lib/site-packages/PIL/FpxImagePlugin.py +253 -0
  31. Lib/site-packages/PIL/FtexImagePlugin.py +113 -0
  32. Lib/site-packages/PIL/GbrImagePlugin.py +102 -0
  33. Lib/site-packages/PIL/GdImageFile.py +97 -0
  34. Lib/site-packages/PIL/GifImagePlugin.py +1064 -0
  35. Lib/site-packages/PIL/GimpGradientFile.py +137 -0
  36. Lib/site-packages/PIL/GimpPaletteFile.py +56 -0
  37. Lib/site-packages/PIL/GribStubImagePlugin.py +73 -0
  38. Lib/site-packages/PIL/Hdf5StubImagePlugin.py +73 -0
  39. Lib/site-packages/PIL/IcnsImagePlugin.py +399 -0
  40. Lib/site-packages/PIL/IcoImagePlugin.py +358 -0
  41. Lib/site-packages/PIL/ImImagePlugin.py +371 -0
  42. Lib/site-packages/PIL/Image.py +0 -0
  43. Lib/site-packages/PIL/ImageChops.py +303 -0
  44. Lib/site-packages/PIL/ImageCms.py +1009 -0
  45. Lib/site-packages/PIL/ImageColor.py +313 -0
  46. Lib/site-packages/PIL/ImageDraw.py +1038 -0
  47. Lib/site-packages/PIL/ImageDraw2.py +193 -0
  48. Lib/site-packages/PIL/ImageEnhance.py +103 -0
  49. Lib/site-packages/PIL/ImageFile.py +773 -0
  50. Lib/site-packages/PIL/ImageFilter.py +550 -0
.gitattributes CHANGED
@@ -36,3 +36,40 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
36
  Docs/Cloudflare[[:space:]]Interview[[:space:]]Guide[[:space:]]_[[:space:]]Strategic[[:space:]]Account[[:space:]]Executive,[[:space:]]Dubai.pdf filter=lfs diff=lfs merge=lfs -text
37
  Docs/RCEM_BPC_Procedural_Sedation_Final_Aug_22_10772cef06[[:space:]](1).pdf filter=lfs diff=lfs merge=lfs -text
38
  Docs/RCEM_BPC_Procedural_Sedation_Final_Aug_22_10772cef06.pdf filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  Docs/Cloudflare[[:space:]]Interview[[:space:]]Guide[[:space:]]_[[:space:]]Strategic[[:space:]]Account[[:space:]]Executive,[[:space:]]Dubai.pdf filter=lfs diff=lfs merge=lfs -text
37
  Docs/RCEM_BPC_Procedural_Sedation_Final_Aug_22_10772cef06[[:space:]](1).pdf filter=lfs diff=lfs merge=lfs -text
38
  Docs/RCEM_BPC_Procedural_Sedation_Final_Aug_22_10772cef06.pdf filter=lfs diff=lfs merge=lfs -text
39
+ Lib/site-packages/_soundfile_data/libsndfile_64bit.dll filter=lfs diff=lfs merge=lfs -text
40
+ Lib/site-packages/altair/vegalite/v5/schema/__pycache__/core.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
41
+ Lib/site-packages/gradio/frpc_windows_amd64_v0.2 filter=lfs diff=lfs merge=lfs -text
42
+ Lib/site-packages/gradio/templates/cdn/assets/index-d9794b8f.js.map filter=lfs diff=lfs merge=lfs -text
43
+ Lib/site-packages/gradio/templates/frontend/assets/index-0eddd93f.js.map filter=lfs diff=lfs merge=lfs -text
44
+ Lib/site-packages/lxml/etree.cp311-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
45
+ Lib/site-packages/lxml/objectify.cp311-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
46
+ Lib/site-packages/numpy/.libs/libopenblas64__v0.3.23-gcc_10_3_0.dll filter=lfs diff=lfs merge=lfs -text
47
+ Lib/site-packages/numpy/core/_multiarray_umath.cp311-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
48
+ Lib/site-packages/numpy/core/_simd.cp311-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
49
+ Lib/site-packages/pandas/_libs/algos.cp311-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
50
+ Lib/site-packages/pandas/_libs/groupby.cp311-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
51
+ Lib/site-packages/pandas/_libs/hashtable.cp311-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
52
+ Lib/site-packages/pandas/_libs/join.cp311-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
53
+ Lib/site-packages/PIL/_imaging.cp311-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
54
+ Lib/site-packages/PIL/_imagingft.cp311-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
55
+ Lib/site-packages/speech_recognition/flac-linux-x86 filter=lfs diff=lfs merge=lfs -text
56
+ Lib/site-packages/speech_recognition/flac-linux-x86_64 filter=lfs diff=lfs merge=lfs -text
57
+ Lib/site-packages/speech_recognition/pocketsphinx-data/en-US/acoustic-model/mdef filter=lfs diff=lfs merge=lfs -text
58
+ Lib/site-packages/speech_recognition/pocketsphinx-data/en-US/acoustic-model/sendump filter=lfs diff=lfs merge=lfs -text
59
+ Lib/site-packages/sympy/polys/benchmarks/__pycache__/bench_solvers.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
60
+ Lib/site-packages/tiktoken/_tiktoken.cp311-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
61
+ Lib/site-packages/tokenizers/tokenizers.cp311-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
62
+ Lib/site-packages/torch/bin/fbgemm.dll filter=lfs diff=lfs merge=lfs -text
63
+ Lib/site-packages/torch/bin/protoc.exe filter=lfs diff=lfs merge=lfs -text
64
+ Lib/site-packages/torch/lib/dnnl.lib filter=lfs diff=lfs merge=lfs -text
65
+ Lib/site-packages/torch/lib/fbgemm.dll filter=lfs diff=lfs merge=lfs -text
66
+ Lib/site-packages/torch/lib/fbgemm.lib filter=lfs diff=lfs merge=lfs -text
67
+ Lib/site-packages/torch/lib/kineto.lib filter=lfs diff=lfs merge=lfs -text
68
+ Lib/site-packages/torch/lib/libiomp5md.dll filter=lfs diff=lfs merge=lfs -text
69
+ Lib/site-packages/torch/lib/libprotobuf-lite.lib filter=lfs diff=lfs merge=lfs -text
70
+ Lib/site-packages/torch/lib/libprotobuf.lib filter=lfs diff=lfs merge=lfs -text
71
+ Lib/site-packages/torch/lib/libprotoc.lib filter=lfs diff=lfs merge=lfs -text
72
+ Lib/site-packages/torch/lib/torch_cpu.dll filter=lfs diff=lfs merge=lfs -text
73
+ Lib/site-packages/torch/lib/torch_cpu.lib filter=lfs diff=lfs merge=lfs -text
74
+ Lib/site-packages/torch/lib/torch_python.dll filter=lfs diff=lfs merge=lfs -text
75
+ Lib/site-packages/torch/lib/XNNPACK.lib filter=lfs diff=lfs merge=lfs -text
Docs/General.txt CHANGED
@@ -703,3 +703,6 @@ Jerry Tylor is a 56-year-old male who presented to the emergency department with
703
  General:
704
  Jerry Tylor is a 56-year-old male who presented to the emergency department with sudden onset of severe chest pain. He has a history of hypertension and type 2 diabetes, and is taking metformin 1000 mg twice daily and lisinopril 20 mg once daily.
705
 
 
 
 
 
703
  General:
704
  Jerry Tylor is a 56-year-old male who presented to the emergency department with sudden onset of severe chest pain. He has a history of hypertension and type 2 diabetes, and is taking metformin 1000 mg twice daily and lisinopril 20 mg once daily.
705
 
706
+ General:
707
+ Jerry Tylor is a 56-year-old male who presented to the emergency department with sudden onset of severe chest pain.
708
+
Include/site/python3.11/greenlet/greenlet.h ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* -*- indent-tabs-mode: nil; tab-width: 4; -*- */
2
+
3
+ /* Greenlet object interface */
4
+
5
+ #ifndef Py_GREENLETOBJECT_H
6
+ #define Py_GREENLETOBJECT_H
7
+
8
+
9
+ #include <Python.h>
10
+
11
+ #ifdef __cplusplus
12
+ extern "C" {
13
+ #endif
14
+
15
+ /* This is deprecated and undocumented. It does not change. */
16
+ #define GREENLET_VERSION "1.0.0"
17
+
18
+ #ifndef GREENLET_MODULE
19
+ #define implementation_ptr_t void*
20
+ #endif
21
+
22
+ typedef struct _greenlet {
23
+ PyObject_HEAD
24
+ PyObject* weakreflist;
25
+ PyObject* dict;
26
+ implementation_ptr_t pimpl;
27
+ } PyGreenlet;
28
+
29
+ #define PyGreenlet_Check(op) (op && PyObject_TypeCheck(op, &PyGreenlet_Type))
30
+
31
+
32
+ /* C API functions */
33
+
34
+ /* Total number of symbols that are exported */
35
+ #define PyGreenlet_API_pointers 12
36
+
37
+ #define PyGreenlet_Type_NUM 0
38
+ #define PyExc_GreenletError_NUM 1
39
+ #define PyExc_GreenletExit_NUM 2
40
+
41
+ #define PyGreenlet_New_NUM 3
42
+ #define PyGreenlet_GetCurrent_NUM 4
43
+ #define PyGreenlet_Throw_NUM 5
44
+ #define PyGreenlet_Switch_NUM 6
45
+ #define PyGreenlet_SetParent_NUM 7
46
+
47
+ #define PyGreenlet_MAIN_NUM 8
48
+ #define PyGreenlet_STARTED_NUM 9
49
+ #define PyGreenlet_ACTIVE_NUM 10
50
+ #define PyGreenlet_GET_PARENT_NUM 11
51
+
52
+ #ifndef GREENLET_MODULE
53
+ /* This section is used by modules that uses the greenlet C API */
54
+ static void** _PyGreenlet_API = NULL;
55
+
56
+ # define PyGreenlet_Type \
57
+ (*(PyTypeObject*)_PyGreenlet_API[PyGreenlet_Type_NUM])
58
+
59
+ # define PyExc_GreenletError \
60
+ ((PyObject*)_PyGreenlet_API[PyExc_GreenletError_NUM])
61
+
62
+ # define PyExc_GreenletExit \
63
+ ((PyObject*)_PyGreenlet_API[PyExc_GreenletExit_NUM])
64
+
65
+ /*
66
+ * PyGreenlet_New(PyObject *args)
67
+ *
68
+ * greenlet.greenlet(run, parent=None)
69
+ */
70
+ # define PyGreenlet_New \
71
+ (*(PyGreenlet * (*)(PyObject * run, PyGreenlet * parent)) \
72
+ _PyGreenlet_API[PyGreenlet_New_NUM])
73
+
74
+ /*
75
+ * PyGreenlet_GetCurrent(void)
76
+ *
77
+ * greenlet.getcurrent()
78
+ */
79
+ # define PyGreenlet_GetCurrent \
80
+ (*(PyGreenlet * (*)(void)) _PyGreenlet_API[PyGreenlet_GetCurrent_NUM])
81
+
82
+ /*
83
+ * PyGreenlet_Throw(
84
+ * PyGreenlet *greenlet,
85
+ * PyObject *typ,
86
+ * PyObject *val,
87
+ * PyObject *tb)
88
+ *
89
+ * g.throw(...)
90
+ */
91
+ # define PyGreenlet_Throw \
92
+ (*(PyObject * (*)(PyGreenlet * self, \
93
+ PyObject * typ, \
94
+ PyObject * val, \
95
+ PyObject * tb)) \
96
+ _PyGreenlet_API[PyGreenlet_Throw_NUM])
97
+
98
+ /*
99
+ * PyGreenlet_Switch(PyGreenlet *greenlet, PyObject *args)
100
+ *
101
+ * g.switch(*args, **kwargs)
102
+ */
103
+ # define PyGreenlet_Switch \
104
+ (*(PyObject * \
105
+ (*)(PyGreenlet * greenlet, PyObject * args, PyObject * kwargs)) \
106
+ _PyGreenlet_API[PyGreenlet_Switch_NUM])
107
+
108
+ /*
109
+ * PyGreenlet_SetParent(PyObject *greenlet, PyObject *new_parent)
110
+ *
111
+ * g.parent = new_parent
112
+ */
113
+ # define PyGreenlet_SetParent \
114
+ (*(int (*)(PyGreenlet * greenlet, PyGreenlet * nparent)) \
115
+ _PyGreenlet_API[PyGreenlet_SetParent_NUM])
116
+
117
+ /*
118
+ * PyGreenlet_GetParent(PyObject* greenlet)
119
+ *
120
+ * return greenlet.parent;
121
+ *
122
+ * This could return NULL even if there is no exception active.
123
+ * If it does not return NULL, you are responsible for decrementing the
124
+ * reference count.
125
+ */
126
+ # define PyGreenlet_GetParent \
127
+ (*(PyGreenlet* (*)(PyGreenlet*)) \
128
+ _PyGreenlet_API[PyGreenlet_GET_PARENT_NUM])
129
+
130
+ /*
131
+ * deprecated, undocumented alias.
132
+ */
133
+ # define PyGreenlet_GET_PARENT PyGreenlet_GetParent
134
+
135
+ # define PyGreenlet_MAIN \
136
+ (*(int (*)(PyGreenlet*)) \
137
+ _PyGreenlet_API[PyGreenlet_MAIN_NUM])
138
+
139
+ # define PyGreenlet_STARTED \
140
+ (*(int (*)(PyGreenlet*)) \
141
+ _PyGreenlet_API[PyGreenlet_STARTED_NUM])
142
+
143
+ # define PyGreenlet_ACTIVE \
144
+ (*(int (*)(PyGreenlet*)) \
145
+ _PyGreenlet_API[PyGreenlet_ACTIVE_NUM])
146
+
147
+
148
+
149
+
150
+ /* Macro that imports greenlet and initializes C API */
151
+ /* NOTE: This has actually moved to ``greenlet._greenlet._C_API``, but we
152
+ keep the older definition to be sure older code that might have a copy of
153
+ the header still works. */
154
+ # define PyGreenlet_Import() \
155
+ { \
156
+ _PyGreenlet_API = (void**)PyCapsule_Import("greenlet._C_API", 0); \
157
+ }
158
+
159
+ #endif /* GREENLET_MODULE */
160
+
161
+ #ifdef __cplusplus
162
+ }
163
+ #endif
164
+ #endif /* !Py_GREENLETOBJECT_H */
Lib/site-packages/Jinja2-3.1.2.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
Lib/site-packages/Jinja2-3.1.2.dist-info/LICENSE.rst ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2007 Pallets
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are
5
+ met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright
8
+ notice, this list of conditions and the following disclaimer.
9
+
10
+ 2. Redistributions in binary form must reproduce the above copyright
11
+ notice, this list of conditions and the following disclaimer in the
12
+ documentation and/or other materials provided with the distribution.
13
+
14
+ 3. Neither the name of the copyright holder nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
21
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
24
+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Lib/site-packages/Jinja2-3.1.2.dist-info/METADATA ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: Jinja2
3
+ Version: 3.1.2
4
+ Summary: A very fast and expressive template engine.
5
+ Home-page: https://palletsprojects.com/p/jinja/
6
+ Author: Armin Ronacher
7
+ Author-email: [email protected]
8
+ Maintainer: Pallets
9
+ Maintainer-email: [email protected]
10
+ License: BSD-3-Clause
11
+ Project-URL: Donate, https://palletsprojects.com/donate
12
+ Project-URL: Documentation, https://jinja.palletsprojects.com/
13
+ Project-URL: Changes, https://jinja.palletsprojects.com/changes/
14
+ Project-URL: Source Code, https://github.com/pallets/jinja/
15
+ Project-URL: Issue Tracker, https://github.com/pallets/jinja/issues/
16
+ Project-URL: Twitter, https://twitter.com/PalletsTeam
17
+ Project-URL: Chat, https://discord.gg/pallets
18
+ Platform: UNKNOWN
19
+ Classifier: Development Status :: 5 - Production/Stable
20
+ Classifier: Environment :: Web Environment
21
+ Classifier: Intended Audience :: Developers
22
+ Classifier: License :: OSI Approved :: BSD License
23
+ Classifier: Operating System :: OS Independent
24
+ Classifier: Programming Language :: Python
25
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
26
+ Classifier: Topic :: Text Processing :: Markup :: HTML
27
+ Requires-Python: >=3.7
28
+ Description-Content-Type: text/x-rst
29
+ License-File: LICENSE.rst
30
+ Requires-Dist: MarkupSafe (>=2.0)
31
+ Provides-Extra: i18n
32
+ Requires-Dist: Babel (>=2.7) ; extra == 'i18n'
33
+
34
+ Jinja
35
+ =====
36
+
37
+ Jinja is a fast, expressive, extensible templating engine. Special
38
+ placeholders in the template allow writing code similar to Python
39
+ syntax. Then the template is passed data to render the final document.
40
+
41
+ It includes:
42
+
43
+ - Template inheritance and inclusion.
44
+ - Define and import macros within templates.
45
+ - HTML templates can use autoescaping to prevent XSS from untrusted
46
+ user input.
47
+ - A sandboxed environment can safely render untrusted templates.
48
+ - AsyncIO support for generating templates and calling async
49
+ functions.
50
+ - I18N support with Babel.
51
+ - Templates are compiled to optimized Python code just-in-time and
52
+ cached, or can be compiled ahead-of-time.
53
+ - Exceptions point to the correct line in templates to make debugging
54
+ easier.
55
+ - Extensible filters, tests, functions, and even syntax.
56
+
57
+ Jinja's philosophy is that while application logic belongs in Python if
58
+ possible, it shouldn't make the template designer's job difficult by
59
+ restricting functionality too much.
60
+
61
+
62
+ Installing
63
+ ----------
64
+
65
+ Install and update using `pip`_:
66
+
67
+ .. code-block:: text
68
+
69
+ $ pip install -U Jinja2
70
+
71
+ .. _pip: https://pip.pypa.io/en/stable/getting-started/
72
+
73
+
74
+ In A Nutshell
75
+ -------------
76
+
77
+ .. code-block:: jinja
78
+
79
+ {% extends "base.html" %}
80
+ {% block title %}Members{% endblock %}
81
+ {% block content %}
82
+ <ul>
83
+ {% for user in users %}
84
+ <li><a href="{{ user.url }}">{{ user.username }}</a></li>
85
+ {% endfor %}
86
+ </ul>
87
+ {% endblock %}
88
+
89
+
90
+ Donate
91
+ ------
92
+
93
+ The Pallets organization develops and supports Jinja and other popular
94
+ packages. In order to grow the community of contributors and users, and
95
+ allow the maintainers to devote more time to the projects, `please
96
+ donate today`_.
97
+
98
+ .. _please donate today: https://palletsprojects.com/donate
99
+
100
+
101
+ Links
102
+ -----
103
+
104
+ - Documentation: https://jinja.palletsprojects.com/
105
+ - Changes: https://jinja.palletsprojects.com/changes/
106
+ - PyPI Releases: https://pypi.org/project/Jinja2/
107
+ - Source Code: https://github.com/pallets/jinja/
108
+ - Issue Tracker: https://github.com/pallets/jinja/issues/
109
+ - Website: https://palletsprojects.com/p/jinja/
110
+ - Twitter: https://twitter.com/PalletsTeam
111
+ - Chat: https://discord.gg/pallets
112
+
113
+
Lib/site-packages/Jinja2-3.1.2.dist-info/RECORD ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Jinja2-3.1.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ Jinja2-3.1.2.dist-info/LICENSE.rst,sha256=O0nc7kEF6ze6wQ-vG-JgQI_oXSUrjp3y4JefweCUQ3s,1475
3
+ Jinja2-3.1.2.dist-info/METADATA,sha256=PZ6v2SIidMNixR7MRUX9f7ZWsPwtXanknqiZUmRbh4U,3539
4
+ Jinja2-3.1.2.dist-info/RECORD,,
5
+ Jinja2-3.1.2.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92
6
+ Jinja2-3.1.2.dist-info/entry_points.txt,sha256=zRd62fbqIyfUpsRtU7EVIFyiu1tPwfgO7EvPErnxgTE,59
7
+ Jinja2-3.1.2.dist-info/top_level.txt,sha256=PkeVWtLb3-CqjWi1fO29OCbj55EhX_chhKrCdrVe_zs,7
8
+ jinja2/__init__.py,sha256=8vGduD8ytwgD6GDSqpYc2m3aU-T7PKOAddvVXgGr_Fs,1927
9
+ jinja2/__pycache__/__init__.cpython-311.pyc,,
10
+ jinja2/__pycache__/_identifier.cpython-311.pyc,,
11
+ jinja2/__pycache__/async_utils.cpython-311.pyc,,
12
+ jinja2/__pycache__/bccache.cpython-311.pyc,,
13
+ jinja2/__pycache__/compiler.cpython-311.pyc,,
14
+ jinja2/__pycache__/constants.cpython-311.pyc,,
15
+ jinja2/__pycache__/debug.cpython-311.pyc,,
16
+ jinja2/__pycache__/defaults.cpython-311.pyc,,
17
+ jinja2/__pycache__/environment.cpython-311.pyc,,
18
+ jinja2/__pycache__/exceptions.cpython-311.pyc,,
19
+ jinja2/__pycache__/ext.cpython-311.pyc,,
20
+ jinja2/__pycache__/filters.cpython-311.pyc,,
21
+ jinja2/__pycache__/idtracking.cpython-311.pyc,,
22
+ jinja2/__pycache__/lexer.cpython-311.pyc,,
23
+ jinja2/__pycache__/loaders.cpython-311.pyc,,
24
+ jinja2/__pycache__/meta.cpython-311.pyc,,
25
+ jinja2/__pycache__/nativetypes.cpython-311.pyc,,
26
+ jinja2/__pycache__/nodes.cpython-311.pyc,,
27
+ jinja2/__pycache__/optimizer.cpython-311.pyc,,
28
+ jinja2/__pycache__/parser.cpython-311.pyc,,
29
+ jinja2/__pycache__/runtime.cpython-311.pyc,,
30
+ jinja2/__pycache__/sandbox.cpython-311.pyc,,
31
+ jinja2/__pycache__/tests.cpython-311.pyc,,
32
+ jinja2/__pycache__/utils.cpython-311.pyc,,
33
+ jinja2/__pycache__/visitor.cpython-311.pyc,,
34
+ jinja2/_identifier.py,sha256=_zYctNKzRqlk_murTNlzrju1FFJL7Va_Ijqqd7ii2lU,1958
35
+ jinja2/async_utils.py,sha256=dHlbTeaxFPtAOQEYOGYh_PHcDT0rsDaUJAFDl_0XtTg,2472
36
+ jinja2/bccache.py,sha256=mhz5xtLxCcHRAa56azOhphIAe19u1we0ojifNMClDio,14061
37
+ jinja2/compiler.py,sha256=Gs-N8ThJ7OWK4-reKoO8Wh1ZXz95MVphBKNVf75qBr8,72172
38
+ jinja2/constants.py,sha256=GMoFydBF_kdpaRKPoM5cl5MviquVRLVyZtfp5-16jg0,1433
39
+ jinja2/debug.py,sha256=iWJ432RadxJNnaMOPrjIDInz50UEgni3_HKuFXi2vuQ,6299
40
+ jinja2/defaults.py,sha256=boBcSw78h-lp20YbaXSJsqkAI2uN_mD_TtCydpeq5wU,1267
41
+ jinja2/environment.py,sha256=6uHIcc7ZblqOMdx_uYNKqRnnwAF0_nzbyeMP9FFtuh4,61349
42
+ jinja2/exceptions.py,sha256=ioHeHrWwCWNaXX1inHmHVblvc4haO7AXsjCp3GfWvx0,5071
43
+ jinja2/ext.py,sha256=ivr3P7LKbddiXDVez20EflcO3q2aHQwz9P_PgWGHVqE,31502
44
+ jinja2/filters.py,sha256=9js1V-h2RlyW90IhLiBGLM2U-k6SCy2F4BUUMgB3K9Q,53509
45
+ jinja2/idtracking.py,sha256=GfNmadir4oDALVxzn3DL9YInhJDr69ebXeA2ygfuCGA,10704
46
+ jinja2/lexer.py,sha256=DW2nX9zk-6MWp65YR2bqqj0xqCvLtD-u9NWT8AnFRxQ,29726
47
+ jinja2/loaders.py,sha256=BfptfvTVpClUd-leMkHczdyPNYFzp_n7PKOJ98iyHOg,23207
48
+ jinja2/meta.py,sha256=GNPEvifmSaU3CMxlbheBOZjeZ277HThOPUTf1RkppKQ,4396
49
+ jinja2/nativetypes.py,sha256=DXgORDPRmVWgy034H0xL8eF7qYoK3DrMxs-935d0Fzk,4226
50
+ jinja2/nodes.py,sha256=i34GPRAZexXMT6bwuf5SEyvdmS-bRCy9KMjwN5O6pjk,34550
51
+ jinja2/optimizer.py,sha256=tHkMwXxfZkbfA1KmLcqmBMSaz7RLIvvItrJcPoXTyD8,1650
52
+ jinja2/parser.py,sha256=nHd-DFHbiygvfaPtm9rcQXJChZG7DPsWfiEsqfwKerY,39595
53
+ jinja2/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
54
+ jinja2/runtime.py,sha256=5CmD5BjbEJxSiDNTFBeKCaq8qU4aYD2v6q2EluyExms,33476
55
+ jinja2/sandbox.py,sha256=Y0xZeXQnH6EX5VjaV2YixESxoepnRbW_3UeQosaBU3M,14584
56
+ jinja2/tests.py,sha256=Am5Z6Lmfr2XaH_npIfJJ8MdXtWsbLjMULZJulTAj30E,5905
57
+ jinja2/utils.py,sha256=u9jXESxGn8ATZNVolwmkjUVu4SA-tLgV0W7PcSfPfdQ,23965
58
+ jinja2/visitor.py,sha256=MH14C6yq24G_KVtWzjwaI7Wg14PCJIYlWW1kpkxYak0,3568
Lib/site-packages/Jinja2-3.1.2.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.37.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
Lib/site-packages/Jinja2-3.1.2.dist-info/entry_points.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [babel.extractors]
2
+ jinja2 = jinja2.ext:babel_extract[i18n]
Lib/site-packages/Jinja2-3.1.2.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ jinja2
Lib/site-packages/MarkupSafe-2.1.3.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
Lib/site-packages/MarkupSafe-2.1.3.dist-info/LICENSE.rst ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2010 Pallets
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are
5
+ met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright
8
+ notice, this list of conditions and the following disclaimer.
9
+
10
+ 2. Redistributions in binary form must reproduce the above copyright
11
+ notice, this list of conditions and the following disclaimer in the
12
+ documentation and/or other materials provided with the distribution.
13
+
14
+ 3. Neither the name of the copyright holder nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
21
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
24
+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Lib/site-packages/MarkupSafe-2.1.3.dist-info/METADATA ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: MarkupSafe
3
+ Version: 2.1.3
4
+ Summary: Safely add untrusted strings to HTML/XML markup.
5
+ Home-page: https://palletsprojects.com/p/markupsafe/
6
+ Maintainer: Pallets
7
+ Maintainer-email: [email protected]
8
+ License: BSD-3-Clause
9
+ Project-URL: Donate, https://palletsprojects.com/donate
10
+ Project-URL: Documentation, https://markupsafe.palletsprojects.com/
11
+ Project-URL: Changes, https://markupsafe.palletsprojects.com/changes/
12
+ Project-URL: Source Code, https://github.com/pallets/markupsafe/
13
+ Project-URL: Issue Tracker, https://github.com/pallets/markupsafe/issues/
14
+ Project-URL: Chat, https://discord.gg/pallets
15
+ Classifier: Development Status :: 5 - Production/Stable
16
+ Classifier: Environment :: Web Environment
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: License :: OSI Approved :: BSD License
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Programming Language :: Python
21
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
22
+ Classifier: Topic :: Text Processing :: Markup :: HTML
23
+ Requires-Python: >=3.7
24
+ Description-Content-Type: text/x-rst
25
+ License-File: LICENSE.rst
26
+
27
+ MarkupSafe
28
+ ==========
29
+
30
+ MarkupSafe implements a text object that escapes characters so it is
31
+ safe to use in HTML and XML. Characters that have special meanings are
32
+ replaced so that they display as the actual characters. This mitigates
33
+ injection attacks, meaning untrusted user input can safely be displayed
34
+ on a page.
35
+
36
+
37
+ Installing
38
+ ----------
39
+
40
+ Install and update using `pip`_:
41
+
42
+ .. code-block:: text
43
+
44
+ pip install -U MarkupSafe
45
+
46
+ .. _pip: https://pip.pypa.io/en/stable/getting-started/
47
+
48
+
49
+ Examples
50
+ --------
51
+
52
+ .. code-block:: pycon
53
+
54
+ >>> from markupsafe import Markup, escape
55
+
56
+ >>> # escape replaces special characters and wraps in Markup
57
+ >>> escape("<script>alert(document.cookie);</script>")
58
+ Markup('&lt;script&gt;alert(document.cookie);&lt;/script&gt;')
59
+
60
+ >>> # wrap in Markup to mark text "safe" and prevent escaping
61
+ >>> Markup("<strong>Hello</strong>")
62
+ Markup('<strong>hello</strong>')
63
+
64
+ >>> escape(Markup("<strong>Hello</strong>"))
65
+ Markup('<strong>hello</strong>')
66
+
67
+ >>> # Markup is a str subclass
68
+ >>> # methods and operators escape their arguments
69
+ >>> template = Markup("Hello <em>{name}</em>")
70
+ >>> template.format(name='"World"')
71
+ Markup('Hello <em>&#34;World&#34;</em>')
72
+
73
+
74
+ Donate
75
+ ------
76
+
77
+ The Pallets organization develops and supports MarkupSafe and other
78
+ popular packages. In order to grow the community of contributors and
79
+ users, and allow the maintainers to devote more time to the projects,
80
+ `please donate today`_.
81
+
82
+ .. _please donate today: https://palletsprojects.com/donate
83
+
84
+
85
+ Links
86
+ -----
87
+
88
+ - Documentation: https://markupsafe.palletsprojects.com/
89
+ - Changes: https://markupsafe.palletsprojects.com/changes/
90
+ - PyPI Releases: https://pypi.org/project/MarkupSafe/
91
+ - Source Code: https://github.com/pallets/markupsafe/
92
+ - Issue Tracker: https://github.com/pallets/markupsafe/issues/
93
+ - Chat: https://discord.gg/pallets
Lib/site-packages/MarkupSafe-2.1.3.dist-info/RECORD ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MarkupSafe-2.1.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ MarkupSafe-2.1.3.dist-info/LICENSE.rst,sha256=RjHsDbX9kKVH4zaBcmTGeYIUM4FG-KyUtKV_lu6MnsQ,1503
3
+ MarkupSafe-2.1.3.dist-info/METADATA,sha256=5gU_TQw6eHpTaqkI6SPeZje6KTPlJPAV82uNiL3naKE,3096
4
+ MarkupSafe-2.1.3.dist-info/RECORD,,
5
+ MarkupSafe-2.1.3.dist-info/WHEEL,sha256=9wvhO-5NhjjD8YmmxAvXTPQXMDOZ50W5vklzeoqFtkM,102
6
+ MarkupSafe-2.1.3.dist-info/top_level.txt,sha256=qy0Plje5IJuvsCBjejJyhDCjEAdcDLK_2agVcex8Z6U,11
7
+ markupsafe/__init__.py,sha256=GsRaSTjrhvg6c88PnPJNqm4MafU_mFatfXz4-h80-Qc,10642
8
+ markupsafe/__pycache__/__init__.cpython-311.pyc,,
9
+ markupsafe/__pycache__/_native.cpython-311.pyc,,
10
+ markupsafe/_native.py,sha256=_Q7UsXCOvgdonCgqG3l5asANI6eo50EKnDM-mlwEC5M,1776
11
+ markupsafe/_speedups.c,sha256=n3jzzaJwXcoN8nTFyA53f3vSqsWK2vujI-v6QYifjhQ,7403
12
+ markupsafe/_speedups.cp311-win_amd64.pyd,sha256=TEUZdBQBxs061oYZQP2cGGlADVOAdHridgTeE6XQxTE,15872
13
+ markupsafe/_speedups.pyi,sha256=f5QtwIOP0eLrxh2v5p6SmaYmlcHIGIfmz0DovaqL0OU,238
14
+ markupsafe/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
Lib/site-packages/MarkupSafe-2.1.3.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.40.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp311-cp311-win_amd64
5
+
Lib/site-packages/MarkupSafe-2.1.3.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ markupsafe
Lib/site-packages/PIL/BdfFontFile.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # bitmap distribution font (bdf) file parser
6
+ #
7
+ # history:
8
+ # 1996-05-16 fl created (as bdf2pil)
9
+ # 1997-08-25 fl converted to FontFile driver
10
+ # 2001-05-25 fl removed bogus __init__ call
11
+ # 2002-11-20 fl robustification (from Kevin Cazabon, Dmitry Vasiliev)
12
+ # 2003-04-22 fl more robustification (from Graham Dumpleton)
13
+ #
14
+ # Copyright (c) 1997-2003 by Secret Labs AB.
15
+ # Copyright (c) 1997-2003 by Fredrik Lundh.
16
+ #
17
+ # See the README file for information on usage and redistribution.
18
+ #
19
+
20
+ """
21
+ Parse X Bitmap Distribution Format (BDF)
22
+ """
23
+
24
+
25
+ from . import FontFile, Image
26
+
27
+ bdf_slant = {
28
+ "R": "Roman",
29
+ "I": "Italic",
30
+ "O": "Oblique",
31
+ "RI": "Reverse Italic",
32
+ "RO": "Reverse Oblique",
33
+ "OT": "Other",
34
+ }
35
+
36
+ bdf_spacing = {"P": "Proportional", "M": "Monospaced", "C": "Cell"}
37
+
38
+
39
+ def bdf_char(f):
40
+ # skip to STARTCHAR
41
+ while True:
42
+ s = f.readline()
43
+ if not s:
44
+ return None
45
+ if s[:9] == b"STARTCHAR":
46
+ break
47
+ id = s[9:].strip().decode("ascii")
48
+
49
+ # load symbol properties
50
+ props = {}
51
+ while True:
52
+ s = f.readline()
53
+ if not s or s[:6] == b"BITMAP":
54
+ break
55
+ i = s.find(b" ")
56
+ props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
57
+
58
+ # load bitmap
59
+ bitmap = []
60
+ while True:
61
+ s = f.readline()
62
+ if not s or s[:7] == b"ENDCHAR":
63
+ break
64
+ bitmap.append(s[:-1])
65
+ bitmap = b"".join(bitmap)
66
+
67
+ # The word BBX
68
+ # followed by the width in x (BBw), height in y (BBh),
69
+ # and x and y displacement (BBxoff0, BByoff0)
70
+ # of the lower left corner from the origin of the character.
71
+ width, height, x_disp, y_disp = [int(p) for p in props["BBX"].split()]
72
+
73
+ # The word DWIDTH
74
+ # followed by the width in x and y of the character in device pixels.
75
+ dwx, dwy = [int(p) for p in props["DWIDTH"].split()]
76
+
77
+ bbox = (
78
+ (dwx, dwy),
79
+ (x_disp, -y_disp - height, width + x_disp, -y_disp),
80
+ (0, 0, width, height),
81
+ )
82
+
83
+ try:
84
+ im = Image.frombytes("1", (width, height), bitmap, "hex", "1")
85
+ except ValueError:
86
+ # deal with zero-width characters
87
+ im = Image.new("1", (width, height))
88
+
89
+ return id, int(props["ENCODING"]), bbox, im
90
+
91
+
92
+ class BdfFontFile(FontFile.FontFile):
93
+ """Font file plugin for the X11 BDF format."""
94
+
95
+ def __init__(self, fp):
96
+ super().__init__()
97
+
98
+ s = fp.readline()
99
+ if s[:13] != b"STARTFONT 2.1":
100
+ msg = "not a valid BDF file"
101
+ raise SyntaxError(msg)
102
+
103
+ props = {}
104
+ comments = []
105
+
106
+ while True:
107
+ s = fp.readline()
108
+ if not s or s[:13] == b"ENDPROPERTIES":
109
+ break
110
+ i = s.find(b" ")
111
+ props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
112
+ if s[:i] in [b"COMMENT", b"COPYRIGHT"]:
113
+ if s.find(b"LogicalFontDescription") < 0:
114
+ comments.append(s[i + 1 : -1].decode("ascii"))
115
+
116
+ while True:
117
+ c = bdf_char(fp)
118
+ if not c:
119
+ break
120
+ id, ch, (xy, dst, src), im = c
121
+ if 0 <= ch < len(self.glyph):
122
+ self.glyph[ch] = xy, dst, src, im
Lib/site-packages/PIL/BlpImagePlugin.py ADDED
@@ -0,0 +1,472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Blizzard Mipmap Format (.blp)
3
+ Jerome Leclanche <[email protected]>
4
+
5
+ The contents of this file are hereby released in the public domain (CC0)
6
+ Full text of the CC0 license:
7
+ https://creativecommons.org/publicdomain/zero/1.0/
8
+
9
+ BLP1 files, used mostly in Warcraft III, are not fully supported.
10
+ All types of BLP2 files used in World of Warcraft are supported.
11
+
12
+ The BLP file structure consists of a header, up to 16 mipmaps of the
13
+ texture
14
+
15
+ Texture sizes must be powers of two, though the two dimensions do
16
+ not have to be equal; 512x256 is valid, but 512x200 is not.
17
+ The first mipmap (mipmap #0) is the full size image; each subsequent
18
+ mipmap halves both dimensions. The final mipmap should be 1x1.
19
+
20
+ BLP files come in many different flavours:
21
+ * JPEG-compressed (type == 0) - only supported for BLP1.
22
+ * RAW images (type == 1, encoding == 1). Each mipmap is stored as an
23
+ array of 8-bit values, one per pixel, left to right, top to bottom.
24
+ Each value is an index to the palette.
25
+ * DXT-compressed (type == 1, encoding == 2):
26
+ - DXT1 compression is used if alpha_encoding == 0.
27
+ - An additional alpha bit is used if alpha_depth == 1.
28
+ - DXT3 compression is used if alpha_encoding == 1.
29
+ - DXT5 compression is used if alpha_encoding == 7.
30
+ """
31
+
32
+ import os
33
+ import struct
34
+ from enum import IntEnum
35
+ from io import BytesIO
36
+
37
+ from . import Image, ImageFile
38
+
39
+
40
+ class Format(IntEnum):
41
+ JPEG = 0
42
+
43
+
44
+ class Encoding(IntEnum):
45
+ UNCOMPRESSED = 1
46
+ DXT = 2
47
+ UNCOMPRESSED_RAW_BGRA = 3
48
+
49
+
50
+ class AlphaEncoding(IntEnum):
51
+ DXT1 = 0
52
+ DXT3 = 1
53
+ DXT5 = 7
54
+
55
+
56
+ def unpack_565(i):
57
+ return ((i >> 11) & 0x1F) << 3, ((i >> 5) & 0x3F) << 2, (i & 0x1F) << 3
58
+
59
+
60
+ def decode_dxt1(data, alpha=False):
61
+ """
62
+ input: one "row" of data (i.e. will produce 4*width pixels)
63
+ """
64
+
65
+ blocks = len(data) // 8 # number of blocks in row
66
+ ret = (bytearray(), bytearray(), bytearray(), bytearray())
67
+
68
+ for block in range(blocks):
69
+ # Decode next 8-byte block.
70
+ idx = block * 8
71
+ color0, color1, bits = struct.unpack_from("<HHI", data, idx)
72
+
73
+ r0, g0, b0 = unpack_565(color0)
74
+ r1, g1, b1 = unpack_565(color1)
75
+
76
+ # Decode this block into 4x4 pixels
77
+ # Accumulate the results onto our 4 row accumulators
78
+ for j in range(4):
79
+ for i in range(4):
80
+ # get next control op and generate a pixel
81
+
82
+ control = bits & 3
83
+ bits = bits >> 2
84
+
85
+ a = 0xFF
86
+ if control == 0:
87
+ r, g, b = r0, g0, b0
88
+ elif control == 1:
89
+ r, g, b = r1, g1, b1
90
+ elif control == 2:
91
+ if color0 > color1:
92
+ r = (2 * r0 + r1) // 3
93
+ g = (2 * g0 + g1) // 3
94
+ b = (2 * b0 + b1) // 3
95
+ else:
96
+ r = (r0 + r1) // 2
97
+ g = (g0 + g1) // 2
98
+ b = (b0 + b1) // 2
99
+ elif control == 3:
100
+ if color0 > color1:
101
+ r = (2 * r1 + r0) // 3
102
+ g = (2 * g1 + g0) // 3
103
+ b = (2 * b1 + b0) // 3
104
+ else:
105
+ r, g, b, a = 0, 0, 0, 0
106
+
107
+ if alpha:
108
+ ret[j].extend([r, g, b, a])
109
+ else:
110
+ ret[j].extend([r, g, b])
111
+
112
+ return ret
113
+
114
+
115
+ def decode_dxt3(data):
116
+ """
117
+ input: one "row" of data (i.e. will produce 4*width pixels)
118
+ """
119
+
120
+ blocks = len(data) // 16 # number of blocks in row
121
+ ret = (bytearray(), bytearray(), bytearray(), bytearray())
122
+
123
+ for block in range(blocks):
124
+ idx = block * 16
125
+ block = data[idx : idx + 16]
126
+ # Decode next 16-byte block.
127
+ bits = struct.unpack_from("<8B", block)
128
+ color0, color1 = struct.unpack_from("<HH", block, 8)
129
+
130
+ (code,) = struct.unpack_from("<I", block, 12)
131
+
132
+ r0, g0, b0 = unpack_565(color0)
133
+ r1, g1, b1 = unpack_565(color1)
134
+
135
+ for j in range(4):
136
+ high = False # Do we want the higher bits?
137
+ for i in range(4):
138
+ alphacode_index = (4 * j + i) // 2
139
+ a = bits[alphacode_index]
140
+ if high:
141
+ high = False
142
+ a >>= 4
143
+ else:
144
+ high = True
145
+ a &= 0xF
146
+ a *= 17 # We get a value between 0 and 15
147
+
148
+ color_code = (code >> 2 * (4 * j + i)) & 0x03
149
+
150
+ if color_code == 0:
151
+ r, g, b = r0, g0, b0
152
+ elif color_code == 1:
153
+ r, g, b = r1, g1, b1
154
+ elif color_code == 2:
155
+ r = (2 * r0 + r1) // 3
156
+ g = (2 * g0 + g1) // 3
157
+ b = (2 * b0 + b1) // 3
158
+ elif color_code == 3:
159
+ r = (2 * r1 + r0) // 3
160
+ g = (2 * g1 + g0) // 3
161
+ b = (2 * b1 + b0) // 3
162
+
163
+ ret[j].extend([r, g, b, a])
164
+
165
+ return ret
166
+
167
+
168
+ def decode_dxt5(data):
169
+ """
170
+ input: one "row" of data (i.e. will produce 4 * width pixels)
171
+ """
172
+
173
+ blocks = len(data) // 16 # number of blocks in row
174
+ ret = (bytearray(), bytearray(), bytearray(), bytearray())
175
+
176
+ for block in range(blocks):
177
+ idx = block * 16
178
+ block = data[idx : idx + 16]
179
+ # Decode next 16-byte block.
180
+ a0, a1 = struct.unpack_from("<BB", block)
181
+
182
+ bits = struct.unpack_from("<6B", block, 2)
183
+ alphacode1 = bits[2] | (bits[3] << 8) | (bits[4] << 16) | (bits[5] << 24)
184
+ alphacode2 = bits[0] | (bits[1] << 8)
185
+
186
+ color0, color1 = struct.unpack_from("<HH", block, 8)
187
+
188
+ (code,) = struct.unpack_from("<I", block, 12)
189
+
190
+ r0, g0, b0 = unpack_565(color0)
191
+ r1, g1, b1 = unpack_565(color1)
192
+
193
+ for j in range(4):
194
+ for i in range(4):
195
+ # get next control op and generate a pixel
196
+ alphacode_index = 3 * (4 * j + i)
197
+
198
+ if alphacode_index <= 12:
199
+ alphacode = (alphacode2 >> alphacode_index) & 0x07
200
+ elif alphacode_index == 15:
201
+ alphacode = (alphacode2 >> 15) | ((alphacode1 << 1) & 0x06)
202
+ else: # alphacode_index >= 18 and alphacode_index <= 45
203
+ alphacode = (alphacode1 >> (alphacode_index - 16)) & 0x07
204
+
205
+ if alphacode == 0:
206
+ a = a0
207
+ elif alphacode == 1:
208
+ a = a1
209
+ elif a0 > a1:
210
+ a = ((8 - alphacode) * a0 + (alphacode - 1) * a1) // 7
211
+ elif alphacode == 6:
212
+ a = 0
213
+ elif alphacode == 7:
214
+ a = 255
215
+ else:
216
+ a = ((6 - alphacode) * a0 + (alphacode - 1) * a1) // 5
217
+
218
+ color_code = (code >> 2 * (4 * j + i)) & 0x03
219
+
220
+ if color_code == 0:
221
+ r, g, b = r0, g0, b0
222
+ elif color_code == 1:
223
+ r, g, b = r1, g1, b1
224
+ elif color_code == 2:
225
+ r = (2 * r0 + r1) // 3
226
+ g = (2 * g0 + g1) // 3
227
+ b = (2 * b0 + b1) // 3
228
+ elif color_code == 3:
229
+ r = (2 * r1 + r0) // 3
230
+ g = (2 * g1 + g0) // 3
231
+ b = (2 * b1 + b0) // 3
232
+
233
+ ret[j].extend([r, g, b, a])
234
+
235
+ return ret
236
+
237
+
238
+ class BLPFormatError(NotImplementedError):
239
+ pass
240
+
241
+
242
+ def _accept(prefix):
243
+ return prefix[:4] in (b"BLP1", b"BLP2")
244
+
245
+
246
+ class BlpImageFile(ImageFile.ImageFile):
247
+ """
248
+ Blizzard Mipmap Format
249
+ """
250
+
251
+ format = "BLP"
252
+ format_description = "Blizzard Mipmap Format"
253
+
254
+ def _open(self):
255
+ self.magic = self.fp.read(4)
256
+
257
+ self.fp.seek(5, os.SEEK_CUR)
258
+ (self._blp_alpha_depth,) = struct.unpack("<b", self.fp.read(1))
259
+
260
+ self.fp.seek(2, os.SEEK_CUR)
261
+ self._size = struct.unpack("<II", self.fp.read(8))
262
+
263
+ if self.magic in (b"BLP1", b"BLP2"):
264
+ decoder = self.magic.decode()
265
+ else:
266
+ msg = f"Bad BLP magic {repr(self.magic)}"
267
+ raise BLPFormatError(msg)
268
+
269
+ self.mode = "RGBA" if self._blp_alpha_depth else "RGB"
270
+ self.tile = [(decoder, (0, 0) + self.size, 0, (self.mode, 0, 1))]
271
+
272
+
273
+ class _BLPBaseDecoder(ImageFile.PyDecoder):
274
+ _pulls_fd = True
275
+
276
+ def decode(self, buffer):
277
+ try:
278
+ self._read_blp_header()
279
+ self._load()
280
+ except struct.error as e:
281
+ msg = "Truncated BLP file"
282
+ raise OSError(msg) from e
283
+ return -1, 0
284
+
285
+ def _read_blp_header(self):
286
+ self.fd.seek(4)
287
+ (self._blp_compression,) = struct.unpack("<i", self._safe_read(4))
288
+
289
+ (self._blp_encoding,) = struct.unpack("<b", self._safe_read(1))
290
+ (self._blp_alpha_depth,) = struct.unpack("<b", self._safe_read(1))
291
+ (self._blp_alpha_encoding,) = struct.unpack("<b", self._safe_read(1))
292
+ self.fd.seek(1, os.SEEK_CUR) # mips
293
+
294
+ self.size = struct.unpack("<II", self._safe_read(8))
295
+
296
+ if isinstance(self, BLP1Decoder):
297
+ # Only present for BLP1
298
+ (self._blp_encoding,) = struct.unpack("<i", self._safe_read(4))
299
+ self.fd.seek(4, os.SEEK_CUR) # subtype
300
+
301
+ self._blp_offsets = struct.unpack("<16I", self._safe_read(16 * 4))
302
+ self._blp_lengths = struct.unpack("<16I", self._safe_read(16 * 4))
303
+
304
+ def _safe_read(self, length):
305
+ return ImageFile._safe_read(self.fd, length)
306
+
307
+ def _read_palette(self):
308
+ ret = []
309
+ for i in range(256):
310
+ try:
311
+ b, g, r, a = struct.unpack("<4B", self._safe_read(4))
312
+ except struct.error:
313
+ break
314
+ ret.append((b, g, r, a))
315
+ return ret
316
+
317
+ def _read_bgra(self, palette):
318
+ data = bytearray()
319
+ _data = BytesIO(self._safe_read(self._blp_lengths[0]))
320
+ while True:
321
+ try:
322
+ (offset,) = struct.unpack("<B", _data.read(1))
323
+ except struct.error:
324
+ break
325
+ b, g, r, a = palette[offset]
326
+ d = (r, g, b)
327
+ if self._blp_alpha_depth:
328
+ d += (a,)
329
+ data.extend(d)
330
+ return data
331
+
332
+
333
+ class BLP1Decoder(_BLPBaseDecoder):
334
+ def _load(self):
335
+ if self._blp_compression == Format.JPEG:
336
+ self._decode_jpeg_stream()
337
+
338
+ elif self._blp_compression == 1:
339
+ if self._blp_encoding in (4, 5):
340
+ palette = self._read_palette()
341
+ data = self._read_bgra(palette)
342
+ self.set_as_raw(bytes(data))
343
+ else:
344
+ msg = f"Unsupported BLP encoding {repr(self._blp_encoding)}"
345
+ raise BLPFormatError(msg)
346
+ else:
347
+ msg = f"Unsupported BLP compression {repr(self._blp_encoding)}"
348
+ raise BLPFormatError(msg)
349
+
350
+ def _decode_jpeg_stream(self):
351
+ from .JpegImagePlugin import JpegImageFile
352
+
353
+ (jpeg_header_size,) = struct.unpack("<I", self._safe_read(4))
354
+ jpeg_header = self._safe_read(jpeg_header_size)
355
+ self._safe_read(self._blp_offsets[0] - self.fd.tell()) # What IS this?
356
+ data = self._safe_read(self._blp_lengths[0])
357
+ data = jpeg_header + data
358
+ data = BytesIO(data)
359
+ image = JpegImageFile(data)
360
+ Image._decompression_bomb_check(image.size)
361
+ if image.mode == "CMYK":
362
+ decoder_name, extents, offset, args = image.tile[0]
363
+ image.tile = [(decoder_name, extents, offset, (args[0], "CMYK"))]
364
+ r, g, b = image.convert("RGB").split()
365
+ image = Image.merge("RGB", (b, g, r))
366
+ self.set_as_raw(image.tobytes())
367
+
368
+
369
+ class BLP2Decoder(_BLPBaseDecoder):
370
+ def _load(self):
371
+ palette = self._read_palette()
372
+
373
+ self.fd.seek(self._blp_offsets[0])
374
+
375
+ if self._blp_compression == 1:
376
+ # Uncompressed or DirectX compression
377
+
378
+ if self._blp_encoding == Encoding.UNCOMPRESSED:
379
+ data = self._read_bgra(palette)
380
+
381
+ elif self._blp_encoding == Encoding.DXT:
382
+ data = bytearray()
383
+ if self._blp_alpha_encoding == AlphaEncoding.DXT1:
384
+ linesize = (self.size[0] + 3) // 4 * 8
385
+ for yb in range((self.size[1] + 3) // 4):
386
+ for d in decode_dxt1(
387
+ self._safe_read(linesize), alpha=bool(self._blp_alpha_depth)
388
+ ):
389
+ data += d
390
+
391
+ elif self._blp_alpha_encoding == AlphaEncoding.DXT3:
392
+ linesize = (self.size[0] + 3) // 4 * 16
393
+ for yb in range((self.size[1] + 3) // 4):
394
+ for d in decode_dxt3(self._safe_read(linesize)):
395
+ data += d
396
+
397
+ elif self._blp_alpha_encoding == AlphaEncoding.DXT5:
398
+ linesize = (self.size[0] + 3) // 4 * 16
399
+ for yb in range((self.size[1] + 3) // 4):
400
+ for d in decode_dxt5(self._safe_read(linesize)):
401
+ data += d
402
+ else:
403
+ msg = f"Unsupported alpha encoding {repr(self._blp_alpha_encoding)}"
404
+ raise BLPFormatError(msg)
405
+ else:
406
+ msg = f"Unknown BLP encoding {repr(self._blp_encoding)}"
407
+ raise BLPFormatError(msg)
408
+
409
+ else:
410
+ msg = f"Unknown BLP compression {repr(self._blp_compression)}"
411
+ raise BLPFormatError(msg)
412
+
413
+ self.set_as_raw(bytes(data))
414
+
415
+
416
+ class BLPEncoder(ImageFile.PyEncoder):
417
+ _pushes_fd = True
418
+
419
+ def _write_palette(self):
420
+ data = b""
421
+ palette = self.im.getpalette("RGBA", "RGBA")
422
+ for i in range(256):
423
+ r, g, b, a = palette[i * 4 : (i + 1) * 4]
424
+ data += struct.pack("<4B", b, g, r, a)
425
+ return data
426
+
427
+ def encode(self, bufsize):
428
+ palette_data = self._write_palette()
429
+
430
+ offset = 20 + 16 * 4 * 2 + len(palette_data)
431
+ data = struct.pack("<16I", offset, *((0,) * 15))
432
+
433
+ w, h = self.im.size
434
+ data += struct.pack("<16I", w * h, *((0,) * 15))
435
+
436
+ data += palette_data
437
+
438
+ for y in range(h):
439
+ for x in range(w):
440
+ data += struct.pack("<B", self.im.getpixel((x, y)))
441
+
442
+ return len(data), 0, data
443
+
444
+
445
+ def _save(im, fp, filename, save_all=False):
446
+ if im.mode != "P":
447
+ msg = "Unsupported BLP image mode"
448
+ raise ValueError(msg)
449
+
450
+ magic = b"BLP1" if im.encoderinfo.get("blp_version") == "BLP1" else b"BLP2"
451
+ fp.write(magic)
452
+
453
+ fp.write(struct.pack("<i", 1)) # Uncompressed or DirectX compression
454
+ fp.write(struct.pack("<b", Encoding.UNCOMPRESSED))
455
+ fp.write(struct.pack("<b", 1 if im.palette.mode == "RGBA" else 0))
456
+ fp.write(struct.pack("<b", 0)) # alpha encoding
457
+ fp.write(struct.pack("<b", 0)) # mips
458
+ fp.write(struct.pack("<II", *im.size))
459
+ if magic == b"BLP1":
460
+ fp.write(struct.pack("<i", 5))
461
+ fp.write(struct.pack("<i", 0))
462
+
463
+ ImageFile._save(im, fp, [("BLP", (0, 0) + im.size, 0, im.mode)])
464
+
465
+
466
+ Image.register_open(BlpImageFile.format, BlpImageFile, _accept)
467
+ Image.register_extension(BlpImageFile.format, ".blp")
468
+ Image.register_decoder("BLP1", BLP1Decoder)
469
+ Image.register_decoder("BLP2", BLP2Decoder)
470
+
471
+ Image.register_save(BlpImageFile.format, _save)
472
+ Image.register_encoder("BLP", BLPEncoder)
Lib/site-packages/PIL/BmpImagePlugin.py ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # BMP file handler
6
+ #
7
+ # Windows (and OS/2) native bitmap storage format.
8
+ #
9
+ # history:
10
+ # 1995-09-01 fl Created
11
+ # 1996-04-30 fl Added save
12
+ # 1997-08-27 fl Fixed save of 1-bit images
13
+ # 1998-03-06 fl Load P images as L where possible
14
+ # 1998-07-03 fl Load P images as 1 where possible
15
+ # 1998-12-29 fl Handle small palettes
16
+ # 2002-12-30 fl Fixed load of 1-bit palette images
17
+ # 2003-04-21 fl Fixed load of 1-bit monochrome images
18
+ # 2003-04-23 fl Added limited support for BI_BITFIELDS compression
19
+ #
20
+ # Copyright (c) 1997-2003 by Secret Labs AB
21
+ # Copyright (c) 1995-2003 by Fredrik Lundh
22
+ #
23
+ # See the README file for information on usage and redistribution.
24
+ #
25
+
26
+
27
+ import os
28
+
29
+ from . import Image, ImageFile, ImagePalette
30
+ from ._binary import i16le as i16
31
+ from ._binary import i32le as i32
32
+ from ._binary import o8
33
+ from ._binary import o16le as o16
34
+ from ._binary import o32le as o32
35
+
36
+ #
37
+ # --------------------------------------------------------------------
38
+ # Read BMP file
39
+
40
+ BIT2MODE = {
41
+ # bits => mode, rawmode
42
+ 1: ("P", "P;1"),
43
+ 4: ("P", "P;4"),
44
+ 8: ("P", "P"),
45
+ 16: ("RGB", "BGR;15"),
46
+ 24: ("RGB", "BGR"),
47
+ 32: ("RGB", "BGRX"),
48
+ }
49
+
50
+
51
+ def _accept(prefix):
52
+ return prefix[:2] == b"BM"
53
+
54
+
55
+ def _dib_accept(prefix):
56
+ return i32(prefix) in [12, 40, 64, 108, 124]
57
+
58
+
59
+ # =============================================================================
60
+ # Image plugin for the Windows BMP format.
61
+ # =============================================================================
62
+ class BmpImageFile(ImageFile.ImageFile):
63
+ """Image plugin for the Windows Bitmap format (BMP)"""
64
+
65
+ # ------------------------------------------------------------- Description
66
+ format_description = "Windows Bitmap"
67
+ format = "BMP"
68
+
69
+ # -------------------------------------------------- BMP Compression values
70
+ COMPRESSIONS = {"RAW": 0, "RLE8": 1, "RLE4": 2, "BITFIELDS": 3, "JPEG": 4, "PNG": 5}
71
+ for k, v in COMPRESSIONS.items():
72
+ vars()[k] = v
73
+
74
+ def _bitmap(self, header=0, offset=0):
75
+ """Read relevant info about the BMP"""
76
+ read, seek = self.fp.read, self.fp.seek
77
+ if header:
78
+ seek(header)
79
+ # read bmp header size @offset 14 (this is part of the header size)
80
+ file_info = {"header_size": i32(read(4)), "direction": -1}
81
+
82
+ # -------------------- If requested, read header at a specific position
83
+ # read the rest of the bmp header, without its size
84
+ header_data = ImageFile._safe_read(self.fp, file_info["header_size"] - 4)
85
+
86
+ # -------------------------------------------------- IBM OS/2 Bitmap v1
87
+ # ----- This format has different offsets because of width/height types
88
+ if file_info["header_size"] == 12:
89
+ file_info["width"] = i16(header_data, 0)
90
+ file_info["height"] = i16(header_data, 2)
91
+ file_info["planes"] = i16(header_data, 4)
92
+ file_info["bits"] = i16(header_data, 6)
93
+ file_info["compression"] = self.RAW
94
+ file_info["palette_padding"] = 3
95
+
96
+ # --------------------------------------------- Windows Bitmap v2 to v5
97
+ # v3, OS/2 v2, v4, v5
98
+ elif file_info["header_size"] in (40, 64, 108, 124):
99
+ file_info["y_flip"] = header_data[7] == 0xFF
100
+ file_info["direction"] = 1 if file_info["y_flip"] else -1
101
+ file_info["width"] = i32(header_data, 0)
102
+ file_info["height"] = (
103
+ i32(header_data, 4)
104
+ if not file_info["y_flip"]
105
+ else 2**32 - i32(header_data, 4)
106
+ )
107
+ file_info["planes"] = i16(header_data, 8)
108
+ file_info["bits"] = i16(header_data, 10)
109
+ file_info["compression"] = i32(header_data, 12)
110
+ # byte size of pixel data
111
+ file_info["data_size"] = i32(header_data, 16)
112
+ file_info["pixels_per_meter"] = (
113
+ i32(header_data, 20),
114
+ i32(header_data, 24),
115
+ )
116
+ file_info["colors"] = i32(header_data, 28)
117
+ file_info["palette_padding"] = 4
118
+ self.info["dpi"] = tuple(x / 39.3701 for x in file_info["pixels_per_meter"])
119
+ if file_info["compression"] == self.BITFIELDS:
120
+ if len(header_data) >= 52:
121
+ for idx, mask in enumerate(
122
+ ["r_mask", "g_mask", "b_mask", "a_mask"]
123
+ ):
124
+ file_info[mask] = i32(header_data, 36 + idx * 4)
125
+ else:
126
+ # 40 byte headers only have the three components in the
127
+ # bitfields masks, ref:
128
+ # https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx
129
+ # See also
130
+ # https://github.com/python-pillow/Pillow/issues/1293
131
+ # There is a 4th component in the RGBQuad, in the alpha
132
+ # location, but it is listed as a reserved component,
133
+ # and it is not generally an alpha channel
134
+ file_info["a_mask"] = 0x0
135
+ for mask in ["r_mask", "g_mask", "b_mask"]:
136
+ file_info[mask] = i32(read(4))
137
+ file_info["rgb_mask"] = (
138
+ file_info["r_mask"],
139
+ file_info["g_mask"],
140
+ file_info["b_mask"],
141
+ )
142
+ file_info["rgba_mask"] = (
143
+ file_info["r_mask"],
144
+ file_info["g_mask"],
145
+ file_info["b_mask"],
146
+ file_info["a_mask"],
147
+ )
148
+ else:
149
+ msg = f"Unsupported BMP header type ({file_info['header_size']})"
150
+ raise OSError(msg)
151
+
152
+ # ------------------ Special case : header is reported 40, which
153
+ # ---------------------- is shorter than real size for bpp >= 16
154
+ self._size = file_info["width"], file_info["height"]
155
+
156
+ # ------- If color count was not found in the header, compute from bits
157
+ file_info["colors"] = (
158
+ file_info["colors"]
159
+ if file_info.get("colors", 0)
160
+ else (1 << file_info["bits"])
161
+ )
162
+ if offset == 14 + file_info["header_size"] and file_info["bits"] <= 8:
163
+ offset += 4 * file_info["colors"]
164
+
165
+ # ---------------------- Check bit depth for unusual unsupported values
166
+ self.mode, raw_mode = BIT2MODE.get(file_info["bits"], (None, None))
167
+ if self.mode is None:
168
+ msg = f"Unsupported BMP pixel depth ({file_info['bits']})"
169
+ raise OSError(msg)
170
+
171
+ # ---------------- Process BMP with Bitfields compression (not palette)
172
+ decoder_name = "raw"
173
+ if file_info["compression"] == self.BITFIELDS:
174
+ SUPPORTED = {
175
+ 32: [
176
+ (0xFF0000, 0xFF00, 0xFF, 0x0),
177
+ (0xFF000000, 0xFF0000, 0xFF00, 0x0),
178
+ (0xFF000000, 0xFF0000, 0xFF00, 0xFF),
179
+ (0xFF, 0xFF00, 0xFF0000, 0xFF000000),
180
+ (0xFF0000, 0xFF00, 0xFF, 0xFF000000),
181
+ (0x0, 0x0, 0x0, 0x0),
182
+ ],
183
+ 24: [(0xFF0000, 0xFF00, 0xFF)],
184
+ 16: [(0xF800, 0x7E0, 0x1F), (0x7C00, 0x3E0, 0x1F)],
185
+ }
186
+ MASK_MODES = {
187
+ (32, (0xFF0000, 0xFF00, 0xFF, 0x0)): "BGRX",
188
+ (32, (0xFF000000, 0xFF0000, 0xFF00, 0x0)): "XBGR",
189
+ (32, (0xFF000000, 0xFF0000, 0xFF00, 0xFF)): "ABGR",
190
+ (32, (0xFF, 0xFF00, 0xFF0000, 0xFF000000)): "RGBA",
191
+ (32, (0xFF0000, 0xFF00, 0xFF, 0xFF000000)): "BGRA",
192
+ (32, (0x0, 0x0, 0x0, 0x0)): "BGRA",
193
+ (24, (0xFF0000, 0xFF00, 0xFF)): "BGR",
194
+ (16, (0xF800, 0x7E0, 0x1F)): "BGR;16",
195
+ (16, (0x7C00, 0x3E0, 0x1F)): "BGR;15",
196
+ }
197
+ if file_info["bits"] in SUPPORTED:
198
+ if (
199
+ file_info["bits"] == 32
200
+ and file_info["rgba_mask"] in SUPPORTED[file_info["bits"]]
201
+ ):
202
+ raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])]
203
+ self.mode = "RGBA" if "A" in raw_mode else self.mode
204
+ elif (
205
+ file_info["bits"] in (24, 16)
206
+ and file_info["rgb_mask"] in SUPPORTED[file_info["bits"]]
207
+ ):
208
+ raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
209
+ else:
210
+ msg = "Unsupported BMP bitfields layout"
211
+ raise OSError(msg)
212
+ else:
213
+ msg = "Unsupported BMP bitfields layout"
214
+ raise OSError(msg)
215
+ elif file_info["compression"] == self.RAW:
216
+ if file_info["bits"] == 32 and header == 22: # 32-bit .cur offset
217
+ raw_mode, self.mode = "BGRA", "RGBA"
218
+ elif file_info["compression"] in (self.RLE8, self.RLE4):
219
+ decoder_name = "bmp_rle"
220
+ else:
221
+ msg = f"Unsupported BMP compression ({file_info['compression']})"
222
+ raise OSError(msg)
223
+
224
+ # --------------- Once the header is processed, process the palette/LUT
225
+ if self.mode == "P": # Paletted for 1, 4 and 8 bit images
226
+ # ---------------------------------------------------- 1-bit images
227
+ if not (0 < file_info["colors"] <= 65536):
228
+ msg = f"Unsupported BMP Palette size ({file_info['colors']})"
229
+ raise OSError(msg)
230
+ else:
231
+ padding = file_info["palette_padding"]
232
+ palette = read(padding * file_info["colors"])
233
+ greyscale = True
234
+ indices = (
235
+ (0, 255)
236
+ if file_info["colors"] == 2
237
+ else list(range(file_info["colors"]))
238
+ )
239
+
240
+ # ----------------- Check if greyscale and ignore palette if so
241
+ for ind, val in enumerate(indices):
242
+ rgb = palette[ind * padding : ind * padding + 3]
243
+ if rgb != o8(val) * 3:
244
+ greyscale = False
245
+
246
+ # ------- If all colors are grey, white or black, ditch palette
247
+ if greyscale:
248
+ self.mode = "1" if file_info["colors"] == 2 else "L"
249
+ raw_mode = self.mode
250
+ else:
251
+ self.mode = "P"
252
+ self.palette = ImagePalette.raw(
253
+ "BGRX" if padding == 4 else "BGR", palette
254
+ )
255
+
256
+ # ---------------------------- Finally set the tile data for the plugin
257
+ self.info["compression"] = file_info["compression"]
258
+ args = [raw_mode]
259
+ if decoder_name == "bmp_rle":
260
+ args.append(file_info["compression"] == self.RLE4)
261
+ else:
262
+ args.append(((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3))
263
+ args.append(file_info["direction"])
264
+ self.tile = [
265
+ (
266
+ decoder_name,
267
+ (0, 0, file_info["width"], file_info["height"]),
268
+ offset or self.fp.tell(),
269
+ tuple(args),
270
+ )
271
+ ]
272
+
273
+ def _open(self):
274
+ """Open file, check magic number and read header"""
275
+ # read 14 bytes: magic number, filesize, reserved, header final offset
276
+ head_data = self.fp.read(14)
277
+ # choke if the file does not have the required magic bytes
278
+ if not _accept(head_data):
279
+ msg = "Not a BMP file"
280
+ raise SyntaxError(msg)
281
+ # read the start position of the BMP image data (u32)
282
+ offset = i32(head_data, 10)
283
+ # load bitmap information (offset=raster info)
284
+ self._bitmap(offset=offset)
285
+
286
+
287
+ class BmpRleDecoder(ImageFile.PyDecoder):
288
+ _pulls_fd = True
289
+
290
+ def decode(self, buffer):
291
+ rle4 = self.args[1]
292
+ data = bytearray()
293
+ x = 0
294
+ while len(data) < self.state.xsize * self.state.ysize:
295
+ pixels = self.fd.read(1)
296
+ byte = self.fd.read(1)
297
+ if not pixels or not byte:
298
+ break
299
+ num_pixels = pixels[0]
300
+ if num_pixels:
301
+ # encoded mode
302
+ if x + num_pixels > self.state.xsize:
303
+ # Too much data for row
304
+ num_pixels = max(0, self.state.xsize - x)
305
+ if rle4:
306
+ first_pixel = o8(byte[0] >> 4)
307
+ second_pixel = o8(byte[0] & 0x0F)
308
+ for index in range(num_pixels):
309
+ if index % 2 == 0:
310
+ data += first_pixel
311
+ else:
312
+ data += second_pixel
313
+ else:
314
+ data += byte * num_pixels
315
+ x += num_pixels
316
+ else:
317
+ if byte[0] == 0:
318
+ # end of line
319
+ while len(data) % self.state.xsize != 0:
320
+ data += b"\x00"
321
+ x = 0
322
+ elif byte[0] == 1:
323
+ # end of bitmap
324
+ break
325
+ elif byte[0] == 2:
326
+ # delta
327
+ bytes_read = self.fd.read(2)
328
+ if len(bytes_read) < 2:
329
+ break
330
+ right, up = self.fd.read(2)
331
+ data += b"\x00" * (right + up * self.state.xsize)
332
+ x = len(data) % self.state.xsize
333
+ else:
334
+ # absolute mode
335
+ if rle4:
336
+ # 2 pixels per byte
337
+ byte_count = byte[0] // 2
338
+ bytes_read = self.fd.read(byte_count)
339
+ for byte_read in bytes_read:
340
+ data += o8(byte_read >> 4)
341
+ data += o8(byte_read & 0x0F)
342
+ else:
343
+ byte_count = byte[0]
344
+ bytes_read = self.fd.read(byte_count)
345
+ data += bytes_read
346
+ if len(bytes_read) < byte_count:
347
+ break
348
+ x += byte[0]
349
+
350
+ # align to 16-bit word boundary
351
+ if self.fd.tell() % 2 != 0:
352
+ self.fd.seek(1, os.SEEK_CUR)
353
+ rawmode = "L" if self.mode == "L" else "P"
354
+ self.set_as_raw(bytes(data), (rawmode, 0, self.args[-1]))
355
+ return -1, 0
356
+
357
+
358
+ # =============================================================================
359
+ # Image plugin for the DIB format (BMP alias)
360
+ # =============================================================================
361
+ class DibImageFile(BmpImageFile):
362
+ format = "DIB"
363
+ format_description = "Windows Bitmap"
364
+
365
+ def _open(self):
366
+ self._bitmap()
367
+
368
+
369
+ #
370
+ # --------------------------------------------------------------------
371
+ # Write BMP file
372
+
373
+
374
+ SAVE = {
375
+ "1": ("1", 1, 2),
376
+ "L": ("L", 8, 256),
377
+ "P": ("P", 8, 256),
378
+ "RGB": ("BGR", 24, 0),
379
+ "RGBA": ("BGRA", 32, 0),
380
+ }
381
+
382
+
383
+ def _dib_save(im, fp, filename):
384
+ _save(im, fp, filename, False)
385
+
386
+
387
+ def _save(im, fp, filename, bitmap_header=True):
388
+ try:
389
+ rawmode, bits, colors = SAVE[im.mode]
390
+ except KeyError as e:
391
+ msg = f"cannot write mode {im.mode} as BMP"
392
+ raise OSError(msg) from e
393
+
394
+ info = im.encoderinfo
395
+
396
+ dpi = info.get("dpi", (96, 96))
397
+
398
+ # 1 meter == 39.3701 inches
399
+ ppm = tuple(map(lambda x: int(x * 39.3701 + 0.5), dpi))
400
+
401
+ stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3)
402
+ header = 40 # or 64 for OS/2 version 2
403
+ image = stride * im.size[1]
404
+
405
+ if im.mode == "1":
406
+ palette = b"".join(o8(i) * 4 for i in (0, 255))
407
+ elif im.mode == "L":
408
+ palette = b"".join(o8(i) * 4 for i in range(256))
409
+ elif im.mode == "P":
410
+ palette = im.im.getpalette("RGB", "BGRX")
411
+ colors = len(palette) // 4
412
+ else:
413
+ palette = None
414
+
415
+ # bitmap header
416
+ if bitmap_header:
417
+ offset = 14 + header + colors * 4
418
+ file_size = offset + image
419
+ if file_size > 2**32 - 1:
420
+ msg = "File size is too large for the BMP format"
421
+ raise ValueError(msg)
422
+ fp.write(
423
+ b"BM" # file type (magic)
424
+ + o32(file_size) # file size
425
+ + o32(0) # reserved
426
+ + o32(offset) # image data offset
427
+ )
428
+
429
+ # bitmap info header
430
+ fp.write(
431
+ o32(header) # info header size
432
+ + o32(im.size[0]) # width
433
+ + o32(im.size[1]) # height
434
+ + o16(1) # planes
435
+ + o16(bits) # depth
436
+ + o32(0) # compression (0=uncompressed)
437
+ + o32(image) # size of bitmap
438
+ + o32(ppm[0]) # resolution
439
+ + o32(ppm[1]) # resolution
440
+ + o32(colors) # colors used
441
+ + o32(colors) # colors important
442
+ )
443
+
444
+ fp.write(b"\0" * (header - 40)) # padding (for OS/2 format)
445
+
446
+ if palette:
447
+ fp.write(palette)
448
+
449
+ ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))])
450
+
451
+
452
+ #
453
+ # --------------------------------------------------------------------
454
+ # Registry
455
+
456
+
457
+ Image.register_open(BmpImageFile.format, BmpImageFile, _accept)
458
+ Image.register_save(BmpImageFile.format, _save)
459
+
460
+ Image.register_extension(BmpImageFile.format, ".bmp")
461
+
462
+ Image.register_mime(BmpImageFile.format, "image/bmp")
463
+
464
+ Image.register_decoder("bmp_rle", BmpRleDecoder)
465
+
466
+ Image.register_open(DibImageFile.format, DibImageFile, _dib_accept)
467
+ Image.register_save(DibImageFile.format, _dib_save)
468
+
469
+ Image.register_extension(DibImageFile.format, ".dib")
470
+
471
+ Image.register_mime(DibImageFile.format, "image/bmp")
Lib/site-packages/PIL/BufrStubImagePlugin.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # BUFR stub adapter
6
+ #
7
+ # Copyright (c) 1996-2003 by Fredrik Lundh
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+
12
+ from . import Image, ImageFile
13
+
14
+ _handler = None
15
+
16
+
17
+ def register_handler(handler):
18
+ """
19
+ Install application-specific BUFR image handler.
20
+
21
+ :param handler: Handler object.
22
+ """
23
+ global _handler
24
+ _handler = handler
25
+
26
+
27
+ # --------------------------------------------------------------------
28
+ # Image adapter
29
+
30
+
31
+ def _accept(prefix):
32
+ return prefix[:4] == b"BUFR" or prefix[:4] == b"ZCZC"
33
+
34
+
35
+ class BufrStubImageFile(ImageFile.StubImageFile):
36
+ format = "BUFR"
37
+ format_description = "BUFR"
38
+
39
+ def _open(self):
40
+ offset = self.fp.tell()
41
+
42
+ if not _accept(self.fp.read(4)):
43
+ msg = "Not a BUFR file"
44
+ raise SyntaxError(msg)
45
+
46
+ self.fp.seek(offset)
47
+
48
+ # make something up
49
+ self.mode = "F"
50
+ self._size = 1, 1
51
+
52
+ loader = self._load()
53
+ if loader:
54
+ loader.open(self)
55
+
56
+ def _load(self):
57
+ return _handler
58
+
59
+
60
+ def _save(im, fp, filename):
61
+ if _handler is None or not hasattr(_handler, "save"):
62
+ msg = "BUFR save handler not installed"
63
+ raise OSError(msg)
64
+ _handler.save(im, fp, filename)
65
+
66
+
67
+ # --------------------------------------------------------------------
68
+ # Registry
69
+
70
+ Image.register_open(BufrStubImageFile.format, BufrStubImageFile, _accept)
71
+ Image.register_save(BufrStubImageFile.format, _save)
72
+
73
+ Image.register_extension(BufrStubImageFile.format, ".bufr")
Lib/site-packages/PIL/ContainerIO.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # a class to read from a container file
6
+ #
7
+ # History:
8
+ # 1995-06-18 fl Created
9
+ # 1995-09-07 fl Added readline(), readlines()
10
+ #
11
+ # Copyright (c) 1997-2001 by Secret Labs AB
12
+ # Copyright (c) 1995 by Fredrik Lundh
13
+ #
14
+ # See the README file for information on usage and redistribution.
15
+ #
16
+
17
+
18
+ import io
19
+
20
+
21
+ class ContainerIO:
22
+ """
23
+ A file object that provides read access to a part of an existing
24
+ file (for example a TAR file).
25
+ """
26
+
27
+ def __init__(self, file, offset, length):
28
+ """
29
+ Create file object.
30
+
31
+ :param file: Existing file.
32
+ :param offset: Start of region, in bytes.
33
+ :param length: Size of region, in bytes.
34
+ """
35
+ self.fh = file
36
+ self.pos = 0
37
+ self.offset = offset
38
+ self.length = length
39
+ self.fh.seek(offset)
40
+
41
+ ##
42
+ # Always false.
43
+
44
+ def isatty(self):
45
+ return False
46
+
47
+ def seek(self, offset, mode=io.SEEK_SET):
48
+ """
49
+ Move file pointer.
50
+
51
+ :param offset: Offset in bytes.
52
+ :param mode: Starting position. Use 0 for beginning of region, 1
53
+ for current offset, and 2 for end of region. You cannot move
54
+ the pointer outside the defined region.
55
+ """
56
+ if mode == 1:
57
+ self.pos = self.pos + offset
58
+ elif mode == 2:
59
+ self.pos = self.length + offset
60
+ else:
61
+ self.pos = offset
62
+ # clamp
63
+ self.pos = max(0, min(self.pos, self.length))
64
+ self.fh.seek(self.offset + self.pos)
65
+
66
+ def tell(self):
67
+ """
68
+ Get current file pointer.
69
+
70
+ :returns: Offset from start of region, in bytes.
71
+ """
72
+ return self.pos
73
+
74
+ def read(self, n=0):
75
+ """
76
+ Read data.
77
+
78
+ :param n: Number of bytes to read. If omitted or zero,
79
+ read until end of region.
80
+ :returns: An 8-bit string.
81
+ """
82
+ if n:
83
+ n = min(n, self.length - self.pos)
84
+ else:
85
+ n = self.length - self.pos
86
+ if not n: # EOF
87
+ return b"" if "b" in self.fh.mode else ""
88
+ self.pos = self.pos + n
89
+ return self.fh.read(n)
90
+
91
+ def readline(self):
92
+ """
93
+ Read a line of text.
94
+
95
+ :returns: An 8-bit string.
96
+ """
97
+ s = b"" if "b" in self.fh.mode else ""
98
+ newline_character = b"\n" if "b" in self.fh.mode else "\n"
99
+ while True:
100
+ c = self.read(1)
101
+ if not c:
102
+ break
103
+ s = s + c
104
+ if c == newline_character:
105
+ break
106
+ return s
107
+
108
+ def readlines(self):
109
+ """
110
+ Read multiple lines of text.
111
+
112
+ :returns: A list of 8-bit strings.
113
+ """
114
+ lines = []
115
+ while True:
116
+ s = self.readline()
117
+ if not s:
118
+ break
119
+ lines.append(s)
120
+ return lines
Lib/site-packages/PIL/CurImagePlugin.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # Windows Cursor support for PIL
6
+ #
7
+ # notes:
8
+ # uses BmpImagePlugin.py to read the bitmap data.
9
+ #
10
+ # history:
11
+ # 96-05-27 fl Created
12
+ #
13
+ # Copyright (c) Secret Labs AB 1997.
14
+ # Copyright (c) Fredrik Lundh 1996.
15
+ #
16
+ # See the README file for information on usage and redistribution.
17
+ #
18
+ from . import BmpImagePlugin, Image
19
+ from ._binary import i16le as i16
20
+ from ._binary import i32le as i32
21
+
22
+ #
23
+ # --------------------------------------------------------------------
24
+
25
+
26
+ def _accept(prefix):
27
+ return prefix[:4] == b"\0\0\2\0"
28
+
29
+
30
+ ##
31
+ # Image plugin for Windows Cursor files.
32
+
33
+
34
+ class CurImageFile(BmpImagePlugin.BmpImageFile):
35
+ format = "CUR"
36
+ format_description = "Windows Cursor"
37
+
38
+ def _open(self):
39
+ offset = self.fp.tell()
40
+
41
+ # check magic
42
+ s = self.fp.read(6)
43
+ if not _accept(s):
44
+ msg = "not a CUR file"
45
+ raise SyntaxError(msg)
46
+
47
+ # pick the largest cursor in the file
48
+ m = b""
49
+ for i in range(i16(s, 4)):
50
+ s = self.fp.read(16)
51
+ if not m:
52
+ m = s
53
+ elif s[0] > m[0] and s[1] > m[1]:
54
+ m = s
55
+ if not m:
56
+ msg = "No cursors were found"
57
+ raise TypeError(msg)
58
+
59
+ # load as bitmap
60
+ self._bitmap(i32(m, 12) + offset)
61
+
62
+ # patch up the bitmap height
63
+ self._size = self.size[0], self.size[1] // 2
64
+ d, e, o, a = self.tile[0]
65
+ self.tile[0] = d, (0, 0) + self.size, o, a
66
+
67
+ return
68
+
69
+
70
+ #
71
+ # --------------------------------------------------------------------
72
+
73
+ Image.register_open(CurImageFile.format, CurImageFile, _accept)
74
+
75
+ Image.register_extension(CurImageFile.format, ".cur")
Lib/site-packages/PIL/DcxImagePlugin.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # DCX file handling
6
+ #
7
+ # DCX is a container file format defined by Intel, commonly used
8
+ # for fax applications. Each DCX file consists of a directory
9
+ # (a list of file offsets) followed by a set of (usually 1-bit)
10
+ # PCX files.
11
+ #
12
+ # History:
13
+ # 1995-09-09 fl Created
14
+ # 1996-03-20 fl Properly derived from PcxImageFile.
15
+ # 1998-07-15 fl Renamed offset attribute to avoid name clash
16
+ # 2002-07-30 fl Fixed file handling
17
+ #
18
+ # Copyright (c) 1997-98 by Secret Labs AB.
19
+ # Copyright (c) 1995-96 by Fredrik Lundh.
20
+ #
21
+ # See the README file for information on usage and redistribution.
22
+ #
23
+
24
+ from . import Image
25
+ from ._binary import i32le as i32
26
+ from .PcxImagePlugin import PcxImageFile
27
+
28
+ MAGIC = 0x3ADE68B1 # QUIZ: what's this value, then?
29
+
30
+
31
+ def _accept(prefix):
32
+ return len(prefix) >= 4 and i32(prefix) == MAGIC
33
+
34
+
35
+ ##
36
+ # Image plugin for the Intel DCX format.
37
+
38
+
39
+ class DcxImageFile(PcxImageFile):
40
+ format = "DCX"
41
+ format_description = "Intel DCX"
42
+ _close_exclusive_fp_after_loading = False
43
+
44
+ def _open(self):
45
+ # Header
46
+ s = self.fp.read(4)
47
+ if not _accept(s):
48
+ msg = "not a DCX file"
49
+ raise SyntaxError(msg)
50
+
51
+ # Component directory
52
+ self._offset = []
53
+ for i in range(1024):
54
+ offset = i32(self.fp.read(4))
55
+ if not offset:
56
+ break
57
+ self._offset.append(offset)
58
+
59
+ self._fp = self.fp
60
+ self.frame = None
61
+ self.n_frames = len(self._offset)
62
+ self.is_animated = self.n_frames > 1
63
+ self.seek(0)
64
+
65
+ def seek(self, frame):
66
+ if not self._seek_check(frame):
67
+ return
68
+ self.frame = frame
69
+ self.fp = self._fp
70
+ self.fp.seek(self._offset[frame])
71
+ PcxImageFile._open(self)
72
+
73
+ def tell(self):
74
+ return self.frame
75
+
76
+
77
+ Image.register_open(DcxImageFile.format, DcxImageFile, _accept)
78
+
79
+ Image.register_extension(DcxImageFile.format, ".dcx")
Lib/site-packages/PIL/DdsImagePlugin.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A Pillow loader for .dds files (S3TC-compressed aka DXTC)
3
+ Jerome Leclanche <[email protected]>
4
+
5
+ Documentation:
6
+ https://web.archive.org/web/20170802060935/http://oss.sgi.com/projects/ogl-sample/registry/EXT/texture_compression_s3tc.txt
7
+
8
+ The contents of this file are hereby released in the public domain (CC0)
9
+ Full text of the CC0 license:
10
+ https://creativecommons.org/publicdomain/zero/1.0/
11
+ """
12
+
13
+ import struct
14
+ from io import BytesIO
15
+
16
+ from . import Image, ImageFile
17
+ from ._binary import o32le as o32
18
+
19
+ # Magic ("DDS ")
20
+ DDS_MAGIC = 0x20534444
21
+
22
+ # DDS flags
23
+ DDSD_CAPS = 0x1
24
+ DDSD_HEIGHT = 0x2
25
+ DDSD_WIDTH = 0x4
26
+ DDSD_PITCH = 0x8
27
+ DDSD_PIXELFORMAT = 0x1000
28
+ DDSD_MIPMAPCOUNT = 0x20000
29
+ DDSD_LINEARSIZE = 0x80000
30
+ DDSD_DEPTH = 0x800000
31
+
32
+ # DDS caps
33
+ DDSCAPS_COMPLEX = 0x8
34
+ DDSCAPS_TEXTURE = 0x1000
35
+ DDSCAPS_MIPMAP = 0x400000
36
+
37
+ DDSCAPS2_CUBEMAP = 0x200
38
+ DDSCAPS2_CUBEMAP_POSITIVEX = 0x400
39
+ DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800
40
+ DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000
41
+ DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000
42
+ DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000
43
+ DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000
44
+ DDSCAPS2_VOLUME = 0x200000
45
+
46
+ # Pixel Format
47
+ DDPF_ALPHAPIXELS = 0x1
48
+ DDPF_ALPHA = 0x2
49
+ DDPF_FOURCC = 0x4
50
+ DDPF_PALETTEINDEXED8 = 0x20
51
+ DDPF_RGB = 0x40
52
+ DDPF_LUMINANCE = 0x20000
53
+
54
+
55
+ # dds.h
56
+
57
+ DDS_FOURCC = DDPF_FOURCC
58
+ DDS_RGB = DDPF_RGB
59
+ DDS_RGBA = DDPF_RGB | DDPF_ALPHAPIXELS
60
+ DDS_LUMINANCE = DDPF_LUMINANCE
61
+ DDS_LUMINANCEA = DDPF_LUMINANCE | DDPF_ALPHAPIXELS
62
+ DDS_ALPHA = DDPF_ALPHA
63
+ DDS_PAL8 = DDPF_PALETTEINDEXED8
64
+
65
+ DDS_HEADER_FLAGS_TEXTURE = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT
66
+ DDS_HEADER_FLAGS_MIPMAP = DDSD_MIPMAPCOUNT
67
+ DDS_HEADER_FLAGS_VOLUME = DDSD_DEPTH
68
+ DDS_HEADER_FLAGS_PITCH = DDSD_PITCH
69
+ DDS_HEADER_FLAGS_LINEARSIZE = DDSD_LINEARSIZE
70
+
71
+ DDS_HEIGHT = DDSD_HEIGHT
72
+ DDS_WIDTH = DDSD_WIDTH
73
+
74
+ DDS_SURFACE_FLAGS_TEXTURE = DDSCAPS_TEXTURE
75
+ DDS_SURFACE_FLAGS_MIPMAP = DDSCAPS_COMPLEX | DDSCAPS_MIPMAP
76
+ DDS_SURFACE_FLAGS_CUBEMAP = DDSCAPS_COMPLEX
77
+
78
+ DDS_CUBEMAP_POSITIVEX = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX
79
+ DDS_CUBEMAP_NEGATIVEX = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX
80
+ DDS_CUBEMAP_POSITIVEY = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY
81
+ DDS_CUBEMAP_NEGATIVEY = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY
82
+ DDS_CUBEMAP_POSITIVEZ = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ
83
+ DDS_CUBEMAP_NEGATIVEZ = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ
84
+
85
+
86
+ # DXT1
87
+ DXT1_FOURCC = 0x31545844
88
+
89
+ # DXT3
90
+ DXT3_FOURCC = 0x33545844
91
+
92
+ # DXT5
93
+ DXT5_FOURCC = 0x35545844
94
+
95
+
96
+ # dxgiformat.h
97
+
98
+ DXGI_FORMAT_R8G8B8A8_TYPELESS = 27
99
+ DXGI_FORMAT_R8G8B8A8_UNORM = 28
100
+ DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 29
101
+ DXGI_FORMAT_BC5_TYPELESS = 82
102
+ DXGI_FORMAT_BC5_UNORM = 83
103
+ DXGI_FORMAT_BC5_SNORM = 84
104
+ DXGI_FORMAT_BC6H_UF16 = 95
105
+ DXGI_FORMAT_BC6H_SF16 = 96
106
+ DXGI_FORMAT_BC7_TYPELESS = 97
107
+ DXGI_FORMAT_BC7_UNORM = 98
108
+ DXGI_FORMAT_BC7_UNORM_SRGB = 99
109
+
110
+
111
+ class DdsImageFile(ImageFile.ImageFile):
112
+ format = "DDS"
113
+ format_description = "DirectDraw Surface"
114
+
115
+ def _open(self):
116
+ if not _accept(self.fp.read(4)):
117
+ msg = "not a DDS file"
118
+ raise SyntaxError(msg)
119
+ (header_size,) = struct.unpack("<I", self.fp.read(4))
120
+ if header_size != 124:
121
+ msg = f"Unsupported header size {repr(header_size)}"
122
+ raise OSError(msg)
123
+ header_bytes = self.fp.read(header_size - 4)
124
+ if len(header_bytes) != 120:
125
+ msg = f"Incomplete header: {len(header_bytes)} bytes"
126
+ raise OSError(msg)
127
+ header = BytesIO(header_bytes)
128
+
129
+ flags, height, width = struct.unpack("<3I", header.read(12))
130
+ self._size = (width, height)
131
+ self.mode = "RGBA"
132
+
133
+ pitch, depth, mipmaps = struct.unpack("<3I", header.read(12))
134
+ struct.unpack("<11I", header.read(44)) # reserved
135
+
136
+ # pixel format
137
+ pfsize, pfflags = struct.unpack("<2I", header.read(8))
138
+ fourcc = header.read(4)
139
+ (bitcount,) = struct.unpack("<I", header.read(4))
140
+ masks = struct.unpack("<4I", header.read(16))
141
+ if pfflags & DDPF_LUMINANCE:
142
+ # Texture contains uncompressed L or LA data
143
+ if pfflags & DDPF_ALPHAPIXELS:
144
+ self.mode = "LA"
145
+ else:
146
+ self.mode = "L"
147
+
148
+ self.tile = [("raw", (0, 0) + self.size, 0, (self.mode, 0, 1))]
149
+ elif pfflags & DDPF_RGB:
150
+ # Texture contains uncompressed RGB data
151
+ masks = {mask: ["R", "G", "B", "A"][i] for i, mask in enumerate(masks)}
152
+ rawmode = ""
153
+ if pfflags & DDPF_ALPHAPIXELS:
154
+ rawmode += masks[0xFF000000]
155
+ else:
156
+ self.mode = "RGB"
157
+ rawmode += masks[0xFF0000] + masks[0xFF00] + masks[0xFF]
158
+
159
+ self.tile = [("raw", (0, 0) + self.size, 0, (rawmode[::-1], 0, 1))]
160
+ else:
161
+ data_start = header_size + 4
162
+ n = 0
163
+ if fourcc == b"DXT1":
164
+ self.pixel_format = "DXT1"
165
+ n = 1
166
+ elif fourcc == b"DXT3":
167
+ self.pixel_format = "DXT3"
168
+ n = 2
169
+ elif fourcc == b"DXT5":
170
+ self.pixel_format = "DXT5"
171
+ n = 3
172
+ elif fourcc == b"ATI1":
173
+ self.pixel_format = "BC4"
174
+ n = 4
175
+ self.mode = "L"
176
+ elif fourcc == b"ATI2":
177
+ self.pixel_format = "BC5"
178
+ n = 5
179
+ self.mode = "RGB"
180
+ elif fourcc == b"BC5S":
181
+ self.pixel_format = "BC5S"
182
+ n = 5
183
+ self.mode = "RGB"
184
+ elif fourcc == b"DX10":
185
+ data_start += 20
186
+ # ignoring flags which pertain to volume textures and cubemaps
187
+ (dxgi_format,) = struct.unpack("<I", self.fp.read(4))
188
+ self.fp.read(16)
189
+ if dxgi_format in (DXGI_FORMAT_BC5_TYPELESS, DXGI_FORMAT_BC5_UNORM):
190
+ self.pixel_format = "BC5"
191
+ n = 5
192
+ self.mode = "RGB"
193
+ elif dxgi_format == DXGI_FORMAT_BC5_SNORM:
194
+ self.pixel_format = "BC5S"
195
+ n = 5
196
+ self.mode = "RGB"
197
+ elif dxgi_format == DXGI_FORMAT_BC6H_UF16:
198
+ self.pixel_format = "BC6H"
199
+ n = 6
200
+ self.mode = "RGB"
201
+ elif dxgi_format == DXGI_FORMAT_BC6H_SF16:
202
+ self.pixel_format = "BC6HS"
203
+ n = 6
204
+ self.mode = "RGB"
205
+ elif dxgi_format in (DXGI_FORMAT_BC7_TYPELESS, DXGI_FORMAT_BC7_UNORM):
206
+ self.pixel_format = "BC7"
207
+ n = 7
208
+ elif dxgi_format == DXGI_FORMAT_BC7_UNORM_SRGB:
209
+ self.pixel_format = "BC7"
210
+ self.info["gamma"] = 1 / 2.2
211
+ n = 7
212
+ elif dxgi_format in (
213
+ DXGI_FORMAT_R8G8B8A8_TYPELESS,
214
+ DXGI_FORMAT_R8G8B8A8_UNORM,
215
+ DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
216
+ ):
217
+ self.tile = [("raw", (0, 0) + self.size, 0, ("RGBA", 0, 1))]
218
+ if dxgi_format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
219
+ self.info["gamma"] = 1 / 2.2
220
+ return
221
+ else:
222
+ msg = f"Unimplemented DXGI format {dxgi_format}"
223
+ raise NotImplementedError(msg)
224
+ else:
225
+ msg = f"Unimplemented pixel format {repr(fourcc)}"
226
+ raise NotImplementedError(msg)
227
+
228
+ self.tile = [
229
+ ("bcn", (0, 0) + self.size, data_start, (n, self.pixel_format))
230
+ ]
231
+
232
+ def load_seek(self, pos):
233
+ pass
234
+
235
+
236
+ def _save(im, fp, filename):
237
+ if im.mode not in ("RGB", "RGBA", "L", "LA"):
238
+ msg = f"cannot write mode {im.mode} as DDS"
239
+ raise OSError(msg)
240
+
241
+ rawmode = im.mode
242
+ masks = [0xFF0000, 0xFF00, 0xFF]
243
+ if im.mode in ("L", "LA"):
244
+ pixel_flags = DDPF_LUMINANCE
245
+ else:
246
+ pixel_flags = DDPF_RGB
247
+ rawmode = rawmode[::-1]
248
+ if im.mode in ("LA", "RGBA"):
249
+ pixel_flags |= DDPF_ALPHAPIXELS
250
+ masks.append(0xFF000000)
251
+
252
+ bitcount = len(masks) * 8
253
+ while len(masks) < 4:
254
+ masks.append(0)
255
+
256
+ fp.write(
257
+ o32(DDS_MAGIC)
258
+ + o32(124) # header size
259
+ + o32(
260
+ DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PITCH | DDSD_PIXELFORMAT
261
+ ) # flags
262
+ + o32(im.height)
263
+ + o32(im.width)
264
+ + o32((im.width * bitcount + 7) // 8) # pitch
265
+ + o32(0) # depth
266
+ + o32(0) # mipmaps
267
+ + o32(0) * 11 # reserved
268
+ + o32(32) # pfsize
269
+ + o32(pixel_flags) # pfflags
270
+ + o32(0) # fourcc
271
+ + o32(bitcount) # bitcount
272
+ + b"".join(o32(mask) for mask in masks) # rgbabitmask
273
+ + o32(DDSCAPS_TEXTURE) # dwCaps
274
+ + o32(0) # dwCaps2
275
+ + o32(0) # dwCaps3
276
+ + o32(0) # dwCaps4
277
+ + o32(0) # dwReserved2
278
+ )
279
+ if im.mode == "RGBA":
280
+ r, g, b, a = im.split()
281
+ im = Image.merge("RGBA", (a, r, g, b))
282
+ ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, 1))])
283
+
284
+
285
+ def _accept(prefix):
286
+ return prefix[:4] == b"DDS "
287
+
288
+
289
+ Image.register_open(DdsImageFile.format, DdsImageFile, _accept)
290
+ Image.register_save(DdsImageFile.format, _save)
291
+ Image.register_extension(DdsImageFile.format, ".dds")
Lib/site-packages/PIL/EpsImagePlugin.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # EPS file handling
6
+ #
7
+ # History:
8
+ # 1995-09-01 fl Created (0.1)
9
+ # 1996-05-18 fl Don't choke on "atend" fields, Ghostscript interface (0.2)
10
+ # 1996-08-22 fl Don't choke on floating point BoundingBox values
11
+ # 1996-08-23 fl Handle files from Macintosh (0.3)
12
+ # 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.4)
13
+ # 2003-09-07 fl Check gs.close status (from Federico Di Gregorio) (0.5)
14
+ # 2014-05-07 e Handling of EPS with binary preview and fixed resolution
15
+ # resizing
16
+ #
17
+ # Copyright (c) 1997-2003 by Secret Labs AB.
18
+ # Copyright (c) 1995-2003 by Fredrik Lundh
19
+ #
20
+ # See the README file for information on usage and redistribution.
21
+ #
22
+
23
+ import io
24
+ import os
25
+ import re
26
+ import subprocess
27
+ import sys
28
+ import tempfile
29
+
30
+ from . import Image, ImageFile
31
+ from ._binary import i32le as i32
32
+ from ._deprecate import deprecate
33
+
34
+ # --------------------------------------------------------------------
35
+
36
+
37
+ split = re.compile(r"^%%([^:]*):[ \t]*(.*)[ \t]*$")
38
+ field = re.compile(r"^%[%!\w]([^:]*)[ \t]*$")
39
+
40
+ gs_windows_binary = None
41
+ if sys.platform.startswith("win"):
42
+ import shutil
43
+
44
+ for binary in ("gswin32c", "gswin64c", "gs"):
45
+ if shutil.which(binary) is not None:
46
+ gs_windows_binary = binary
47
+ break
48
+ else:
49
+ gs_windows_binary = False
50
+
51
+
52
+ def has_ghostscript():
53
+ if gs_windows_binary:
54
+ return True
55
+ if not sys.platform.startswith("win"):
56
+ try:
57
+ subprocess.check_call(["gs", "--version"], stdout=subprocess.DEVNULL)
58
+ return True
59
+ except OSError:
60
+ # No Ghostscript
61
+ pass
62
+ return False
63
+
64
+
65
+ def Ghostscript(tile, size, fp, scale=1, transparency=False):
66
+ """Render an image using Ghostscript"""
67
+
68
+ # Unpack decoder tile
69
+ decoder, tile, offset, data = tile[0]
70
+ length, bbox = data
71
+
72
+ # Hack to support hi-res rendering
73
+ scale = int(scale) or 1
74
+ # orig_size = size
75
+ # orig_bbox = bbox
76
+ size = (size[0] * scale, size[1] * scale)
77
+ # resolution is dependent on bbox and size
78
+ res = (
79
+ 72.0 * size[0] / (bbox[2] - bbox[0]),
80
+ 72.0 * size[1] / (bbox[3] - bbox[1]),
81
+ )
82
+
83
+ out_fd, outfile = tempfile.mkstemp()
84
+ os.close(out_fd)
85
+
86
+ infile_temp = None
87
+ if hasattr(fp, "name") and os.path.exists(fp.name):
88
+ infile = fp.name
89
+ else:
90
+ in_fd, infile_temp = tempfile.mkstemp()
91
+ os.close(in_fd)
92
+ infile = infile_temp
93
+
94
+ # Ignore length and offset!
95
+ # Ghostscript can read it
96
+ # Copy whole file to read in Ghostscript
97
+ with open(infile_temp, "wb") as f:
98
+ # fetch length of fp
99
+ fp.seek(0, io.SEEK_END)
100
+ fsize = fp.tell()
101
+ # ensure start position
102
+ # go back
103
+ fp.seek(0)
104
+ lengthfile = fsize
105
+ while lengthfile > 0:
106
+ s = fp.read(min(lengthfile, 100 * 1024))
107
+ if not s:
108
+ break
109
+ lengthfile -= len(s)
110
+ f.write(s)
111
+
112
+ device = "pngalpha" if transparency else "ppmraw"
113
+
114
+ # Build Ghostscript command
115
+ command = [
116
+ "gs",
117
+ "-q", # quiet mode
118
+ "-g%dx%d" % size, # set output geometry (pixels)
119
+ "-r%fx%f" % res, # set input DPI (dots per inch)
120
+ "-dBATCH", # exit after processing
121
+ "-dNOPAUSE", # don't pause between pages
122
+ "-dSAFER", # safe mode
123
+ f"-sDEVICE={device}",
124
+ f"-sOutputFile={outfile}", # output file
125
+ # adjust for image origin
126
+ "-c",
127
+ f"{-bbox[0]} {-bbox[1]} translate",
128
+ "-f",
129
+ infile, # input file
130
+ # showpage (see https://bugs.ghostscript.com/show_bug.cgi?id=698272)
131
+ "-c",
132
+ "showpage",
133
+ ]
134
+
135
+ if gs_windows_binary is not None:
136
+ if not gs_windows_binary:
137
+ try:
138
+ os.unlink(outfile)
139
+ if infile_temp:
140
+ os.unlink(infile_temp)
141
+ except OSError:
142
+ pass
143
+
144
+ msg = "Unable to locate Ghostscript on paths"
145
+ raise OSError(msg)
146
+ command[0] = gs_windows_binary
147
+
148
+ # push data through Ghostscript
149
+ try:
150
+ startupinfo = None
151
+ if sys.platform.startswith("win"):
152
+ startupinfo = subprocess.STARTUPINFO()
153
+ startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
154
+ subprocess.check_call(command, startupinfo=startupinfo)
155
+ out_im = Image.open(outfile)
156
+ out_im.load()
157
+ finally:
158
+ try:
159
+ os.unlink(outfile)
160
+ if infile_temp:
161
+ os.unlink(infile_temp)
162
+ except OSError:
163
+ pass
164
+
165
+ im = out_im.im.copy()
166
+ out_im.close()
167
+ return im
168
+
169
+
170
+ class PSFile:
171
+ """
172
+ Wrapper for bytesio object that treats either CR or LF as end of line.
173
+ This class is no longer used internally, but kept for backwards compatibility.
174
+ """
175
+
176
+ def __init__(self, fp):
177
+ deprecate(
178
+ "PSFile",
179
+ 11,
180
+ action="If you need the functionality of this class "
181
+ "you will need to implement it yourself.",
182
+ )
183
+ self.fp = fp
184
+ self.char = None
185
+
186
+ def seek(self, offset, whence=io.SEEK_SET):
187
+ self.char = None
188
+ self.fp.seek(offset, whence)
189
+
190
+ def readline(self):
191
+ s = [self.char or b""]
192
+ self.char = None
193
+
194
+ c = self.fp.read(1)
195
+ while (c not in b"\r\n") and len(c):
196
+ s.append(c)
197
+ c = self.fp.read(1)
198
+
199
+ self.char = self.fp.read(1)
200
+ # line endings can be 1 or 2 of \r \n, in either order
201
+ if self.char in b"\r\n":
202
+ self.char = None
203
+
204
+ return b"".join(s).decode("latin-1")
205
+
206
+
207
+ def _accept(prefix):
208
+ return prefix[:4] == b"%!PS" or (len(prefix) >= 4 and i32(prefix) == 0xC6D3D0C5)
209
+
210
+
211
+ ##
212
+ # Image plugin for Encapsulated PostScript. This plugin supports only
213
+ # a few variants of this format.
214
+
215
+
216
+ class EpsImageFile(ImageFile.ImageFile):
217
+ """EPS File Parser for the Python Imaging Library"""
218
+
219
+ format = "EPS"
220
+ format_description = "Encapsulated Postscript"
221
+
222
+ mode_map = {1: "L", 2: "LAB", 3: "RGB", 4: "CMYK"}
223
+
224
+ def _open(self):
225
+ (length, offset) = self._find_offset(self.fp)
226
+
227
+ # go to offset - start of "%!PS"
228
+ self.fp.seek(offset)
229
+
230
+ self.mode = "RGB"
231
+ self._size = None
232
+
233
+ byte_arr = bytearray(255)
234
+ bytes_mv = memoryview(byte_arr)
235
+ bytes_read = 0
236
+ reading_comments = True
237
+
238
+ def check_required_header_comments():
239
+ if "PS-Adobe" not in self.info:
240
+ msg = 'EPS header missing "%!PS-Adobe" comment'
241
+ raise SyntaxError(msg)
242
+ if "BoundingBox" not in self.info:
243
+ msg = 'EPS header missing "%%BoundingBox" comment'
244
+ raise SyntaxError(msg)
245
+
246
+ while True:
247
+ byte = self.fp.read(1)
248
+ if byte == b"":
249
+ # if we didn't read a byte we must be at the end of the file
250
+ if bytes_read == 0:
251
+ break
252
+ elif byte in b"\r\n":
253
+ # if we read a line ending character, ignore it and parse what
254
+ # we have already read. if we haven't read any other characters,
255
+ # continue reading
256
+ if bytes_read == 0:
257
+ continue
258
+ else:
259
+ # ASCII/hexadecimal lines in an EPS file must not exceed
260
+ # 255 characters, not including line ending characters
261
+ if bytes_read >= 255:
262
+ # only enforce this for lines starting with a "%",
263
+ # otherwise assume it's binary data
264
+ if byte_arr[0] == ord("%"):
265
+ msg = "not an EPS file"
266
+ raise SyntaxError(msg)
267
+ else:
268
+ if reading_comments:
269
+ check_required_header_comments()
270
+ reading_comments = False
271
+ # reset bytes_read so we can keep reading
272
+ # data until the end of the line
273
+ bytes_read = 0
274
+ byte_arr[bytes_read] = byte[0]
275
+ bytes_read += 1
276
+ continue
277
+
278
+ if reading_comments:
279
+ # Load EPS header
280
+
281
+ # if this line doesn't start with a "%",
282
+ # or does start with "%%EndComments",
283
+ # then we've reached the end of the header/comments
284
+ if byte_arr[0] != ord("%") or bytes_mv[:13] == b"%%EndComments":
285
+ check_required_header_comments()
286
+ reading_comments = False
287
+ continue
288
+
289
+ s = str(bytes_mv[:bytes_read], "latin-1")
290
+
291
+ try:
292
+ m = split.match(s)
293
+ except re.error as e:
294
+ msg = "not an EPS file"
295
+ raise SyntaxError(msg) from e
296
+
297
+ if m:
298
+ k, v = m.group(1, 2)
299
+ self.info[k] = v
300
+ if k == "BoundingBox":
301
+ try:
302
+ # Note: The DSC spec says that BoundingBox
303
+ # fields should be integers, but some drivers
304
+ # put floating point values there anyway.
305
+ box = [int(float(i)) for i in v.split()]
306
+ self._size = box[2] - box[0], box[3] - box[1]
307
+ self.tile = [
308
+ ("eps", (0, 0) + self.size, offset, (length, box))
309
+ ]
310
+ except Exception:
311
+ pass
312
+ else:
313
+ m = field.match(s)
314
+ if m:
315
+ k = m.group(1)
316
+ if k[:8] == "PS-Adobe":
317
+ self.info["PS-Adobe"] = k[9:]
318
+ else:
319
+ self.info[k] = ""
320
+ elif s[0] == "%":
321
+ # handle non-DSC PostScript comments that some
322
+ # tools mistakenly put in the Comments section
323
+ pass
324
+ else:
325
+ msg = "bad EPS header"
326
+ raise OSError(msg)
327
+ elif bytes_mv[:11] == b"%ImageData:":
328
+ # Check for an "ImageData" descriptor
329
+ # https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577413_pgfId-1035096
330
+
331
+ # Values:
332
+ # columns
333
+ # rows
334
+ # bit depth (1 or 8)
335
+ # mode (1: L, 2: LAB, 3: RGB, 4: CMYK)
336
+ # number of padding channels
337
+ # block size (number of bytes per row per channel)
338
+ # binary/ascii (1: binary, 2: ascii)
339
+ # data start identifier (the image data follows after a single line
340
+ # consisting only of this quoted value)
341
+ image_data_values = byte_arr[11:bytes_read].split(None, 7)
342
+ columns, rows, bit_depth, mode_id = [
343
+ int(value) for value in image_data_values[:4]
344
+ ]
345
+
346
+ if bit_depth == 1:
347
+ self.mode = "1"
348
+ elif bit_depth == 8:
349
+ try:
350
+ self.mode = self.mode_map[mode_id]
351
+ except ValueError:
352
+ break
353
+ else:
354
+ break
355
+
356
+ self._size = columns, rows
357
+ return
358
+
359
+ bytes_read = 0
360
+
361
+ check_required_header_comments()
362
+
363
+ if not self._size:
364
+ msg = "cannot determine EPS bounding box"
365
+ raise OSError(msg)
366
+
367
+ def _find_offset(self, fp):
368
+ s = fp.read(4)
369
+
370
+ if s == b"%!PS":
371
+ # for HEAD without binary preview
372
+ fp.seek(0, io.SEEK_END)
373
+ length = fp.tell()
374
+ offset = 0
375
+ elif i32(s) == 0xC6D3D0C5:
376
+ # FIX for: Some EPS file not handled correctly / issue #302
377
+ # EPS can contain binary data
378
+ # or start directly with latin coding
379
+ # more info see:
380
+ # https://web.archive.org/web/20160528181353/http://partners.adobe.com/public/developer/en/ps/5002.EPSF_Spec.pdf
381
+ s = fp.read(8)
382
+ offset = i32(s)
383
+ length = i32(s, 4)
384
+ else:
385
+ msg = "not an EPS file"
386
+ raise SyntaxError(msg)
387
+
388
+ return length, offset
389
+
390
+ def load(self, scale=1, transparency=False):
391
+ # Load EPS via Ghostscript
392
+ if self.tile:
393
+ self.im = Ghostscript(self.tile, self.size, self.fp, scale, transparency)
394
+ self.mode = self.im.mode
395
+ self._size = self.im.size
396
+ self.tile = []
397
+ return Image.Image.load(self)
398
+
399
+ def load_seek(self, *args, **kwargs):
400
+ # we can't incrementally load, so force ImageFile.parser to
401
+ # use our custom load method by defining this method.
402
+ pass
403
+
404
+
405
+ # --------------------------------------------------------------------
406
+
407
+
408
+ def _save(im, fp, filename, eps=1):
409
+ """EPS Writer for the Python Imaging Library."""
410
+
411
+ # make sure image data is available
412
+ im.load()
413
+
414
+ # determine PostScript image mode
415
+ if im.mode == "L":
416
+ operator = (8, 1, b"image")
417
+ elif im.mode == "RGB":
418
+ operator = (8, 3, b"false 3 colorimage")
419
+ elif im.mode == "CMYK":
420
+ operator = (8, 4, b"false 4 colorimage")
421
+ else:
422
+ msg = "image mode is not supported"
423
+ raise ValueError(msg)
424
+
425
+ if eps:
426
+ # write EPS header
427
+ fp.write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
428
+ fp.write(b"%%Creator: PIL 0.1 EpsEncode\n")
429
+ # fp.write("%%CreationDate: %s"...)
430
+ fp.write(b"%%%%BoundingBox: 0 0 %d %d\n" % im.size)
431
+ fp.write(b"%%Pages: 1\n")
432
+ fp.write(b"%%EndComments\n")
433
+ fp.write(b"%%Page: 1 1\n")
434
+ fp.write(b"%%ImageData: %d %d " % im.size)
435
+ fp.write(b'%d %d 0 1 1 "%s"\n' % operator)
436
+
437
+ # image header
438
+ fp.write(b"gsave\n")
439
+ fp.write(b"10 dict begin\n")
440
+ fp.write(b"/buf %d string def\n" % (im.size[0] * operator[1]))
441
+ fp.write(b"%d %d scale\n" % im.size)
442
+ fp.write(b"%d %d 8\n" % im.size) # <= bits
443
+ fp.write(b"[%d 0 0 -%d 0 %d]\n" % (im.size[0], im.size[1], im.size[1]))
444
+ fp.write(b"{ currentfile buf readhexstring pop } bind\n")
445
+ fp.write(operator[2] + b"\n")
446
+ if hasattr(fp, "flush"):
447
+ fp.flush()
448
+
449
+ ImageFile._save(im, fp, [("eps", (0, 0) + im.size, 0, None)])
450
+
451
+ fp.write(b"\n%%%%EndBinary\n")
452
+ fp.write(b"grestore end\n")
453
+ if hasattr(fp, "flush"):
454
+ fp.flush()
455
+
456
+
457
+ # --------------------------------------------------------------------
458
+
459
+
460
+ Image.register_open(EpsImageFile.format, EpsImageFile, _accept)
461
+
462
+ Image.register_save(EpsImageFile.format, _save)
463
+
464
+ Image.register_extensions(EpsImageFile.format, [".ps", ".eps"])
465
+
466
+ Image.register_mime(EpsImageFile.format, "application/postscript")
Lib/site-packages/PIL/ExifTags.py ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # EXIF tags
6
+ #
7
+ # Copyright (c) 2003 by Secret Labs AB
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+
12
+ """
13
+ This module provides constants and clear-text names for various
14
+ well-known EXIF tags.
15
+ """
16
+
17
+ from enum import IntEnum
18
+
19
+
20
+ class Base(IntEnum):
21
+ # possibly incomplete
22
+ InteropIndex = 0x0001
23
+ ProcessingSoftware = 0x000B
24
+ NewSubfileType = 0x00FE
25
+ SubfileType = 0x00FF
26
+ ImageWidth = 0x0100
27
+ ImageLength = 0x0101
28
+ BitsPerSample = 0x0102
29
+ Compression = 0x0103
30
+ PhotometricInterpretation = 0x0106
31
+ Thresholding = 0x0107
32
+ CellWidth = 0x0108
33
+ CellLength = 0x0109
34
+ FillOrder = 0x010A
35
+ DocumentName = 0x010D
36
+ ImageDescription = 0x010E
37
+ Make = 0x010F
38
+ Model = 0x0110
39
+ StripOffsets = 0x0111
40
+ Orientation = 0x0112
41
+ SamplesPerPixel = 0x0115
42
+ RowsPerStrip = 0x0116
43
+ StripByteCounts = 0x0117
44
+ MinSampleValue = 0x0118
45
+ MaxSampleValue = 0x0119
46
+ XResolution = 0x011A
47
+ YResolution = 0x011B
48
+ PlanarConfiguration = 0x011C
49
+ PageName = 0x011D
50
+ FreeOffsets = 0x0120
51
+ FreeByteCounts = 0x0121
52
+ GrayResponseUnit = 0x0122
53
+ GrayResponseCurve = 0x0123
54
+ T4Options = 0x0124
55
+ T6Options = 0x0125
56
+ ResolutionUnit = 0x0128
57
+ PageNumber = 0x0129
58
+ TransferFunction = 0x012D
59
+ Software = 0x0131
60
+ DateTime = 0x0132
61
+ Artist = 0x013B
62
+ HostComputer = 0x013C
63
+ Predictor = 0x013D
64
+ WhitePoint = 0x013E
65
+ PrimaryChromaticities = 0x013F
66
+ ColorMap = 0x0140
67
+ HalftoneHints = 0x0141
68
+ TileWidth = 0x0142
69
+ TileLength = 0x0143
70
+ TileOffsets = 0x0144
71
+ TileByteCounts = 0x0145
72
+ SubIFDs = 0x014A
73
+ InkSet = 0x014C
74
+ InkNames = 0x014D
75
+ NumberOfInks = 0x014E
76
+ DotRange = 0x0150
77
+ TargetPrinter = 0x0151
78
+ ExtraSamples = 0x0152
79
+ SampleFormat = 0x0153
80
+ SMinSampleValue = 0x0154
81
+ SMaxSampleValue = 0x0155
82
+ TransferRange = 0x0156
83
+ ClipPath = 0x0157
84
+ XClipPathUnits = 0x0158
85
+ YClipPathUnits = 0x0159
86
+ Indexed = 0x015A
87
+ JPEGTables = 0x015B
88
+ OPIProxy = 0x015F
89
+ JPEGProc = 0x0200
90
+ JpegIFOffset = 0x0201
91
+ JpegIFByteCount = 0x0202
92
+ JpegRestartInterval = 0x0203
93
+ JpegLosslessPredictors = 0x0205
94
+ JpegPointTransforms = 0x0206
95
+ JpegQTables = 0x0207
96
+ JpegDCTables = 0x0208
97
+ JpegACTables = 0x0209
98
+ YCbCrCoefficients = 0x0211
99
+ YCbCrSubSampling = 0x0212
100
+ YCbCrPositioning = 0x0213
101
+ ReferenceBlackWhite = 0x0214
102
+ XMLPacket = 0x02BC
103
+ RelatedImageFileFormat = 0x1000
104
+ RelatedImageWidth = 0x1001
105
+ RelatedImageLength = 0x1002
106
+ Rating = 0x4746
107
+ RatingPercent = 0x4749
108
+ ImageID = 0x800D
109
+ CFARepeatPatternDim = 0x828D
110
+ BatteryLevel = 0x828F
111
+ Copyright = 0x8298
112
+ ExposureTime = 0x829A
113
+ FNumber = 0x829D
114
+ IPTCNAA = 0x83BB
115
+ ImageResources = 0x8649
116
+ ExifOffset = 0x8769
117
+ InterColorProfile = 0x8773
118
+ ExposureProgram = 0x8822
119
+ SpectralSensitivity = 0x8824
120
+ GPSInfo = 0x8825
121
+ ISOSpeedRatings = 0x8827
122
+ OECF = 0x8828
123
+ Interlace = 0x8829
124
+ TimeZoneOffset = 0x882A
125
+ SelfTimerMode = 0x882B
126
+ SensitivityType = 0x8830
127
+ StandardOutputSensitivity = 0x8831
128
+ RecommendedExposureIndex = 0x8832
129
+ ISOSpeed = 0x8833
130
+ ISOSpeedLatitudeyyy = 0x8834
131
+ ISOSpeedLatitudezzz = 0x8835
132
+ ExifVersion = 0x9000
133
+ DateTimeOriginal = 0x9003
134
+ DateTimeDigitized = 0x9004
135
+ OffsetTime = 0x9010
136
+ OffsetTimeOriginal = 0x9011
137
+ OffsetTimeDigitized = 0x9012
138
+ ComponentsConfiguration = 0x9101
139
+ CompressedBitsPerPixel = 0x9102
140
+ ShutterSpeedValue = 0x9201
141
+ ApertureValue = 0x9202
142
+ BrightnessValue = 0x9203
143
+ ExposureBiasValue = 0x9204
144
+ MaxApertureValue = 0x9205
145
+ SubjectDistance = 0x9206
146
+ MeteringMode = 0x9207
147
+ LightSource = 0x9208
148
+ Flash = 0x9209
149
+ FocalLength = 0x920A
150
+ Noise = 0x920D
151
+ ImageNumber = 0x9211
152
+ SecurityClassification = 0x9212
153
+ ImageHistory = 0x9213
154
+ TIFFEPStandardID = 0x9216
155
+ MakerNote = 0x927C
156
+ UserComment = 0x9286
157
+ SubsecTime = 0x9290
158
+ SubsecTimeOriginal = 0x9291
159
+ SubsecTimeDigitized = 0x9292
160
+ AmbientTemperature = 0x9400
161
+ Humidity = 0x9401
162
+ Pressure = 0x9402
163
+ WaterDepth = 0x9403
164
+ Acceleration = 0x9404
165
+ CameraElevationAngle = 0x9405
166
+ XPTitle = 0x9C9B
167
+ XPComment = 0x9C9C
168
+ XPAuthor = 0x9C9D
169
+ XPKeywords = 0x9C9E
170
+ XPSubject = 0x9C9F
171
+ FlashPixVersion = 0xA000
172
+ ColorSpace = 0xA001
173
+ ExifImageWidth = 0xA002
174
+ ExifImageHeight = 0xA003
175
+ RelatedSoundFile = 0xA004
176
+ ExifInteroperabilityOffset = 0xA005
177
+ FlashEnergy = 0xA20B
178
+ SpatialFrequencyResponse = 0xA20C
179
+ FocalPlaneXResolution = 0xA20E
180
+ FocalPlaneYResolution = 0xA20F
181
+ FocalPlaneResolutionUnit = 0xA210
182
+ SubjectLocation = 0xA214
183
+ ExposureIndex = 0xA215
184
+ SensingMethod = 0xA217
185
+ FileSource = 0xA300
186
+ SceneType = 0xA301
187
+ CFAPattern = 0xA302
188
+ CustomRendered = 0xA401
189
+ ExposureMode = 0xA402
190
+ WhiteBalance = 0xA403
191
+ DigitalZoomRatio = 0xA404
192
+ FocalLengthIn35mmFilm = 0xA405
193
+ SceneCaptureType = 0xA406
194
+ GainControl = 0xA407
195
+ Contrast = 0xA408
196
+ Saturation = 0xA409
197
+ Sharpness = 0xA40A
198
+ DeviceSettingDescription = 0xA40B
199
+ SubjectDistanceRange = 0xA40C
200
+ ImageUniqueID = 0xA420
201
+ CameraOwnerName = 0xA430
202
+ BodySerialNumber = 0xA431
203
+ LensSpecification = 0xA432
204
+ LensMake = 0xA433
205
+ LensModel = 0xA434
206
+ LensSerialNumber = 0xA435
207
+ CompositeImage = 0xA460
208
+ CompositeImageCount = 0xA461
209
+ CompositeImageExposureTimes = 0xA462
210
+ Gamma = 0xA500
211
+ PrintImageMatching = 0xC4A5
212
+ DNGVersion = 0xC612
213
+ DNGBackwardVersion = 0xC613
214
+ UniqueCameraModel = 0xC614
215
+ LocalizedCameraModel = 0xC615
216
+ CFAPlaneColor = 0xC616
217
+ CFALayout = 0xC617
218
+ LinearizationTable = 0xC618
219
+ BlackLevelRepeatDim = 0xC619
220
+ BlackLevel = 0xC61A
221
+ BlackLevelDeltaH = 0xC61B
222
+ BlackLevelDeltaV = 0xC61C
223
+ WhiteLevel = 0xC61D
224
+ DefaultScale = 0xC61E
225
+ DefaultCropOrigin = 0xC61F
226
+ DefaultCropSize = 0xC620
227
+ ColorMatrix1 = 0xC621
228
+ ColorMatrix2 = 0xC622
229
+ CameraCalibration1 = 0xC623
230
+ CameraCalibration2 = 0xC624
231
+ ReductionMatrix1 = 0xC625
232
+ ReductionMatrix2 = 0xC626
233
+ AnalogBalance = 0xC627
234
+ AsShotNeutral = 0xC628
235
+ AsShotWhiteXY = 0xC629
236
+ BaselineExposure = 0xC62A
237
+ BaselineNoise = 0xC62B
238
+ BaselineSharpness = 0xC62C
239
+ BayerGreenSplit = 0xC62D
240
+ LinearResponseLimit = 0xC62E
241
+ CameraSerialNumber = 0xC62F
242
+ LensInfo = 0xC630
243
+ ChromaBlurRadius = 0xC631
244
+ AntiAliasStrength = 0xC632
245
+ ShadowScale = 0xC633
246
+ DNGPrivateData = 0xC634
247
+ MakerNoteSafety = 0xC635
248
+ CalibrationIlluminant1 = 0xC65A
249
+ CalibrationIlluminant2 = 0xC65B
250
+ BestQualityScale = 0xC65C
251
+ RawDataUniqueID = 0xC65D
252
+ OriginalRawFileName = 0xC68B
253
+ OriginalRawFileData = 0xC68C
254
+ ActiveArea = 0xC68D
255
+ MaskedAreas = 0xC68E
256
+ AsShotICCProfile = 0xC68F
257
+ AsShotPreProfileMatrix = 0xC690
258
+ CurrentICCProfile = 0xC691
259
+ CurrentPreProfileMatrix = 0xC692
260
+ ColorimetricReference = 0xC6BF
261
+ CameraCalibrationSignature = 0xC6F3
262
+ ProfileCalibrationSignature = 0xC6F4
263
+ AsShotProfileName = 0xC6F6
264
+ NoiseReductionApplied = 0xC6F7
265
+ ProfileName = 0xC6F8
266
+ ProfileHueSatMapDims = 0xC6F9
267
+ ProfileHueSatMapData1 = 0xC6FA
268
+ ProfileHueSatMapData2 = 0xC6FB
269
+ ProfileToneCurve = 0xC6FC
270
+ ProfileEmbedPolicy = 0xC6FD
271
+ ProfileCopyright = 0xC6FE
272
+ ForwardMatrix1 = 0xC714
273
+ ForwardMatrix2 = 0xC715
274
+ PreviewApplicationName = 0xC716
275
+ PreviewApplicationVersion = 0xC717
276
+ PreviewSettingsName = 0xC718
277
+ PreviewSettingsDigest = 0xC719
278
+ PreviewColorSpace = 0xC71A
279
+ PreviewDateTime = 0xC71B
280
+ RawImageDigest = 0xC71C
281
+ OriginalRawFileDigest = 0xC71D
282
+ SubTileBlockSize = 0xC71E
283
+ RowInterleaveFactor = 0xC71F
284
+ ProfileLookTableDims = 0xC725
285
+ ProfileLookTableData = 0xC726
286
+ OpcodeList1 = 0xC740
287
+ OpcodeList2 = 0xC741
288
+ OpcodeList3 = 0xC74E
289
+ NoiseProfile = 0xC761
290
+
291
+
292
+ """Maps EXIF tags to tag names."""
293
+ TAGS = {
294
+ **{i.value: i.name for i in Base},
295
+ 0x920C: "SpatialFrequencyResponse",
296
+ 0x9214: "SubjectLocation",
297
+ 0x9215: "ExposureIndex",
298
+ 0x828E: "CFAPattern",
299
+ 0x920B: "FlashEnergy",
300
+ 0x9216: "TIFF/EPStandardID",
301
+ }
302
+
303
+
304
+ class GPS(IntEnum):
305
+ GPSVersionID = 0
306
+ GPSLatitudeRef = 1
307
+ GPSLatitude = 2
308
+ GPSLongitudeRef = 3
309
+ GPSLongitude = 4
310
+ GPSAltitudeRef = 5
311
+ GPSAltitude = 6
312
+ GPSTimeStamp = 7
313
+ GPSSatellites = 8
314
+ GPSStatus = 9
315
+ GPSMeasureMode = 10
316
+ GPSDOP = 11
317
+ GPSSpeedRef = 12
318
+ GPSSpeed = 13
319
+ GPSTrackRef = 14
320
+ GPSTrack = 15
321
+ GPSImgDirectionRef = 16
322
+ GPSImgDirection = 17
323
+ GPSMapDatum = 18
324
+ GPSDestLatitudeRef = 19
325
+ GPSDestLatitude = 20
326
+ GPSDestLongitudeRef = 21
327
+ GPSDestLongitude = 22
328
+ GPSDestBearingRef = 23
329
+ GPSDestBearing = 24
330
+ GPSDestDistanceRef = 25
331
+ GPSDestDistance = 26
332
+ GPSProcessingMethod = 27
333
+ GPSAreaInformation = 28
334
+ GPSDateStamp = 29
335
+ GPSDifferential = 30
336
+ GPSHPositioningError = 31
337
+
338
+
339
+ """Maps EXIF GPS tags to tag names."""
340
+ GPSTAGS = {i.value: i.name for i in GPS}
341
+
342
+
343
+ class Interop(IntEnum):
344
+ InteropIndex = 1
345
+ InteropVersion = 2
346
+ RelatedImageFileFormat = 4096
347
+ RelatedImageWidth = 4097
348
+ RleatedImageHeight = 4098
349
+
350
+
351
+ class IFD(IntEnum):
352
+ Exif = 34665
353
+ GPSInfo = 34853
354
+ Makernote = 37500
355
+ Interop = 40965
356
+ IFD1 = -1
357
+
358
+
359
+ class LightSource(IntEnum):
360
+ Unknown = 0
361
+ Daylight = 1
362
+ Fluorescent = 2
363
+ Tungsten = 3
364
+ Flash = 4
365
+ Fine = 9
366
+ Cloudy = 10
367
+ Shade = 11
368
+ DaylightFluorescent = 12
369
+ DayWhiteFluorescent = 13
370
+ CoolWhiteFluorescent = 14
371
+ WhiteFluorescent = 15
372
+ StandardLightA = 17
373
+ StandardLightB = 18
374
+ StandardLightC = 19
375
+ D55 = 20
376
+ D65 = 21
377
+ D75 = 22
378
+ D50 = 23
379
+ ISO = 24
380
+ Other = 255
Lib/site-packages/PIL/FitsImagePlugin.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # FITS file handling
6
+ #
7
+ # Copyright (c) 1998-2003 by Fredrik Lundh
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+
12
+ import math
13
+
14
+ from . import Image, ImageFile
15
+
16
+
17
+ def _accept(prefix):
18
+ return prefix[:6] == b"SIMPLE"
19
+
20
+
21
+ class FitsImageFile(ImageFile.ImageFile):
22
+ format = "FITS"
23
+ format_description = "FITS"
24
+
25
+ def _open(self):
26
+ headers = {}
27
+ while True:
28
+ header = self.fp.read(80)
29
+ if not header:
30
+ msg = "Truncated FITS file"
31
+ raise OSError(msg)
32
+ keyword = header[:8].strip()
33
+ if keyword == b"END":
34
+ break
35
+ value = header[8:].split(b"/")[0].strip()
36
+ if value.startswith(b"="):
37
+ value = value[1:].strip()
38
+ if not headers and (not _accept(keyword) or value != b"T"):
39
+ msg = "Not a FITS file"
40
+ raise SyntaxError(msg)
41
+ headers[keyword] = value
42
+
43
+ naxis = int(headers[b"NAXIS"])
44
+ if naxis == 0:
45
+ msg = "No image data"
46
+ raise ValueError(msg)
47
+ elif naxis == 1:
48
+ self._size = 1, int(headers[b"NAXIS1"])
49
+ else:
50
+ self._size = int(headers[b"NAXIS1"]), int(headers[b"NAXIS2"])
51
+
52
+ number_of_bits = int(headers[b"BITPIX"])
53
+ if number_of_bits == 8:
54
+ self.mode = "L"
55
+ elif number_of_bits == 16:
56
+ self.mode = "I"
57
+ # rawmode = "I;16S"
58
+ elif number_of_bits == 32:
59
+ self.mode = "I"
60
+ elif number_of_bits in (-32, -64):
61
+ self.mode = "F"
62
+ # rawmode = "F" if number_of_bits == -32 else "F;64F"
63
+
64
+ offset = math.ceil(self.fp.tell() / 2880) * 2880
65
+ self.tile = [("raw", (0, 0) + self.size, offset, (self.mode, 0, -1))]
66
+
67
+
68
+ # --------------------------------------------------------------------
69
+ # Registry
70
+
71
+ Image.register_open(FitsImageFile.format, FitsImageFile, _accept)
72
+
73
+ Image.register_extensions(FitsImageFile.format, [".fit", ".fits"])
Lib/site-packages/PIL/FliImagePlugin.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # FLI/FLC file handling.
6
+ #
7
+ # History:
8
+ # 95-09-01 fl Created
9
+ # 97-01-03 fl Fixed parser, setup decoder tile
10
+ # 98-07-15 fl Renamed offset attribute to avoid name clash
11
+ #
12
+ # Copyright (c) Secret Labs AB 1997-98.
13
+ # Copyright (c) Fredrik Lundh 1995-97.
14
+ #
15
+ # See the README file for information on usage and redistribution.
16
+ #
17
+
18
+ import os
19
+
20
+ from . import Image, ImageFile, ImagePalette
21
+ from ._binary import i16le as i16
22
+ from ._binary import i32le as i32
23
+ from ._binary import o8
24
+
25
+ #
26
+ # decoder
27
+
28
+
29
+ def _accept(prefix):
30
+ return (
31
+ len(prefix) >= 6
32
+ and i16(prefix, 4) in [0xAF11, 0xAF12]
33
+ and i16(prefix, 14) in [0, 3] # flags
34
+ )
35
+
36
+
37
+ ##
38
+ # Image plugin for the FLI/FLC animation format. Use the <b>seek</b>
39
+ # method to load individual frames.
40
+
41
+
42
+ class FliImageFile(ImageFile.ImageFile):
43
+ format = "FLI"
44
+ format_description = "Autodesk FLI/FLC Animation"
45
+ _close_exclusive_fp_after_loading = False
46
+
47
+ def _open(self):
48
+ # HEAD
49
+ s = self.fp.read(128)
50
+ if not (_accept(s) and s[20:22] == b"\x00\x00"):
51
+ msg = "not an FLI/FLC file"
52
+ raise SyntaxError(msg)
53
+
54
+ # frames
55
+ self.n_frames = i16(s, 6)
56
+ self.is_animated = self.n_frames > 1
57
+
58
+ # image characteristics
59
+ self.mode = "P"
60
+ self._size = i16(s, 8), i16(s, 10)
61
+
62
+ # animation speed
63
+ duration = i32(s, 16)
64
+ magic = i16(s, 4)
65
+ if magic == 0xAF11:
66
+ duration = (duration * 1000) // 70
67
+ self.info["duration"] = duration
68
+
69
+ # look for palette
70
+ palette = [(a, a, a) for a in range(256)]
71
+
72
+ s = self.fp.read(16)
73
+
74
+ self.__offset = 128
75
+
76
+ if i16(s, 4) == 0xF100:
77
+ # prefix chunk; ignore it
78
+ self.__offset = self.__offset + i32(s)
79
+ s = self.fp.read(16)
80
+
81
+ if i16(s, 4) == 0xF1FA:
82
+ # look for palette chunk
83
+ number_of_subchunks = i16(s, 6)
84
+ chunk_size = None
85
+ for _ in range(number_of_subchunks):
86
+ if chunk_size is not None:
87
+ self.fp.seek(chunk_size - 6, os.SEEK_CUR)
88
+ s = self.fp.read(6)
89
+ chunk_type = i16(s, 4)
90
+ if chunk_type in (4, 11):
91
+ self._palette(palette, 2 if chunk_type == 11 else 0)
92
+ break
93
+ chunk_size = i32(s)
94
+ if not chunk_size:
95
+ break
96
+
97
+ palette = [o8(r) + o8(g) + o8(b) for (r, g, b) in palette]
98
+ self.palette = ImagePalette.raw("RGB", b"".join(palette))
99
+
100
+ # set things up to decode first frame
101
+ self.__frame = -1
102
+ self._fp = self.fp
103
+ self.__rewind = self.fp.tell()
104
+ self.seek(0)
105
+
106
+ def _palette(self, palette, shift):
107
+ # load palette
108
+
109
+ i = 0
110
+ for e in range(i16(self.fp.read(2))):
111
+ s = self.fp.read(2)
112
+ i = i + s[0]
113
+ n = s[1]
114
+ if n == 0:
115
+ n = 256
116
+ s = self.fp.read(n * 3)
117
+ for n in range(0, len(s), 3):
118
+ r = s[n] << shift
119
+ g = s[n + 1] << shift
120
+ b = s[n + 2] << shift
121
+ palette[i] = (r, g, b)
122
+ i += 1
123
+
124
+ def seek(self, frame):
125
+ if not self._seek_check(frame):
126
+ return
127
+ if frame < self.__frame:
128
+ self._seek(0)
129
+
130
+ for f in range(self.__frame + 1, frame + 1):
131
+ self._seek(f)
132
+
133
+ def _seek(self, frame):
134
+ if frame == 0:
135
+ self.__frame = -1
136
+ self._fp.seek(self.__rewind)
137
+ self.__offset = 128
138
+ else:
139
+ # ensure that the previous frame was loaded
140
+ self.load()
141
+
142
+ if frame != self.__frame + 1:
143
+ msg = f"cannot seek to frame {frame}"
144
+ raise ValueError(msg)
145
+ self.__frame = frame
146
+
147
+ # move to next frame
148
+ self.fp = self._fp
149
+ self.fp.seek(self.__offset)
150
+
151
+ s = self.fp.read(4)
152
+ if not s:
153
+ raise EOFError
154
+
155
+ framesize = i32(s)
156
+
157
+ self.decodermaxblock = framesize
158
+ self.tile = [("fli", (0, 0) + self.size, self.__offset, None)]
159
+
160
+ self.__offset += framesize
161
+
162
+ def tell(self):
163
+ return self.__frame
164
+
165
+
166
+ #
167
+ # registry
168
+
169
+ Image.register_open(FliImageFile.format, FliImageFile, _accept)
170
+
171
+ Image.register_extensions(FliImageFile.format, [".fli", ".flc"])
Lib/site-packages/PIL/FontFile.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # base class for raster font file parsers
6
+ #
7
+ # history:
8
+ # 1997-06-05 fl created
9
+ # 1997-08-19 fl restrict image width
10
+ #
11
+ # Copyright (c) 1997-1998 by Secret Labs AB
12
+ # Copyright (c) 1997-1998 by Fredrik Lundh
13
+ #
14
+ # See the README file for information on usage and redistribution.
15
+ #
16
+
17
+
18
+ import os
19
+
20
+ from . import Image, _binary
21
+
22
+ WIDTH = 800
23
+
24
+
25
+ def puti16(fp, values):
26
+ """Write network order (big-endian) 16-bit sequence"""
27
+ for v in values:
28
+ if v < 0:
29
+ v += 65536
30
+ fp.write(_binary.o16be(v))
31
+
32
+
33
+ class FontFile:
34
+ """Base class for raster font file handlers."""
35
+
36
+ bitmap = None
37
+
38
+ def __init__(self):
39
+ self.info = {}
40
+ self.glyph = [None] * 256
41
+
42
+ def __getitem__(self, ix):
43
+ return self.glyph[ix]
44
+
45
+ def compile(self):
46
+ """Create metrics and bitmap"""
47
+
48
+ if self.bitmap:
49
+ return
50
+
51
+ # create bitmap large enough to hold all data
52
+ h = w = maxwidth = 0
53
+ lines = 1
54
+ for glyph in self:
55
+ if glyph:
56
+ d, dst, src, im = glyph
57
+ h = max(h, src[3] - src[1])
58
+ w = w + (src[2] - src[0])
59
+ if w > WIDTH:
60
+ lines += 1
61
+ w = src[2] - src[0]
62
+ maxwidth = max(maxwidth, w)
63
+
64
+ xsize = maxwidth
65
+ ysize = lines * h
66
+
67
+ if xsize == 0 and ysize == 0:
68
+ return ""
69
+
70
+ self.ysize = h
71
+
72
+ # paste glyphs into bitmap
73
+ self.bitmap = Image.new("1", (xsize, ysize))
74
+ self.metrics = [None] * 256
75
+ x = y = 0
76
+ for i in range(256):
77
+ glyph = self[i]
78
+ if glyph:
79
+ d, dst, src, im = glyph
80
+ xx = src[2] - src[0]
81
+ # yy = src[3] - src[1]
82
+ x0, y0 = x, y
83
+ x = x + xx
84
+ if x > WIDTH:
85
+ x, y = 0, y + h
86
+ x0, y0 = x, y
87
+ x = xx
88
+ s = src[0] + x0, src[1] + y0, src[2] + x0, src[3] + y0
89
+ self.bitmap.paste(im.crop(src), s)
90
+ self.metrics[i] = d, dst, s
91
+
92
+ def save(self, filename):
93
+ """Save font"""
94
+
95
+ self.compile()
96
+
97
+ # font data
98
+ self.bitmap.save(os.path.splitext(filename)[0] + ".pbm", "PNG")
99
+
100
+ # font metrics
101
+ with open(os.path.splitext(filename)[0] + ".pil", "wb") as fp:
102
+ fp.write(b"PILfont\n")
103
+ fp.write(f";;;;;;{self.ysize};\n".encode("ascii")) # HACK!!!
104
+ fp.write(b"DATA\n")
105
+ for id in range(256):
106
+ m = self.metrics[id]
107
+ if not m:
108
+ puti16(fp, [0] * 10)
109
+ else:
110
+ puti16(fp, m[0] + m[1] + m[2])
Lib/site-packages/PIL/FpxImagePlugin.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # THIS IS WORK IN PROGRESS
3
+ #
4
+ # The Python Imaging Library.
5
+ # $Id$
6
+ #
7
+ # FlashPix support for PIL
8
+ #
9
+ # History:
10
+ # 97-01-25 fl Created (reads uncompressed RGB images only)
11
+ #
12
+ # Copyright (c) Secret Labs AB 1997.
13
+ # Copyright (c) Fredrik Lundh 1997.
14
+ #
15
+ # See the README file for information on usage and redistribution.
16
+ #
17
+ import olefile
18
+
19
+ from . import Image, ImageFile
20
+ from ._binary import i32le as i32
21
+
22
+ # we map from colour field tuples to (mode, rawmode) descriptors
23
+ MODES = {
24
+ # opacity
25
+ (0x00007FFE,): ("A", "L"),
26
+ # monochrome
27
+ (0x00010000,): ("L", "L"),
28
+ (0x00018000, 0x00017FFE): ("RGBA", "LA"),
29
+ # photo YCC
30
+ (0x00020000, 0x00020001, 0x00020002): ("RGB", "YCC;P"),
31
+ (0x00028000, 0x00028001, 0x00028002, 0x00027FFE): ("RGBA", "YCCA;P"),
32
+ # standard RGB (NIFRGB)
33
+ (0x00030000, 0x00030001, 0x00030002): ("RGB", "RGB"),
34
+ (0x00038000, 0x00038001, 0x00038002, 0x00037FFE): ("RGBA", "RGBA"),
35
+ }
36
+
37
+
38
+ #
39
+ # --------------------------------------------------------------------
40
+
41
+
42
+ def _accept(prefix):
43
+ return prefix[:8] == olefile.MAGIC
44
+
45
+
46
+ ##
47
+ # Image plugin for the FlashPix images.
48
+
49
+
50
+ class FpxImageFile(ImageFile.ImageFile):
51
+ format = "FPX"
52
+ format_description = "FlashPix"
53
+
54
+ def _open(self):
55
+ #
56
+ # read the OLE directory and see if this is a likely
57
+ # to be a FlashPix file
58
+
59
+ try:
60
+ self.ole = olefile.OleFileIO(self.fp)
61
+ except OSError as e:
62
+ msg = "not an FPX file; invalid OLE file"
63
+ raise SyntaxError(msg) from e
64
+
65
+ if self.ole.root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B":
66
+ msg = "not an FPX file; bad root CLSID"
67
+ raise SyntaxError(msg)
68
+
69
+ self._open_index(1)
70
+
71
+ def _open_index(self, index=1):
72
+ #
73
+ # get the Image Contents Property Set
74
+
75
+ prop = self.ole.getproperties(
76
+ [f"Data Object Store {index:06d}", "\005Image Contents"]
77
+ )
78
+
79
+ # size (highest resolution)
80
+
81
+ self._size = prop[0x1000002], prop[0x1000003]
82
+
83
+ size = max(self.size)
84
+ i = 1
85
+ while size > 64:
86
+ size = size / 2
87
+ i += 1
88
+ self.maxid = i - 1
89
+
90
+ # mode. instead of using a single field for this, flashpix
91
+ # requires you to specify the mode for each channel in each
92
+ # resolution subimage, and leaves it to the decoder to make
93
+ # sure that they all match. for now, we'll cheat and assume
94
+ # that this is always the case.
95
+
96
+ id = self.maxid << 16
97
+
98
+ s = prop[0x2000002 | id]
99
+
100
+ colors = []
101
+ bands = i32(s, 4)
102
+ if bands > 4:
103
+ msg = "Invalid number of bands"
104
+ raise OSError(msg)
105
+ for i in range(bands):
106
+ # note: for now, we ignore the "uncalibrated" flag
107
+ colors.append(i32(s, 8 + i * 4) & 0x7FFFFFFF)
108
+
109
+ self.mode, self.rawmode = MODES[tuple(colors)]
110
+
111
+ # load JPEG tables, if any
112
+ self.jpeg = {}
113
+ for i in range(256):
114
+ id = 0x3000001 | (i << 16)
115
+ if id in prop:
116
+ self.jpeg[i] = prop[id]
117
+
118
+ self._open_subimage(1, self.maxid)
119
+
120
+ def _open_subimage(self, index=1, subimage=0):
121
+ #
122
+ # setup tile descriptors for a given subimage
123
+
124
+ stream = [
125
+ f"Data Object Store {index:06d}",
126
+ f"Resolution {subimage:04d}",
127
+ "Subimage 0000 Header",
128
+ ]
129
+
130
+ fp = self.ole.openstream(stream)
131
+
132
+ # skip prefix
133
+ fp.read(28)
134
+
135
+ # header stream
136
+ s = fp.read(36)
137
+
138
+ size = i32(s, 4), i32(s, 8)
139
+ # tilecount = i32(s, 12)
140
+ tilesize = i32(s, 16), i32(s, 20)
141
+ # channels = i32(s, 24)
142
+ offset = i32(s, 28)
143
+ length = i32(s, 32)
144
+
145
+ if size != self.size:
146
+ msg = "subimage mismatch"
147
+ raise OSError(msg)
148
+
149
+ # get tile descriptors
150
+ fp.seek(28 + offset)
151
+ s = fp.read(i32(s, 12) * length)
152
+
153
+ x = y = 0
154
+ xsize, ysize = size
155
+ xtile, ytile = tilesize
156
+ self.tile = []
157
+
158
+ for i in range(0, len(s), length):
159
+ x1 = min(xsize, x + xtile)
160
+ y1 = min(ysize, y + ytile)
161
+
162
+ compression = i32(s, i + 8)
163
+
164
+ if compression == 0:
165
+ self.tile.append(
166
+ (
167
+ "raw",
168
+ (x, y, x1, y1),
169
+ i32(s, i) + 28,
170
+ (self.rawmode,),
171
+ )
172
+ )
173
+
174
+ elif compression == 1:
175
+ # FIXME: the fill decoder is not implemented
176
+ self.tile.append(
177
+ (
178
+ "fill",
179
+ (x, y, x1, y1),
180
+ i32(s, i) + 28,
181
+ (self.rawmode, s[12:16]),
182
+ )
183
+ )
184
+
185
+ elif compression == 2:
186
+ internal_color_conversion = s[14]
187
+ jpeg_tables = s[15]
188
+ rawmode = self.rawmode
189
+
190
+ if internal_color_conversion:
191
+ # The image is stored as usual (usually YCbCr).
192
+ if rawmode == "RGBA":
193
+ # For "RGBA", data is stored as YCbCrA based on
194
+ # negative RGB. The following trick works around
195
+ # this problem :
196
+ jpegmode, rawmode = "YCbCrK", "CMYK"
197
+ else:
198
+ jpegmode = None # let the decoder decide
199
+
200
+ else:
201
+ # The image is stored as defined by rawmode
202
+ jpegmode = rawmode
203
+
204
+ self.tile.append(
205
+ (
206
+ "jpeg",
207
+ (x, y, x1, y1),
208
+ i32(s, i) + 28,
209
+ (rawmode, jpegmode),
210
+ )
211
+ )
212
+
213
+ # FIXME: jpeg tables are tile dependent; the prefix
214
+ # data must be placed in the tile descriptor itself!
215
+
216
+ if jpeg_tables:
217
+ self.tile_prefix = self.jpeg[jpeg_tables]
218
+
219
+ else:
220
+ msg = "unknown/invalid compression"
221
+ raise OSError(msg)
222
+
223
+ x = x + xtile
224
+ if x >= xsize:
225
+ x, y = 0, y + ytile
226
+ if y >= ysize:
227
+ break # isn't really required
228
+
229
+ self.stream = stream
230
+ self.fp = None
231
+
232
+ def load(self):
233
+ if not self.fp:
234
+ self.fp = self.ole.openstream(self.stream[:2] + ["Subimage 0000 Data"])
235
+
236
+ return ImageFile.ImageFile.load(self)
237
+
238
+ def close(self):
239
+ self.ole.close()
240
+ super().close()
241
+
242
+ def __exit__(self, *args):
243
+ self.ole.close()
244
+ super().__exit__()
245
+
246
+
247
+ #
248
+ # --------------------------------------------------------------------
249
+
250
+
251
+ Image.register_open(FpxImageFile.format, FpxImageFile, _accept)
252
+
253
+ Image.register_extension(FpxImageFile.format, ".fpx")
Lib/site-packages/PIL/FtexImagePlugin.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A Pillow loader for .ftc and .ftu files (FTEX)
3
+ Jerome Leclanche <[email protected]>
4
+
5
+ The contents of this file are hereby released in the public domain (CC0)
6
+ Full text of the CC0 license:
7
+ https://creativecommons.org/publicdomain/zero/1.0/
8
+
9
+ Independence War 2: Edge Of Chaos - Texture File Format - 16 October 2001
10
+
11
+ The textures used for 3D objects in Independence War 2: Edge Of Chaos are in a
12
+ packed custom format called FTEX. This file format uses file extensions FTC
13
+ and FTU.
14
+ * FTC files are compressed textures (using standard texture compression).
15
+ * FTU files are not compressed.
16
+ Texture File Format
17
+ The FTC and FTU texture files both use the same format. This
18
+ has the following structure:
19
+ {header}
20
+ {format_directory}
21
+ {data}
22
+ Where:
23
+ {header} = {
24
+ u32:magic,
25
+ u32:version,
26
+ u32:width,
27
+ u32:height,
28
+ u32:mipmap_count,
29
+ u32:format_count
30
+ }
31
+
32
+ * The "magic" number is "FTEX".
33
+ * "width" and "height" are the dimensions of the texture.
34
+ * "mipmap_count" is the number of mipmaps in the texture.
35
+ * "format_count" is the number of texture formats (different versions of the
36
+ same texture) in this file.
37
+
38
+ {format_directory} = format_count * { u32:format, u32:where }
39
+
40
+ The format value is 0 for DXT1 compressed textures and 1 for 24-bit RGB
41
+ uncompressed textures.
42
+ The texture data for a format starts at the position "where" in the file.
43
+
44
+ Each set of texture data in the file has the following structure:
45
+ {data} = format_count * { u32:mipmap_size, mipmap_size * { u8 } }
46
+ * "mipmap_size" is the number of bytes in that mip level. For compressed
47
+ textures this is the size of the texture data compressed with DXT1. For 24 bit
48
+ uncompressed textures, this is 3 * width * height. Following this are the image
49
+ bytes for that mipmap level.
50
+
51
+ Note: All data is stored in little-Endian (Intel) byte order.
52
+ """
53
+
54
+ import struct
55
+ from enum import IntEnum
56
+ from io import BytesIO
57
+
58
+ from . import Image, ImageFile
59
+
60
+ MAGIC = b"FTEX"
61
+
62
+
63
+ class Format(IntEnum):
64
+ DXT1 = 0
65
+ UNCOMPRESSED = 1
66
+
67
+
68
+ class FtexImageFile(ImageFile.ImageFile):
69
+ format = "FTEX"
70
+ format_description = "Texture File Format (IW2:EOC)"
71
+
72
+ def _open(self):
73
+ if not _accept(self.fp.read(4)):
74
+ msg = "not an FTEX file"
75
+ raise SyntaxError(msg)
76
+ struct.unpack("<i", self.fp.read(4)) # version
77
+ self._size = struct.unpack("<2i", self.fp.read(8))
78
+ mipmap_count, format_count = struct.unpack("<2i", self.fp.read(8))
79
+
80
+ self.mode = "RGB"
81
+
82
+ # Only support single-format files.
83
+ # I don't know of any multi-format file.
84
+ assert format_count == 1
85
+
86
+ format, where = struct.unpack("<2i", self.fp.read(8))
87
+ self.fp.seek(where)
88
+ (mipmap_size,) = struct.unpack("<i", self.fp.read(4))
89
+
90
+ data = self.fp.read(mipmap_size)
91
+
92
+ if format == Format.DXT1:
93
+ self.mode = "RGBA"
94
+ self.tile = [("bcn", (0, 0) + self.size, 0, 1)]
95
+ elif format == Format.UNCOMPRESSED:
96
+ self.tile = [("raw", (0, 0) + self.size, 0, ("RGB", 0, 1))]
97
+ else:
98
+ msg = f"Invalid texture compression format: {repr(format)}"
99
+ raise ValueError(msg)
100
+
101
+ self.fp.close()
102
+ self.fp = BytesIO(data)
103
+
104
+ def load_seek(self, pos):
105
+ pass
106
+
107
+
108
+ def _accept(prefix):
109
+ return prefix[:4] == MAGIC
110
+
111
+
112
+ Image.register_open(FtexImageFile.format, FtexImageFile, _accept)
113
+ Image.register_extensions(FtexImageFile.format, [".ftc", ".ftu"])
Lib/site-packages/PIL/GbrImagePlugin.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ #
4
+ # load a GIMP brush file
5
+ #
6
+ # History:
7
+ # 96-03-14 fl Created
8
+ # 16-01-08 es Version 2
9
+ #
10
+ # Copyright (c) Secret Labs AB 1997.
11
+ # Copyright (c) Fredrik Lundh 1996.
12
+ # Copyright (c) Eric Soroos 2016.
13
+ #
14
+ # See the README file for information on usage and redistribution.
15
+ #
16
+ #
17
+ # See https://github.com/GNOME/gimp/blob/mainline/devel-docs/gbr.txt for
18
+ # format documentation.
19
+ #
20
+ # This code Interprets version 1 and 2 .gbr files.
21
+ # Version 1 files are obsolete, and should not be used for new
22
+ # brushes.
23
+ # Version 2 files are saved by GIMP v2.8 (at least)
24
+ # Version 3 files have a format specifier of 18 for 16bit floats in
25
+ # the color depth field. This is currently unsupported by Pillow.
26
+
27
+ from . import Image, ImageFile
28
+ from ._binary import i32be as i32
29
+
30
+
31
+ def _accept(prefix):
32
+ return len(prefix) >= 8 and i32(prefix, 0) >= 20 and i32(prefix, 4) in (1, 2)
33
+
34
+
35
+ ##
36
+ # Image plugin for the GIMP brush format.
37
+
38
+
39
+ class GbrImageFile(ImageFile.ImageFile):
40
+ format = "GBR"
41
+ format_description = "GIMP brush file"
42
+
43
+ def _open(self):
44
+ header_size = i32(self.fp.read(4))
45
+ if header_size < 20:
46
+ msg = "not a GIMP brush"
47
+ raise SyntaxError(msg)
48
+ version = i32(self.fp.read(4))
49
+ if version not in (1, 2):
50
+ msg = f"Unsupported GIMP brush version: {version}"
51
+ raise SyntaxError(msg)
52
+
53
+ width = i32(self.fp.read(4))
54
+ height = i32(self.fp.read(4))
55
+ color_depth = i32(self.fp.read(4))
56
+ if width <= 0 or height <= 0:
57
+ msg = "not a GIMP brush"
58
+ raise SyntaxError(msg)
59
+ if color_depth not in (1, 4):
60
+ msg = f"Unsupported GIMP brush color depth: {color_depth}"
61
+ raise SyntaxError(msg)
62
+
63
+ if version == 1:
64
+ comment_length = header_size - 20
65
+ else:
66
+ comment_length = header_size - 28
67
+ magic_number = self.fp.read(4)
68
+ if magic_number != b"GIMP":
69
+ msg = "not a GIMP brush, bad magic number"
70
+ raise SyntaxError(msg)
71
+ self.info["spacing"] = i32(self.fp.read(4))
72
+
73
+ comment = self.fp.read(comment_length)[:-1]
74
+
75
+ if color_depth == 1:
76
+ self.mode = "L"
77
+ else:
78
+ self.mode = "RGBA"
79
+
80
+ self._size = width, height
81
+
82
+ self.info["comment"] = comment
83
+
84
+ # Image might not be small
85
+ Image._decompression_bomb_check(self.size)
86
+
87
+ # Data is an uncompressed block of w * h * bytes/pixel
88
+ self._data_size = width * height * color_depth
89
+
90
+ def load(self):
91
+ if not self.im:
92
+ self.im = Image.core.new(self.mode, self.size)
93
+ self.frombytes(self.fp.read(self._data_size))
94
+ return Image.Image.load(self)
95
+
96
+
97
+ #
98
+ # registry
99
+
100
+
101
+ Image.register_open(GbrImageFile.format, GbrImageFile, _accept)
102
+ Image.register_extension(GbrImageFile.format, ".gbr")
Lib/site-packages/PIL/GdImageFile.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # GD file handling
6
+ #
7
+ # History:
8
+ # 1996-04-12 fl Created
9
+ #
10
+ # Copyright (c) 1997 by Secret Labs AB.
11
+ # Copyright (c) 1996 by Fredrik Lundh.
12
+ #
13
+ # See the README file for information on usage and redistribution.
14
+ #
15
+
16
+
17
+ """
18
+ .. note::
19
+ This format cannot be automatically recognized, so the
20
+ class is not registered for use with :py:func:`PIL.Image.open()`. To open a
21
+ gd file, use the :py:func:`PIL.GdImageFile.open()` function instead.
22
+
23
+ .. warning::
24
+ THE GD FORMAT IS NOT DESIGNED FOR DATA INTERCHANGE. This
25
+ implementation is provided for convenience and demonstrational
26
+ purposes only.
27
+ """
28
+
29
+
30
+ from . import ImageFile, ImagePalette, UnidentifiedImageError
31
+ from ._binary import i16be as i16
32
+ from ._binary import i32be as i32
33
+
34
+
35
+ class GdImageFile(ImageFile.ImageFile):
36
+ """
37
+ Image plugin for the GD uncompressed format. Note that this format
38
+ is not supported by the standard :py:func:`PIL.Image.open()` function. To use
39
+ this plugin, you have to import the :py:mod:`PIL.GdImageFile` module and
40
+ use the :py:func:`PIL.GdImageFile.open()` function.
41
+ """
42
+
43
+ format = "GD"
44
+ format_description = "GD uncompressed images"
45
+
46
+ def _open(self):
47
+ # Header
48
+ s = self.fp.read(1037)
49
+
50
+ if i16(s) not in [65534, 65535]:
51
+ msg = "Not a valid GD 2.x .gd file"
52
+ raise SyntaxError(msg)
53
+
54
+ self.mode = "L" # FIXME: "P"
55
+ self._size = i16(s, 2), i16(s, 4)
56
+
57
+ true_color = s[6]
58
+ true_color_offset = 2 if true_color else 0
59
+
60
+ # transparency index
61
+ tindex = i32(s, 7 + true_color_offset)
62
+ if tindex < 256:
63
+ self.info["transparency"] = tindex
64
+
65
+ self.palette = ImagePalette.raw(
66
+ "XBGR", s[7 + true_color_offset + 4 : 7 + true_color_offset + 4 + 256 * 4]
67
+ )
68
+
69
+ self.tile = [
70
+ (
71
+ "raw",
72
+ (0, 0) + self.size,
73
+ 7 + true_color_offset + 4 + 256 * 4,
74
+ ("L", 0, 1),
75
+ )
76
+ ]
77
+
78
+
79
+ def open(fp, mode="r"):
80
+ """
81
+ Load texture from a GD image file.
82
+
83
+ :param fp: GD file name, or an opened file handle.
84
+ :param mode: Optional mode. In this version, if the mode argument
85
+ is given, it must be "r".
86
+ :returns: An image instance.
87
+ :raises OSError: If the image could not be read.
88
+ """
89
+ if mode != "r":
90
+ msg = "bad mode"
91
+ raise ValueError(msg)
92
+
93
+ try:
94
+ return GdImageFile(fp)
95
+ except SyntaxError as e:
96
+ msg = "cannot identify this image file"
97
+ raise UnidentifiedImageError(msg) from e
Lib/site-packages/PIL/GifImagePlugin.py ADDED
@@ -0,0 +1,1064 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # GIF file handling
6
+ #
7
+ # History:
8
+ # 1995-09-01 fl Created
9
+ # 1996-12-14 fl Added interlace support
10
+ # 1996-12-30 fl Added animation support
11
+ # 1997-01-05 fl Added write support, fixed local colour map bug
12
+ # 1997-02-23 fl Make sure to load raster data in getdata()
13
+ # 1997-07-05 fl Support external decoder (0.4)
14
+ # 1998-07-09 fl Handle all modes when saving (0.5)
15
+ # 1998-07-15 fl Renamed offset attribute to avoid name clash
16
+ # 2001-04-16 fl Added rewind support (seek to frame 0) (0.6)
17
+ # 2001-04-17 fl Added palette optimization (0.7)
18
+ # 2002-06-06 fl Added transparency support for save (0.8)
19
+ # 2004-02-24 fl Disable interlacing for small images
20
+ #
21
+ # Copyright (c) 1997-2004 by Secret Labs AB
22
+ # Copyright (c) 1995-2004 by Fredrik Lundh
23
+ #
24
+ # See the README file for information on usage and redistribution.
25
+ #
26
+
27
+ import itertools
28
+ import math
29
+ import os
30
+ import subprocess
31
+ from enum import IntEnum
32
+
33
+ from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence
34
+ from ._binary import i16le as i16
35
+ from ._binary import o8
36
+ from ._binary import o16le as o16
37
+
38
+
39
+ class LoadingStrategy(IntEnum):
40
+ """.. versionadded:: 9.1.0"""
41
+
42
+ RGB_AFTER_FIRST = 0
43
+ RGB_AFTER_DIFFERENT_PALETTE_ONLY = 1
44
+ RGB_ALWAYS = 2
45
+
46
+
47
+ #: .. versionadded:: 9.1.0
48
+ LOADING_STRATEGY = LoadingStrategy.RGB_AFTER_FIRST
49
+
50
+ # --------------------------------------------------------------------
51
+ # Identify/read GIF files
52
+
53
+
54
+ def _accept(prefix):
55
+ return prefix[:6] in [b"GIF87a", b"GIF89a"]
56
+
57
+
58
+ ##
59
+ # Image plugin for GIF images. This plugin supports both GIF87 and
60
+ # GIF89 images.
61
+
62
+
63
+ class GifImageFile(ImageFile.ImageFile):
64
+ format = "GIF"
65
+ format_description = "Compuserve GIF"
66
+ _close_exclusive_fp_after_loading = False
67
+
68
+ global_palette = None
69
+
70
+ def data(self):
71
+ s = self.fp.read(1)
72
+ if s and s[0]:
73
+ return self.fp.read(s[0])
74
+ return None
75
+
76
+ def _is_palette_needed(self, p):
77
+ for i in range(0, len(p), 3):
78
+ if not (i // 3 == p[i] == p[i + 1] == p[i + 2]):
79
+ return True
80
+ return False
81
+
82
+ def _open(self):
83
+ # Screen
84
+ s = self.fp.read(13)
85
+ if not _accept(s):
86
+ msg = "not a GIF file"
87
+ raise SyntaxError(msg)
88
+
89
+ self.info["version"] = s[:6]
90
+ self._size = i16(s, 6), i16(s, 8)
91
+ self.tile = []
92
+ flags = s[10]
93
+ bits = (flags & 7) + 1
94
+
95
+ if flags & 128:
96
+ # get global palette
97
+ self.info["background"] = s[11]
98
+ # check if palette contains colour indices
99
+ p = self.fp.read(3 << bits)
100
+ if self._is_palette_needed(p):
101
+ p = ImagePalette.raw("RGB", p)
102
+ self.global_palette = self.palette = p
103
+
104
+ self._fp = self.fp # FIXME: hack
105
+ self.__rewind = self.fp.tell()
106
+ self._n_frames = None
107
+ self._is_animated = None
108
+ self._seek(0) # get ready to read first frame
109
+
110
+ @property
111
+ def n_frames(self):
112
+ if self._n_frames is None:
113
+ current = self.tell()
114
+ try:
115
+ while True:
116
+ self._seek(self.tell() + 1, False)
117
+ except EOFError:
118
+ self._n_frames = self.tell() + 1
119
+ self.seek(current)
120
+ return self._n_frames
121
+
122
+ @property
123
+ def is_animated(self):
124
+ if self._is_animated is None:
125
+ if self._n_frames is not None:
126
+ self._is_animated = self._n_frames != 1
127
+ else:
128
+ current = self.tell()
129
+ if current:
130
+ self._is_animated = True
131
+ else:
132
+ try:
133
+ self._seek(1, False)
134
+ self._is_animated = True
135
+ except EOFError:
136
+ self._is_animated = False
137
+
138
+ self.seek(current)
139
+ return self._is_animated
140
+
141
+ def seek(self, frame):
142
+ if not self._seek_check(frame):
143
+ return
144
+ if frame < self.__frame:
145
+ self.im = None
146
+ self._seek(0)
147
+
148
+ last_frame = self.__frame
149
+ for f in range(self.__frame + 1, frame + 1):
150
+ try:
151
+ self._seek(f)
152
+ except EOFError as e:
153
+ self.seek(last_frame)
154
+ msg = "no more images in GIF file"
155
+ raise EOFError(msg) from e
156
+
157
+ def _seek(self, frame, update_image=True):
158
+ if frame == 0:
159
+ # rewind
160
+ self.__offset = 0
161
+ self.dispose = None
162
+ self.__frame = -1
163
+ self._fp.seek(self.__rewind)
164
+ self.disposal_method = 0
165
+ if "comment" in self.info:
166
+ del self.info["comment"]
167
+ else:
168
+ # ensure that the previous frame was loaded
169
+ if self.tile and update_image:
170
+ self.load()
171
+
172
+ if frame != self.__frame + 1:
173
+ msg = f"cannot seek to frame {frame}"
174
+ raise ValueError(msg)
175
+
176
+ self.fp = self._fp
177
+ if self.__offset:
178
+ # backup to last frame
179
+ self.fp.seek(self.__offset)
180
+ while self.data():
181
+ pass
182
+ self.__offset = 0
183
+
184
+ s = self.fp.read(1)
185
+ if not s or s == b";":
186
+ raise EOFError
187
+
188
+ palette = None
189
+
190
+ info = {}
191
+ frame_transparency = None
192
+ interlace = None
193
+ frame_dispose_extent = None
194
+ while True:
195
+ if not s:
196
+ s = self.fp.read(1)
197
+ if not s or s == b";":
198
+ break
199
+
200
+ elif s == b"!":
201
+ #
202
+ # extensions
203
+ #
204
+ s = self.fp.read(1)
205
+ block = self.data()
206
+ if s[0] == 249:
207
+ #
208
+ # graphic control extension
209
+ #
210
+ flags = block[0]
211
+ if flags & 1:
212
+ frame_transparency = block[3]
213
+ info["duration"] = i16(block, 1) * 10
214
+
215
+ # disposal method - find the value of bits 4 - 6
216
+ dispose_bits = 0b00011100 & flags
217
+ dispose_bits = dispose_bits >> 2
218
+ if dispose_bits:
219
+ # only set the dispose if it is not
220
+ # unspecified. I'm not sure if this is
221
+ # correct, but it seems to prevent the last
222
+ # frame from looking odd for some animations
223
+ self.disposal_method = dispose_bits
224
+ elif s[0] == 254:
225
+ #
226
+ # comment extension
227
+ #
228
+ comment = b""
229
+
230
+ # Read this comment block
231
+ while block:
232
+ comment += block
233
+ block = self.data()
234
+
235
+ if "comment" in info:
236
+ # If multiple comment blocks in frame, separate with \n
237
+ info["comment"] += b"\n" + comment
238
+ else:
239
+ info["comment"] = comment
240
+ s = None
241
+ continue
242
+ elif s[0] == 255 and frame == 0:
243
+ #
244
+ # application extension
245
+ #
246
+ info["extension"] = block, self.fp.tell()
247
+ if block[:11] == b"NETSCAPE2.0":
248
+ block = self.data()
249
+ if len(block) >= 3 and block[0] == 1:
250
+ self.info["loop"] = i16(block, 1)
251
+ while self.data():
252
+ pass
253
+
254
+ elif s == b",":
255
+ #
256
+ # local image
257
+ #
258
+ s = self.fp.read(9)
259
+
260
+ # extent
261
+ x0, y0 = i16(s, 0), i16(s, 2)
262
+ x1, y1 = x0 + i16(s, 4), y0 + i16(s, 6)
263
+ if (x1 > self.size[0] or y1 > self.size[1]) and update_image:
264
+ self._size = max(x1, self.size[0]), max(y1, self.size[1])
265
+ Image._decompression_bomb_check(self._size)
266
+ frame_dispose_extent = x0, y0, x1, y1
267
+ flags = s[8]
268
+
269
+ interlace = (flags & 64) != 0
270
+
271
+ if flags & 128:
272
+ bits = (flags & 7) + 1
273
+ p = self.fp.read(3 << bits)
274
+ if self._is_palette_needed(p):
275
+ palette = ImagePalette.raw("RGB", p)
276
+ else:
277
+ palette = False
278
+
279
+ # image data
280
+ bits = self.fp.read(1)[0]
281
+ self.__offset = self.fp.tell()
282
+ break
283
+
284
+ else:
285
+ pass
286
+ # raise OSError, "illegal GIF tag `%x`" % s[0]
287
+ s = None
288
+
289
+ if interlace is None:
290
+ # self._fp = None
291
+ raise EOFError
292
+
293
+ self.__frame = frame
294
+ if not update_image:
295
+ return
296
+
297
+ self.tile = []
298
+
299
+ if self.dispose:
300
+ self.im.paste(self.dispose, self.dispose_extent)
301
+
302
+ self._frame_palette = palette if palette is not None else self.global_palette
303
+ self._frame_transparency = frame_transparency
304
+ if frame == 0:
305
+ if self._frame_palette:
306
+ if LOADING_STRATEGY == LoadingStrategy.RGB_ALWAYS:
307
+ self.mode = "RGBA" if frame_transparency is not None else "RGB"
308
+ else:
309
+ self.mode = "P"
310
+ else:
311
+ self.mode = "L"
312
+
313
+ if not palette and self.global_palette:
314
+ from copy import copy
315
+
316
+ palette = copy(self.global_palette)
317
+ self.palette = palette
318
+ else:
319
+ if self.mode == "P":
320
+ if (
321
+ LOADING_STRATEGY != LoadingStrategy.RGB_AFTER_DIFFERENT_PALETTE_ONLY
322
+ or palette
323
+ ):
324
+ self.pyaccess = None
325
+ if "transparency" in self.info:
326
+ self.im.putpalettealpha(self.info["transparency"], 0)
327
+ self.im = self.im.convert("RGBA", Image.Dither.FLOYDSTEINBERG)
328
+ self.mode = "RGBA"
329
+ del self.info["transparency"]
330
+ else:
331
+ self.mode = "RGB"
332
+ self.im = self.im.convert("RGB", Image.Dither.FLOYDSTEINBERG)
333
+
334
+ def _rgb(color):
335
+ if self._frame_palette:
336
+ color = tuple(self._frame_palette.palette[color * 3 : color * 3 + 3])
337
+ else:
338
+ color = (color, color, color)
339
+ return color
340
+
341
+ self.dispose_extent = frame_dispose_extent
342
+ try:
343
+ if self.disposal_method < 2:
344
+ # do not dispose or none specified
345
+ self.dispose = None
346
+ elif self.disposal_method == 2:
347
+ # replace with background colour
348
+
349
+ # only dispose the extent in this frame
350
+ x0, y0, x1, y1 = self.dispose_extent
351
+ dispose_size = (x1 - x0, y1 - y0)
352
+
353
+ Image._decompression_bomb_check(dispose_size)
354
+
355
+ # by convention, attempt to use transparency first
356
+ dispose_mode = "P"
357
+ color = self.info.get("transparency", frame_transparency)
358
+ if color is not None:
359
+ if self.mode in ("RGB", "RGBA"):
360
+ dispose_mode = "RGBA"
361
+ color = _rgb(color) + (0,)
362
+ else:
363
+ color = self.info.get("background", 0)
364
+ if self.mode in ("RGB", "RGBA"):
365
+ dispose_mode = "RGB"
366
+ color = _rgb(color)
367
+ self.dispose = Image.core.fill(dispose_mode, dispose_size, color)
368
+ else:
369
+ # replace with previous contents
370
+ if self.im is not None:
371
+ # only dispose the extent in this frame
372
+ self.dispose = self._crop(self.im, self.dispose_extent)
373
+ elif frame_transparency is not None:
374
+ x0, y0, x1, y1 = self.dispose_extent
375
+ dispose_size = (x1 - x0, y1 - y0)
376
+
377
+ Image._decompression_bomb_check(dispose_size)
378
+ dispose_mode = "P"
379
+ color = frame_transparency
380
+ if self.mode in ("RGB", "RGBA"):
381
+ dispose_mode = "RGBA"
382
+ color = _rgb(frame_transparency) + (0,)
383
+ self.dispose = Image.core.fill(dispose_mode, dispose_size, color)
384
+ except AttributeError:
385
+ pass
386
+
387
+ if interlace is not None:
388
+ transparency = -1
389
+ if frame_transparency is not None:
390
+ if frame == 0:
391
+ if LOADING_STRATEGY != LoadingStrategy.RGB_ALWAYS:
392
+ self.info["transparency"] = frame_transparency
393
+ elif self.mode not in ("RGB", "RGBA"):
394
+ transparency = frame_transparency
395
+ self.tile = [
396
+ (
397
+ "gif",
398
+ (x0, y0, x1, y1),
399
+ self.__offset,
400
+ (bits, interlace, transparency),
401
+ )
402
+ ]
403
+
404
+ if info.get("comment"):
405
+ self.info["comment"] = info["comment"]
406
+ for k in ["duration", "extension"]:
407
+ if k in info:
408
+ self.info[k] = info[k]
409
+ elif k in self.info:
410
+ del self.info[k]
411
+
412
+ def load_prepare(self):
413
+ temp_mode = "P" if self._frame_palette else "L"
414
+ self._prev_im = None
415
+ if self.__frame == 0:
416
+ if self._frame_transparency is not None:
417
+ self.im = Image.core.fill(
418
+ temp_mode, self.size, self._frame_transparency
419
+ )
420
+ elif self.mode in ("RGB", "RGBA"):
421
+ self._prev_im = self.im
422
+ if self._frame_palette:
423
+ self.im = Image.core.fill("P", self.size, self._frame_transparency or 0)
424
+ self.im.putpalette(*self._frame_palette.getdata())
425
+ else:
426
+ self.im = None
427
+ self.mode = temp_mode
428
+ self._frame_palette = None
429
+
430
+ super().load_prepare()
431
+
432
+ def load_end(self):
433
+ if self.__frame == 0:
434
+ if self.mode == "P" and LOADING_STRATEGY == LoadingStrategy.RGB_ALWAYS:
435
+ if self._frame_transparency is not None:
436
+ self.im.putpalettealpha(self._frame_transparency, 0)
437
+ self.mode = "RGBA"
438
+ else:
439
+ self.mode = "RGB"
440
+ self.im = self.im.convert(self.mode, Image.Dither.FLOYDSTEINBERG)
441
+ return
442
+ if not self._prev_im:
443
+ return
444
+ if self._frame_transparency is not None:
445
+ self.im.putpalettealpha(self._frame_transparency, 0)
446
+ frame_im = self.im.convert("RGBA")
447
+ else:
448
+ frame_im = self.im.convert("RGB")
449
+ frame_im = self._crop(frame_im, self.dispose_extent)
450
+
451
+ self.im = self._prev_im
452
+ self.mode = self.im.mode
453
+ if frame_im.mode == "RGBA":
454
+ self.im.paste(frame_im, self.dispose_extent, frame_im)
455
+ else:
456
+ self.im.paste(frame_im, self.dispose_extent)
457
+
458
+ def tell(self):
459
+ return self.__frame
460
+
461
+
462
+ # --------------------------------------------------------------------
463
+ # Write GIF files
464
+
465
+
466
+ RAWMODE = {"1": "L", "L": "L", "P": "P"}
467
+
468
+
469
+ def _normalize_mode(im):
470
+ """
471
+ Takes an image (or frame), returns an image in a mode that is appropriate
472
+ for saving in a Gif.
473
+
474
+ It may return the original image, or it may return an image converted to
475
+ palette or 'L' mode.
476
+
477
+ :param im: Image object
478
+ :returns: Image object
479
+ """
480
+ if im.mode in RAWMODE:
481
+ im.load()
482
+ return im
483
+ if Image.getmodebase(im.mode) == "RGB":
484
+ im = im.convert("P", palette=Image.Palette.ADAPTIVE)
485
+ if im.palette.mode == "RGBA":
486
+ for rgba in im.palette.colors:
487
+ if rgba[3] == 0:
488
+ im.info["transparency"] = im.palette.colors[rgba]
489
+ break
490
+ return im
491
+ return im.convert("L")
492
+
493
+
494
+ def _normalize_palette(im, palette, info):
495
+ """
496
+ Normalizes the palette for image.
497
+ - Sets the palette to the incoming palette, if provided.
498
+ - Ensures that there's a palette for L mode images
499
+ - Optimizes the palette if necessary/desired.
500
+
501
+ :param im: Image object
502
+ :param palette: bytes object containing the source palette, or ....
503
+ :param info: encoderinfo
504
+ :returns: Image object
505
+ """
506
+ source_palette = None
507
+ if palette:
508
+ # a bytes palette
509
+ if isinstance(palette, (bytes, bytearray, list)):
510
+ source_palette = bytearray(palette[:768])
511
+ if isinstance(palette, ImagePalette.ImagePalette):
512
+ source_palette = bytearray(palette.palette)
513
+
514
+ if im.mode == "P":
515
+ if not source_palette:
516
+ source_palette = im.im.getpalette("RGB")[:768]
517
+ else: # L-mode
518
+ if not source_palette:
519
+ source_palette = bytearray(i // 3 for i in range(768))
520
+ im.palette = ImagePalette.ImagePalette("RGB", palette=source_palette)
521
+
522
+ if palette:
523
+ used_palette_colors = []
524
+ for i in range(0, len(source_palette), 3):
525
+ source_color = tuple(source_palette[i : i + 3])
526
+ index = im.palette.colors.get(source_color)
527
+ if index in used_palette_colors:
528
+ index = None
529
+ used_palette_colors.append(index)
530
+ for i, index in enumerate(used_palette_colors):
531
+ if index is None:
532
+ for j in range(len(used_palette_colors)):
533
+ if j not in used_palette_colors:
534
+ used_palette_colors[i] = j
535
+ break
536
+ im = im.remap_palette(used_palette_colors)
537
+ else:
538
+ used_palette_colors = _get_optimize(im, info)
539
+ if used_palette_colors is not None:
540
+ return im.remap_palette(used_palette_colors, source_palette)
541
+
542
+ im.palette.palette = source_palette
543
+ return im
544
+
545
+
546
+ def _write_single_frame(im, fp, palette):
547
+ im_out = _normalize_mode(im)
548
+ for k, v in im_out.info.items():
549
+ im.encoderinfo.setdefault(k, v)
550
+ im_out = _normalize_palette(im_out, palette, im.encoderinfo)
551
+
552
+ for s in _get_global_header(im_out, im.encoderinfo):
553
+ fp.write(s)
554
+
555
+ # local image header
556
+ flags = 0
557
+ if get_interlace(im):
558
+ flags = flags | 64
559
+ _write_local_header(fp, im, (0, 0), flags)
560
+
561
+ im_out.encoderconfig = (8, get_interlace(im))
562
+ ImageFile._save(im_out, fp, [("gif", (0, 0) + im.size, 0, RAWMODE[im_out.mode])])
563
+
564
+ fp.write(b"\0") # end of image data
565
+
566
+
567
+ def _getbbox(base_im, im_frame):
568
+ if _get_palette_bytes(im_frame) == _get_palette_bytes(base_im):
569
+ delta = ImageChops.subtract_modulo(im_frame, base_im)
570
+ else:
571
+ delta = ImageChops.subtract_modulo(
572
+ im_frame.convert("RGBA"), base_im.convert("RGBA")
573
+ )
574
+ return delta.getbbox(alpha_only=False)
575
+
576
+
577
+ def _write_multiple_frames(im, fp, palette):
578
+ duration = im.encoderinfo.get("duration")
579
+ disposal = im.encoderinfo.get("disposal", im.info.get("disposal"))
580
+
581
+ im_frames = []
582
+ frame_count = 0
583
+ background_im = None
584
+ for imSequence in itertools.chain([im], im.encoderinfo.get("append_images", [])):
585
+ for im_frame in ImageSequence.Iterator(imSequence):
586
+ # a copy is required here since seek can still mutate the image
587
+ im_frame = _normalize_mode(im_frame.copy())
588
+ if frame_count == 0:
589
+ for k, v in im_frame.info.items():
590
+ if k == "transparency":
591
+ continue
592
+ im.encoderinfo.setdefault(k, v)
593
+
594
+ encoderinfo = im.encoderinfo.copy()
595
+ im_frame = _normalize_palette(im_frame, palette, encoderinfo)
596
+ if "transparency" in im_frame.info:
597
+ encoderinfo.setdefault("transparency", im_frame.info["transparency"])
598
+ if isinstance(duration, (list, tuple)):
599
+ encoderinfo["duration"] = duration[frame_count]
600
+ elif duration is None and "duration" in im_frame.info:
601
+ encoderinfo["duration"] = im_frame.info["duration"]
602
+ if isinstance(disposal, (list, tuple)):
603
+ encoderinfo["disposal"] = disposal[frame_count]
604
+ frame_count += 1
605
+
606
+ if im_frames:
607
+ # delta frame
608
+ previous = im_frames[-1]
609
+ bbox = _getbbox(previous["im"], im_frame)
610
+ if not bbox:
611
+ # This frame is identical to the previous frame
612
+ if encoderinfo.get("duration"):
613
+ previous["encoderinfo"]["duration"] += encoderinfo["duration"]
614
+ continue
615
+ if encoderinfo.get("disposal") == 2:
616
+ if background_im is None:
617
+ color = im.encoderinfo.get(
618
+ "transparency", im.info.get("transparency", (0, 0, 0))
619
+ )
620
+ background = _get_background(im_frame, color)
621
+ background_im = Image.new("P", im_frame.size, background)
622
+ background_im.putpalette(im_frames[0]["im"].palette)
623
+ bbox = _getbbox(background_im, im_frame)
624
+ else:
625
+ bbox = None
626
+ im_frames.append({"im": im_frame, "bbox": bbox, "encoderinfo": encoderinfo})
627
+
628
+ if len(im_frames) > 1:
629
+ for frame_data in im_frames:
630
+ im_frame = frame_data["im"]
631
+ if not frame_data["bbox"]:
632
+ # global header
633
+ for s in _get_global_header(im_frame, frame_data["encoderinfo"]):
634
+ fp.write(s)
635
+ offset = (0, 0)
636
+ else:
637
+ # compress difference
638
+ if not palette:
639
+ frame_data["encoderinfo"]["include_color_table"] = True
640
+
641
+ im_frame = im_frame.crop(frame_data["bbox"])
642
+ offset = frame_data["bbox"][:2]
643
+ _write_frame_data(fp, im_frame, offset, frame_data["encoderinfo"])
644
+ return True
645
+ elif "duration" in im.encoderinfo and isinstance(
646
+ im.encoderinfo["duration"], (list, tuple)
647
+ ):
648
+ # Since multiple frames will not be written, add together the frame durations
649
+ im.encoderinfo["duration"] = sum(im.encoderinfo["duration"])
650
+
651
+
652
+ def _save_all(im, fp, filename):
653
+ _save(im, fp, filename, save_all=True)
654
+
655
+
656
+ def _save(im, fp, filename, save_all=False):
657
+ # header
658
+ if "palette" in im.encoderinfo or "palette" in im.info:
659
+ palette = im.encoderinfo.get("palette", im.info.get("palette"))
660
+ else:
661
+ palette = None
662
+ im.encoderinfo["optimize"] = im.encoderinfo.get("optimize", True)
663
+
664
+ if not save_all or not _write_multiple_frames(im, fp, palette):
665
+ _write_single_frame(im, fp, palette)
666
+
667
+ fp.write(b";") # end of file
668
+
669
+ if hasattr(fp, "flush"):
670
+ fp.flush()
671
+
672
+
673
+ def get_interlace(im):
674
+ interlace = im.encoderinfo.get("interlace", 1)
675
+
676
+ # workaround for @PIL153
677
+ if min(im.size) < 16:
678
+ interlace = 0
679
+
680
+ return interlace
681
+
682
+
683
+ def _write_local_header(fp, im, offset, flags):
684
+ transparent_color_exists = False
685
+ try:
686
+ if "transparency" in im.encoderinfo:
687
+ transparency = im.encoderinfo["transparency"]
688
+ else:
689
+ transparency = im.info["transparency"]
690
+ transparency = int(transparency)
691
+ except (KeyError, ValueError):
692
+ pass
693
+ else:
694
+ # optimize the block away if transparent color is not used
695
+ transparent_color_exists = True
696
+
697
+ used_palette_colors = _get_optimize(im, im.encoderinfo)
698
+ if used_palette_colors is not None:
699
+ # adjust the transparency index after optimize
700
+ try:
701
+ transparency = used_palette_colors.index(transparency)
702
+ except ValueError:
703
+ transparent_color_exists = False
704
+
705
+ if "duration" in im.encoderinfo:
706
+ duration = int(im.encoderinfo["duration"] / 10)
707
+ else:
708
+ duration = 0
709
+
710
+ disposal = int(im.encoderinfo.get("disposal", 0))
711
+
712
+ if transparent_color_exists or duration != 0 or disposal:
713
+ packed_flag = 1 if transparent_color_exists else 0
714
+ packed_flag |= disposal << 2
715
+ if not transparent_color_exists:
716
+ transparency = 0
717
+
718
+ fp.write(
719
+ b"!"
720
+ + o8(249) # extension intro
721
+ + o8(4) # length
722
+ + o8(packed_flag) # packed fields
723
+ + o16(duration) # duration
724
+ + o8(transparency) # transparency index
725
+ + o8(0)
726
+ )
727
+
728
+ include_color_table = im.encoderinfo.get("include_color_table")
729
+ if include_color_table:
730
+ palette_bytes = _get_palette_bytes(im)
731
+ color_table_size = _get_color_table_size(palette_bytes)
732
+ if color_table_size:
733
+ flags = flags | 128 # local color table flag
734
+ flags = flags | color_table_size
735
+
736
+ fp.write(
737
+ b","
738
+ + o16(offset[0]) # offset
739
+ + o16(offset[1])
740
+ + o16(im.size[0]) # size
741
+ + o16(im.size[1])
742
+ + o8(flags) # flags
743
+ )
744
+ if include_color_table and color_table_size:
745
+ fp.write(_get_header_palette(palette_bytes))
746
+ fp.write(o8(8)) # bits
747
+
748
+
749
+ def _save_netpbm(im, fp, filename):
750
+ # Unused by default.
751
+ # To use, uncomment the register_save call at the end of the file.
752
+ #
753
+ # If you need real GIF compression and/or RGB quantization, you
754
+ # can use the external NETPBM/PBMPLUS utilities. See comments
755
+ # below for information on how to enable this.
756
+ tempfile = im._dump()
757
+
758
+ try:
759
+ with open(filename, "wb") as f:
760
+ if im.mode != "RGB":
761
+ subprocess.check_call(
762
+ ["ppmtogif", tempfile], stdout=f, stderr=subprocess.DEVNULL
763
+ )
764
+ else:
765
+ # Pipe ppmquant output into ppmtogif
766
+ # "ppmquant 256 %s | ppmtogif > %s" % (tempfile, filename)
767
+ quant_cmd = ["ppmquant", "256", tempfile]
768
+ togif_cmd = ["ppmtogif"]
769
+ quant_proc = subprocess.Popen(
770
+ quant_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL
771
+ )
772
+ togif_proc = subprocess.Popen(
773
+ togif_cmd,
774
+ stdin=quant_proc.stdout,
775
+ stdout=f,
776
+ stderr=subprocess.DEVNULL,
777
+ )
778
+
779
+ # Allow ppmquant to receive SIGPIPE if ppmtogif exits
780
+ quant_proc.stdout.close()
781
+
782
+ retcode = quant_proc.wait()
783
+ if retcode:
784
+ raise subprocess.CalledProcessError(retcode, quant_cmd)
785
+
786
+ retcode = togif_proc.wait()
787
+ if retcode:
788
+ raise subprocess.CalledProcessError(retcode, togif_cmd)
789
+ finally:
790
+ try:
791
+ os.unlink(tempfile)
792
+ except OSError:
793
+ pass
794
+
795
+
796
+ # Force optimization so that we can test performance against
797
+ # cases where it took lots of memory and time previously.
798
+ _FORCE_OPTIMIZE = False
799
+
800
+
801
+ def _get_optimize(im, info):
802
+ """
803
+ Palette optimization is a potentially expensive operation.
804
+
805
+ This function determines if the palette should be optimized using
806
+ some heuristics, then returns the list of palette entries in use.
807
+
808
+ :param im: Image object
809
+ :param info: encoderinfo
810
+ :returns: list of indexes of palette entries in use, or None
811
+ """
812
+ if im.mode in ("P", "L") and info and info.get("optimize", 0):
813
+ # Potentially expensive operation.
814
+
815
+ # The palette saves 3 bytes per color not used, but palette
816
+ # lengths are restricted to 3*(2**N) bytes. Max saving would
817
+ # be 768 -> 6 bytes if we went all the way down to 2 colors.
818
+ # * If we're over 128 colors, we can't save any space.
819
+ # * If there aren't any holes, it's not worth collapsing.
820
+ # * If we have a 'large' image, the palette is in the noise.
821
+
822
+ # create the new palette if not every color is used
823
+ optimise = _FORCE_OPTIMIZE or im.mode == "L"
824
+ if optimise or im.width * im.height < 512 * 512:
825
+ # check which colors are used
826
+ used_palette_colors = []
827
+ for i, count in enumerate(im.histogram()):
828
+ if count:
829
+ used_palette_colors.append(i)
830
+
831
+ if optimise or max(used_palette_colors) >= len(used_palette_colors):
832
+ return used_palette_colors
833
+
834
+ num_palette_colors = len(im.palette.palette) // Image.getmodebands(
835
+ im.palette.mode
836
+ )
837
+ current_palette_size = 1 << (num_palette_colors - 1).bit_length()
838
+ if (
839
+ # check that the palette would become smaller when saved
840
+ len(used_palette_colors) <= current_palette_size // 2
841
+ # check that the palette is not already the smallest possible size
842
+ and current_palette_size > 2
843
+ ):
844
+ return used_palette_colors
845
+
846
+
847
+ def _get_color_table_size(palette_bytes):
848
+ # calculate the palette size for the header
849
+ if not palette_bytes:
850
+ return 0
851
+ elif len(palette_bytes) < 9:
852
+ return 1
853
+ else:
854
+ return math.ceil(math.log(len(palette_bytes) // 3, 2)) - 1
855
+
856
+
857
+ def _get_header_palette(palette_bytes):
858
+ """
859
+ Returns the palette, null padded to the next power of 2 (*3) bytes
860
+ suitable for direct inclusion in the GIF header
861
+
862
+ :param palette_bytes: Unpadded palette bytes, in RGBRGB form
863
+ :returns: Null padded palette
864
+ """
865
+ color_table_size = _get_color_table_size(palette_bytes)
866
+
867
+ # add the missing amount of bytes
868
+ # the palette has to be 2<<n in size
869
+ actual_target_size_diff = (2 << color_table_size) - len(palette_bytes) // 3
870
+ if actual_target_size_diff > 0:
871
+ palette_bytes += o8(0) * 3 * actual_target_size_diff
872
+ return palette_bytes
873
+
874
+
875
+ def _get_palette_bytes(im):
876
+ """
877
+ Gets the palette for inclusion in the gif header
878
+
879
+ :param im: Image object
880
+ :returns: Bytes, len<=768 suitable for inclusion in gif header
881
+ """
882
+ return im.palette.palette if im.palette else b""
883
+
884
+
885
+ def _get_background(im, info_background):
886
+ background = 0
887
+ if info_background:
888
+ if isinstance(info_background, tuple):
889
+ # WebPImagePlugin stores an RGBA value in info["background"]
890
+ # So it must be converted to the same format as GifImagePlugin's
891
+ # info["background"] - a global color table index
892
+ try:
893
+ background = im.palette.getcolor(info_background, im)
894
+ except ValueError as e:
895
+ if str(e) not in (
896
+ # If all 256 colors are in use,
897
+ # then there is no need for the background color
898
+ "cannot allocate more than 256 colors",
899
+ # Ignore non-opaque WebP background
900
+ "cannot add non-opaque RGBA color to RGB palette",
901
+ ):
902
+ raise
903
+ else:
904
+ background = info_background
905
+ return background
906
+
907
+
908
+ def _get_global_header(im, info):
909
+ """Return a list of strings representing a GIF header"""
910
+
911
+ # Header Block
912
+ # https://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp
913
+
914
+ version = b"87a"
915
+ if im.info.get("version") == b"89a" or (
916
+ info
917
+ and (
918
+ "transparency" in info
919
+ or "loop" in info
920
+ or info.get("duration")
921
+ or info.get("comment")
922
+ )
923
+ ):
924
+ version = b"89a"
925
+
926
+ background = _get_background(im, info.get("background"))
927
+
928
+ palette_bytes = _get_palette_bytes(im)
929
+ color_table_size = _get_color_table_size(palette_bytes)
930
+
931
+ header = [
932
+ b"GIF" # signature
933
+ + version # version
934
+ + o16(im.size[0]) # canvas width
935
+ + o16(im.size[1]), # canvas height
936
+ # Logical Screen Descriptor
937
+ # size of global color table + global color table flag
938
+ o8(color_table_size + 128), # packed fields
939
+ # background + reserved/aspect
940
+ o8(background) + o8(0),
941
+ # Global Color Table
942
+ _get_header_palette(palette_bytes),
943
+ ]
944
+ if "loop" in info:
945
+ header.append(
946
+ b"!"
947
+ + o8(255) # extension intro
948
+ + o8(11)
949
+ + b"NETSCAPE2.0"
950
+ + o8(3)
951
+ + o8(1)
952
+ + o16(info["loop"]) # number of loops
953
+ + o8(0)
954
+ )
955
+ if info.get("comment"):
956
+ comment_block = b"!" + o8(254) # extension intro
957
+
958
+ comment = info["comment"]
959
+ if isinstance(comment, str):
960
+ comment = comment.encode()
961
+ for i in range(0, len(comment), 255):
962
+ subblock = comment[i : i + 255]
963
+ comment_block += o8(len(subblock)) + subblock
964
+
965
+ comment_block += o8(0)
966
+ header.append(comment_block)
967
+ return header
968
+
969
+
970
+ def _write_frame_data(fp, im_frame, offset, params):
971
+ try:
972
+ im_frame.encoderinfo = params
973
+
974
+ # local image header
975
+ _write_local_header(fp, im_frame, offset, 0)
976
+
977
+ ImageFile._save(
978
+ im_frame, fp, [("gif", (0, 0) + im_frame.size, 0, RAWMODE[im_frame.mode])]
979
+ )
980
+
981
+ fp.write(b"\0") # end of image data
982
+ finally:
983
+ del im_frame.encoderinfo
984
+
985
+
986
+ # --------------------------------------------------------------------
987
+ # Legacy GIF utilities
988
+
989
+
990
+ def getheader(im, palette=None, info=None):
991
+ """
992
+ Legacy Method to get Gif data from image.
993
+
994
+ Warning:: May modify image data.
995
+
996
+ :param im: Image object
997
+ :param palette: bytes object containing the source palette, or ....
998
+ :param info: encoderinfo
999
+ :returns: tuple of(list of header items, optimized palette)
1000
+
1001
+ """
1002
+ used_palette_colors = _get_optimize(im, info)
1003
+
1004
+ if info is None:
1005
+ info = {}
1006
+
1007
+ if "background" not in info and "background" in im.info:
1008
+ info["background"] = im.info["background"]
1009
+
1010
+ im_mod = _normalize_palette(im, palette, info)
1011
+ im.palette = im_mod.palette
1012
+ im.im = im_mod.im
1013
+ header = _get_global_header(im, info)
1014
+
1015
+ return header, used_palette_colors
1016
+
1017
+
1018
+ def getdata(im, offset=(0, 0), **params):
1019
+ """
1020
+ Legacy Method
1021
+
1022
+ Return a list of strings representing this image.
1023
+ The first string is a local image header, the rest contains
1024
+ encoded image data.
1025
+
1026
+ To specify duration, add the time in milliseconds,
1027
+ e.g. ``getdata(im_frame, duration=1000)``
1028
+
1029
+ :param im: Image object
1030
+ :param offset: Tuple of (x, y) pixels. Defaults to (0, 0)
1031
+ :param \\**params: e.g. duration or other encoder info parameters
1032
+ :returns: List of bytes containing GIF encoded frame data
1033
+
1034
+ """
1035
+
1036
+ class Collector:
1037
+ data = []
1038
+
1039
+ def write(self, data):
1040
+ self.data.append(data)
1041
+
1042
+ im.load() # make sure raster data is available
1043
+
1044
+ fp = Collector()
1045
+
1046
+ _write_frame_data(fp, im, offset, params)
1047
+
1048
+ return fp.data
1049
+
1050
+
1051
+ # --------------------------------------------------------------------
1052
+ # Registry
1053
+
1054
+ Image.register_open(GifImageFile.format, GifImageFile, _accept)
1055
+ Image.register_save(GifImageFile.format, _save)
1056
+ Image.register_save_all(GifImageFile.format, _save_all)
1057
+ Image.register_extension(GifImageFile.format, ".gif")
1058
+ Image.register_mime(GifImageFile.format, "image/gif")
1059
+
1060
+ #
1061
+ # Uncomment the following line if you wish to use NETPBM/PBMPLUS
1062
+ # instead of the built-in "uncompressed" GIF encoder
1063
+
1064
+ # Image.register_save(GifImageFile.format, _save_netpbm)
Lib/site-packages/PIL/GimpGradientFile.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # stuff to read (and render) GIMP gradient files
6
+ #
7
+ # History:
8
+ # 97-08-23 fl Created
9
+ #
10
+ # Copyright (c) Secret Labs AB 1997.
11
+ # Copyright (c) Fredrik Lundh 1997.
12
+ #
13
+ # See the README file for information on usage and redistribution.
14
+ #
15
+
16
+ """
17
+ Stuff to translate curve segments to palette values (derived from
18
+ the corresponding code in GIMP, written by Federico Mena Quintero.
19
+ See the GIMP distribution for more information.)
20
+ """
21
+
22
+
23
+ from math import log, pi, sin, sqrt
24
+
25
+ from ._binary import o8
26
+
27
+ EPSILON = 1e-10
28
+ """""" # Enable auto-doc for data member
29
+
30
+
31
+ def linear(middle, pos):
32
+ if pos <= middle:
33
+ if middle < EPSILON:
34
+ return 0.0
35
+ else:
36
+ return 0.5 * pos / middle
37
+ else:
38
+ pos = pos - middle
39
+ middle = 1.0 - middle
40
+ if middle < EPSILON:
41
+ return 1.0
42
+ else:
43
+ return 0.5 + 0.5 * pos / middle
44
+
45
+
46
+ def curved(middle, pos):
47
+ return pos ** (log(0.5) / log(max(middle, EPSILON)))
48
+
49
+
50
+ def sine(middle, pos):
51
+ return (sin((-pi / 2.0) + pi * linear(middle, pos)) + 1.0) / 2.0
52
+
53
+
54
+ def sphere_increasing(middle, pos):
55
+ return sqrt(1.0 - (linear(middle, pos) - 1.0) ** 2)
56
+
57
+
58
+ def sphere_decreasing(middle, pos):
59
+ return 1.0 - sqrt(1.0 - linear(middle, pos) ** 2)
60
+
61
+
62
+ SEGMENTS = [linear, curved, sine, sphere_increasing, sphere_decreasing]
63
+ """""" # Enable auto-doc for data member
64
+
65
+
66
+ class GradientFile:
67
+ gradient = None
68
+
69
+ def getpalette(self, entries=256):
70
+ palette = []
71
+
72
+ ix = 0
73
+ x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]
74
+
75
+ for i in range(entries):
76
+ x = i / (entries - 1)
77
+
78
+ while x1 < x:
79
+ ix += 1
80
+ x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]
81
+
82
+ w = x1 - x0
83
+
84
+ if w < EPSILON:
85
+ scale = segment(0.5, 0.5)
86
+ else:
87
+ scale = segment((xm - x0) / w, (x - x0) / w)
88
+
89
+ # expand to RGBA
90
+ r = o8(int(255 * ((rgb1[0] - rgb0[0]) * scale + rgb0[0]) + 0.5))
91
+ g = o8(int(255 * ((rgb1[1] - rgb0[1]) * scale + rgb0[1]) + 0.5))
92
+ b = o8(int(255 * ((rgb1[2] - rgb0[2]) * scale + rgb0[2]) + 0.5))
93
+ a = o8(int(255 * ((rgb1[3] - rgb0[3]) * scale + rgb0[3]) + 0.5))
94
+
95
+ # add to palette
96
+ palette.append(r + g + b + a)
97
+
98
+ return b"".join(palette), "RGBA"
99
+
100
+
101
+ class GimpGradientFile(GradientFile):
102
+ """File handler for GIMP's gradient format."""
103
+
104
+ def __init__(self, fp):
105
+ if fp.readline()[:13] != b"GIMP Gradient":
106
+ msg = "not a GIMP gradient file"
107
+ raise SyntaxError(msg)
108
+
109
+ line = fp.readline()
110
+
111
+ # GIMP 1.2 gradient files don't contain a name, but GIMP 1.3 files do
112
+ if line.startswith(b"Name: "):
113
+ line = fp.readline().strip()
114
+
115
+ count = int(line)
116
+
117
+ gradient = []
118
+
119
+ for i in range(count):
120
+ s = fp.readline().split()
121
+ w = [float(x) for x in s[:11]]
122
+
123
+ x0, x1 = w[0], w[2]
124
+ xm = w[1]
125
+ rgb0 = w[3:7]
126
+ rgb1 = w[7:11]
127
+
128
+ segment = SEGMENTS[int(s[11])]
129
+ cspace = int(s[12])
130
+
131
+ if cspace != 0:
132
+ msg = "cannot handle HSV colour space"
133
+ raise OSError(msg)
134
+
135
+ gradient.append((x0, x1, xm, rgb0, rgb1, segment))
136
+
137
+ self.gradient = gradient
Lib/site-packages/PIL/GimpPaletteFile.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # stuff to read GIMP palette files
6
+ #
7
+ # History:
8
+ # 1997-08-23 fl Created
9
+ # 2004-09-07 fl Support GIMP 2.0 palette files.
10
+ #
11
+ # Copyright (c) Secret Labs AB 1997-2004. All rights reserved.
12
+ # Copyright (c) Fredrik Lundh 1997-2004.
13
+ #
14
+ # See the README file for information on usage and redistribution.
15
+ #
16
+
17
+ import re
18
+
19
+ from ._binary import o8
20
+
21
+
22
+ class GimpPaletteFile:
23
+ """File handler for GIMP's palette format."""
24
+
25
+ rawmode = "RGB"
26
+
27
+ def __init__(self, fp):
28
+ self.palette = [o8(i) * 3 for i in range(256)]
29
+
30
+ if fp.readline()[:12] != b"GIMP Palette":
31
+ msg = "not a GIMP palette file"
32
+ raise SyntaxError(msg)
33
+
34
+ for i in range(256):
35
+ s = fp.readline()
36
+ if not s:
37
+ break
38
+
39
+ # skip fields and comment lines
40
+ if re.match(rb"\w+:|#", s):
41
+ continue
42
+ if len(s) > 100:
43
+ msg = "bad palette file"
44
+ raise SyntaxError(msg)
45
+
46
+ v = tuple(map(int, s.split()[:3]))
47
+ if len(v) != 3:
48
+ msg = "bad palette entry"
49
+ raise ValueError(msg)
50
+
51
+ self.palette[i] = o8(v[0]) + o8(v[1]) + o8(v[2])
52
+
53
+ self.palette = b"".join(self.palette)
54
+
55
+ def getpalette(self):
56
+ return self.palette, self.rawmode
Lib/site-packages/PIL/GribStubImagePlugin.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # GRIB stub adapter
6
+ #
7
+ # Copyright (c) 1996-2003 by Fredrik Lundh
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+
12
+ from . import Image, ImageFile
13
+
14
+ _handler = None
15
+
16
+
17
+ def register_handler(handler):
18
+ """
19
+ Install application-specific GRIB image handler.
20
+
21
+ :param handler: Handler object.
22
+ """
23
+ global _handler
24
+ _handler = handler
25
+
26
+
27
+ # --------------------------------------------------------------------
28
+ # Image adapter
29
+
30
+
31
+ def _accept(prefix):
32
+ return prefix[:4] == b"GRIB" and prefix[7] == 1
33
+
34
+
35
+ class GribStubImageFile(ImageFile.StubImageFile):
36
+ format = "GRIB"
37
+ format_description = "GRIB"
38
+
39
+ def _open(self):
40
+ offset = self.fp.tell()
41
+
42
+ if not _accept(self.fp.read(8)):
43
+ msg = "Not a GRIB file"
44
+ raise SyntaxError(msg)
45
+
46
+ self.fp.seek(offset)
47
+
48
+ # make something up
49
+ self.mode = "F"
50
+ self._size = 1, 1
51
+
52
+ loader = self._load()
53
+ if loader:
54
+ loader.open(self)
55
+
56
+ def _load(self):
57
+ return _handler
58
+
59
+
60
+ def _save(im, fp, filename):
61
+ if _handler is None or not hasattr(_handler, "save"):
62
+ msg = "GRIB save handler not installed"
63
+ raise OSError(msg)
64
+ _handler.save(im, fp, filename)
65
+
66
+
67
+ # --------------------------------------------------------------------
68
+ # Registry
69
+
70
+ Image.register_open(GribStubImageFile.format, GribStubImageFile, _accept)
71
+ Image.register_save(GribStubImageFile.format, _save)
72
+
73
+ Image.register_extension(GribStubImageFile.format, ".grib")
Lib/site-packages/PIL/Hdf5StubImagePlugin.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # HDF5 stub adapter
6
+ #
7
+ # Copyright (c) 2000-2003 by Fredrik Lundh
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+
12
+ from . import Image, ImageFile
13
+
14
+ _handler = None
15
+
16
+
17
+ def register_handler(handler):
18
+ """
19
+ Install application-specific HDF5 image handler.
20
+
21
+ :param handler: Handler object.
22
+ """
23
+ global _handler
24
+ _handler = handler
25
+
26
+
27
+ # --------------------------------------------------------------------
28
+ # Image adapter
29
+
30
+
31
+ def _accept(prefix):
32
+ return prefix[:8] == b"\x89HDF\r\n\x1a\n"
33
+
34
+
35
+ class HDF5StubImageFile(ImageFile.StubImageFile):
36
+ format = "HDF5"
37
+ format_description = "HDF5"
38
+
39
+ def _open(self):
40
+ offset = self.fp.tell()
41
+
42
+ if not _accept(self.fp.read(8)):
43
+ msg = "Not an HDF file"
44
+ raise SyntaxError(msg)
45
+
46
+ self.fp.seek(offset)
47
+
48
+ # make something up
49
+ self.mode = "F"
50
+ self._size = 1, 1
51
+
52
+ loader = self._load()
53
+ if loader:
54
+ loader.open(self)
55
+
56
+ def _load(self):
57
+ return _handler
58
+
59
+
60
+ def _save(im, fp, filename):
61
+ if _handler is None or not hasattr(_handler, "save"):
62
+ msg = "HDF5 save handler not installed"
63
+ raise OSError(msg)
64
+ _handler.save(im, fp, filename)
65
+
66
+
67
+ # --------------------------------------------------------------------
68
+ # Registry
69
+
70
+ Image.register_open(HDF5StubImageFile.format, HDF5StubImageFile, _accept)
71
+ Image.register_save(HDF5StubImageFile.format, _save)
72
+
73
+ Image.register_extensions(HDF5StubImageFile.format, [".h5", ".hdf"])
Lib/site-packages/PIL/IcnsImagePlugin.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # macOS icns file decoder, based on icns.py by Bob Ippolito.
6
+ #
7
+ # history:
8
+ # 2004-10-09 fl Turned into a PIL plugin; removed 2.3 dependencies.
9
+ # 2020-04-04 Allow saving on all operating systems.
10
+ #
11
+ # Copyright (c) 2004 by Bob Ippolito.
12
+ # Copyright (c) 2004 by Secret Labs.
13
+ # Copyright (c) 2004 by Fredrik Lundh.
14
+ # Copyright (c) 2014 by Alastair Houghton.
15
+ # Copyright (c) 2020 by Pan Jing.
16
+ #
17
+ # See the README file for information on usage and redistribution.
18
+ #
19
+
20
+ import io
21
+ import os
22
+ import struct
23
+ import sys
24
+
25
+ from . import Image, ImageFile, PngImagePlugin, features
26
+
27
+ enable_jpeg2k = features.check_codec("jpg_2000")
28
+ if enable_jpeg2k:
29
+ from . import Jpeg2KImagePlugin
30
+
31
+ MAGIC = b"icns"
32
+ HEADERSIZE = 8
33
+
34
+
35
+ def nextheader(fobj):
36
+ return struct.unpack(">4sI", fobj.read(HEADERSIZE))
37
+
38
+
39
+ def read_32t(fobj, start_length, size):
40
+ # The 128x128 icon seems to have an extra header for some reason.
41
+ (start, length) = start_length
42
+ fobj.seek(start)
43
+ sig = fobj.read(4)
44
+ if sig != b"\x00\x00\x00\x00":
45
+ msg = "Unknown signature, expecting 0x00000000"
46
+ raise SyntaxError(msg)
47
+ return read_32(fobj, (start + 4, length - 4), size)
48
+
49
+
50
+ def read_32(fobj, start_length, size):
51
+ """
52
+ Read a 32bit RGB icon resource. Seems to be either uncompressed or
53
+ an RLE packbits-like scheme.
54
+ """
55
+ (start, length) = start_length
56
+ fobj.seek(start)
57
+ pixel_size = (size[0] * size[2], size[1] * size[2])
58
+ sizesq = pixel_size[0] * pixel_size[1]
59
+ if length == sizesq * 3:
60
+ # uncompressed ("RGBRGBGB")
61
+ indata = fobj.read(length)
62
+ im = Image.frombuffer("RGB", pixel_size, indata, "raw", "RGB", 0, 1)
63
+ else:
64
+ # decode image
65
+ im = Image.new("RGB", pixel_size, None)
66
+ for band_ix in range(3):
67
+ data = []
68
+ bytesleft = sizesq
69
+ while bytesleft > 0:
70
+ byte = fobj.read(1)
71
+ if not byte:
72
+ break
73
+ byte = byte[0]
74
+ if byte & 0x80:
75
+ blocksize = byte - 125
76
+ byte = fobj.read(1)
77
+ for i in range(blocksize):
78
+ data.append(byte)
79
+ else:
80
+ blocksize = byte + 1
81
+ data.append(fobj.read(blocksize))
82
+ bytesleft -= blocksize
83
+ if bytesleft <= 0:
84
+ break
85
+ if bytesleft != 0:
86
+ msg = f"Error reading channel [{repr(bytesleft)} left]"
87
+ raise SyntaxError(msg)
88
+ band = Image.frombuffer("L", pixel_size, b"".join(data), "raw", "L", 0, 1)
89
+ im.im.putband(band.im, band_ix)
90
+ return {"RGB": im}
91
+
92
+
93
+ def read_mk(fobj, start_length, size):
94
+ # Alpha masks seem to be uncompressed
95
+ start = start_length[0]
96
+ fobj.seek(start)
97
+ pixel_size = (size[0] * size[2], size[1] * size[2])
98
+ sizesq = pixel_size[0] * pixel_size[1]
99
+ band = Image.frombuffer("L", pixel_size, fobj.read(sizesq), "raw", "L", 0, 1)
100
+ return {"A": band}
101
+
102
+
103
+ def read_png_or_jpeg2000(fobj, start_length, size):
104
+ (start, length) = start_length
105
+ fobj.seek(start)
106
+ sig = fobj.read(12)
107
+ if sig[:8] == b"\x89PNG\x0d\x0a\x1a\x0a":
108
+ fobj.seek(start)
109
+ im = PngImagePlugin.PngImageFile(fobj)
110
+ Image._decompression_bomb_check(im.size)
111
+ return {"RGBA": im}
112
+ elif (
113
+ sig[:4] == b"\xff\x4f\xff\x51"
114
+ or sig[:4] == b"\x0d\x0a\x87\x0a"
115
+ or sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a"
116
+ ):
117
+ if not enable_jpeg2k:
118
+ msg = (
119
+ "Unsupported icon subimage format (rebuild PIL "
120
+ "with JPEG 2000 support to fix this)"
121
+ )
122
+ raise ValueError(msg)
123
+ # j2k, jpc or j2c
124
+ fobj.seek(start)
125
+ jp2kstream = fobj.read(length)
126
+ f = io.BytesIO(jp2kstream)
127
+ im = Jpeg2KImagePlugin.Jpeg2KImageFile(f)
128
+ Image._decompression_bomb_check(im.size)
129
+ if im.mode != "RGBA":
130
+ im = im.convert("RGBA")
131
+ return {"RGBA": im}
132
+ else:
133
+ msg = "Unsupported icon subimage format"
134
+ raise ValueError(msg)
135
+
136
+
137
+ class IcnsFile:
138
+ SIZES = {
139
+ (512, 512, 2): [(b"ic10", read_png_or_jpeg2000)],
140
+ (512, 512, 1): [(b"ic09", read_png_or_jpeg2000)],
141
+ (256, 256, 2): [(b"ic14", read_png_or_jpeg2000)],
142
+ (256, 256, 1): [(b"ic08", read_png_or_jpeg2000)],
143
+ (128, 128, 2): [(b"ic13", read_png_or_jpeg2000)],
144
+ (128, 128, 1): [
145
+ (b"ic07", read_png_or_jpeg2000),
146
+ (b"it32", read_32t),
147
+ (b"t8mk", read_mk),
148
+ ],
149
+ (64, 64, 1): [(b"icp6", read_png_or_jpeg2000)],
150
+ (32, 32, 2): [(b"ic12", read_png_or_jpeg2000)],
151
+ (48, 48, 1): [(b"ih32", read_32), (b"h8mk", read_mk)],
152
+ (32, 32, 1): [
153
+ (b"icp5", read_png_or_jpeg2000),
154
+ (b"il32", read_32),
155
+ (b"l8mk", read_mk),
156
+ ],
157
+ (16, 16, 2): [(b"ic11", read_png_or_jpeg2000)],
158
+ (16, 16, 1): [
159
+ (b"icp4", read_png_or_jpeg2000),
160
+ (b"is32", read_32),
161
+ (b"s8mk", read_mk),
162
+ ],
163
+ }
164
+
165
+ def __init__(self, fobj):
166
+ """
167
+ fobj is a file-like object as an icns resource
168
+ """
169
+ # signature : (start, length)
170
+ self.dct = dct = {}
171
+ self.fobj = fobj
172
+ sig, filesize = nextheader(fobj)
173
+ if not _accept(sig):
174
+ msg = "not an icns file"
175
+ raise SyntaxError(msg)
176
+ i = HEADERSIZE
177
+ while i < filesize:
178
+ sig, blocksize = nextheader(fobj)
179
+ if blocksize <= 0:
180
+ msg = "invalid block header"
181
+ raise SyntaxError(msg)
182
+ i += HEADERSIZE
183
+ blocksize -= HEADERSIZE
184
+ dct[sig] = (i, blocksize)
185
+ fobj.seek(blocksize, io.SEEK_CUR)
186
+ i += blocksize
187
+
188
+ def itersizes(self):
189
+ sizes = []
190
+ for size, fmts in self.SIZES.items():
191
+ for fmt, reader in fmts:
192
+ if fmt in self.dct:
193
+ sizes.append(size)
194
+ break
195
+ return sizes
196
+
197
+ def bestsize(self):
198
+ sizes = self.itersizes()
199
+ if not sizes:
200
+ msg = "No 32bit icon resources found"
201
+ raise SyntaxError(msg)
202
+ return max(sizes)
203
+
204
+ def dataforsize(self, size):
205
+ """
206
+ Get an icon resource as {channel: array}. Note that
207
+ the arrays are bottom-up like windows bitmaps and will likely
208
+ need to be flipped or transposed in some way.
209
+ """
210
+ dct = {}
211
+ for code, reader in self.SIZES[size]:
212
+ desc = self.dct.get(code)
213
+ if desc is not None:
214
+ dct.update(reader(self.fobj, desc, size))
215
+ return dct
216
+
217
+ def getimage(self, size=None):
218
+ if size is None:
219
+ size = self.bestsize()
220
+ if len(size) == 2:
221
+ size = (size[0], size[1], 1)
222
+ channels = self.dataforsize(size)
223
+
224
+ im = channels.get("RGBA", None)
225
+ if im:
226
+ return im
227
+
228
+ im = channels.get("RGB").copy()
229
+ try:
230
+ im.putalpha(channels["A"])
231
+ except KeyError:
232
+ pass
233
+ return im
234
+
235
+
236
+ ##
237
+ # Image plugin for Mac OS icons.
238
+
239
+
240
+ class IcnsImageFile(ImageFile.ImageFile):
241
+ """
242
+ PIL image support for Mac OS .icns files.
243
+ Chooses the best resolution, but will possibly load
244
+ a different size image if you mutate the size attribute
245
+ before calling 'load'.
246
+
247
+ The info dictionary has a key 'sizes' that is a list
248
+ of sizes that the icns file has.
249
+ """
250
+
251
+ format = "ICNS"
252
+ format_description = "Mac OS icns resource"
253
+
254
+ def _open(self):
255
+ self.icns = IcnsFile(self.fp)
256
+ self.mode = "RGBA"
257
+ self.info["sizes"] = self.icns.itersizes()
258
+ self.best_size = self.icns.bestsize()
259
+ self.size = (
260
+ self.best_size[0] * self.best_size[2],
261
+ self.best_size[1] * self.best_size[2],
262
+ )
263
+
264
+ @property
265
+ def size(self):
266
+ return self._size
267
+
268
+ @size.setter
269
+ def size(self, value):
270
+ info_size = value
271
+ if info_size not in self.info["sizes"] and len(info_size) == 2:
272
+ info_size = (info_size[0], info_size[1], 1)
273
+ if (
274
+ info_size not in self.info["sizes"]
275
+ and len(info_size) == 3
276
+ and info_size[2] == 1
277
+ ):
278
+ simple_sizes = [
279
+ (size[0] * size[2], size[1] * size[2]) for size in self.info["sizes"]
280
+ ]
281
+ if value in simple_sizes:
282
+ info_size = self.info["sizes"][simple_sizes.index(value)]
283
+ if info_size not in self.info["sizes"]:
284
+ msg = "This is not one of the allowed sizes of this image"
285
+ raise ValueError(msg)
286
+ self._size = value
287
+
288
+ def load(self):
289
+ if len(self.size) == 3:
290
+ self.best_size = self.size
291
+ self.size = (
292
+ self.best_size[0] * self.best_size[2],
293
+ self.best_size[1] * self.best_size[2],
294
+ )
295
+
296
+ px = Image.Image.load(self)
297
+ if self.im is not None and self.im.size == self.size:
298
+ # Already loaded
299
+ return px
300
+ self.load_prepare()
301
+ # This is likely NOT the best way to do it, but whatever.
302
+ im = self.icns.getimage(self.best_size)
303
+
304
+ # If this is a PNG or JPEG 2000, it won't be loaded yet
305
+ px = im.load()
306
+
307
+ self.im = im.im
308
+ self.mode = im.mode
309
+ self.size = im.size
310
+
311
+ return px
312
+
313
+
314
+ def _save(im, fp, filename):
315
+ """
316
+ Saves the image as a series of PNG files,
317
+ that are then combined into a .icns file.
318
+ """
319
+ if hasattr(fp, "flush"):
320
+ fp.flush()
321
+
322
+ sizes = {
323
+ b"ic07": 128,
324
+ b"ic08": 256,
325
+ b"ic09": 512,
326
+ b"ic10": 1024,
327
+ b"ic11": 32,
328
+ b"ic12": 64,
329
+ b"ic13": 256,
330
+ b"ic14": 512,
331
+ }
332
+ provided_images = {im.width: im for im in im.encoderinfo.get("append_images", [])}
333
+ size_streams = {}
334
+ for size in set(sizes.values()):
335
+ image = (
336
+ provided_images[size]
337
+ if size in provided_images
338
+ else im.resize((size, size))
339
+ )
340
+
341
+ temp = io.BytesIO()
342
+ image.save(temp, "png")
343
+ size_streams[size] = temp.getvalue()
344
+
345
+ entries = []
346
+ for type, size in sizes.items():
347
+ stream = size_streams[size]
348
+ entries.append(
349
+ {"type": type, "size": HEADERSIZE + len(stream), "stream": stream}
350
+ )
351
+
352
+ # Header
353
+ fp.write(MAGIC)
354
+ file_length = HEADERSIZE # Header
355
+ file_length += HEADERSIZE + 8 * len(entries) # TOC
356
+ file_length += sum(entry["size"] for entry in entries)
357
+ fp.write(struct.pack(">i", file_length))
358
+
359
+ # TOC
360
+ fp.write(b"TOC ")
361
+ fp.write(struct.pack(">i", HEADERSIZE + len(entries) * HEADERSIZE))
362
+ for entry in entries:
363
+ fp.write(entry["type"])
364
+ fp.write(struct.pack(">i", entry["size"]))
365
+
366
+ # Data
367
+ for entry in entries:
368
+ fp.write(entry["type"])
369
+ fp.write(struct.pack(">i", entry["size"]))
370
+ fp.write(entry["stream"])
371
+
372
+ if hasattr(fp, "flush"):
373
+ fp.flush()
374
+
375
+
376
+ def _accept(prefix):
377
+ return prefix[:4] == MAGIC
378
+
379
+
380
+ Image.register_open(IcnsImageFile.format, IcnsImageFile, _accept)
381
+ Image.register_extension(IcnsImageFile.format, ".icns")
382
+
383
+ Image.register_save(IcnsImageFile.format, _save)
384
+ Image.register_mime(IcnsImageFile.format, "image/icns")
385
+
386
+ if __name__ == "__main__":
387
+ if len(sys.argv) < 2:
388
+ print("Syntax: python3 IcnsImagePlugin.py [file]")
389
+ sys.exit()
390
+
391
+ with open(sys.argv[1], "rb") as fp:
392
+ imf = IcnsImageFile(fp)
393
+ for size in imf.info["sizes"]:
394
+ imf.size = size
395
+ imf.save("out-%s-%s-%s.png" % size)
396
+ with Image.open(sys.argv[1]) as im:
397
+ im.save("out.png")
398
+ if sys.platform == "windows":
399
+ os.startfile("out.png")
Lib/site-packages/PIL/IcoImagePlugin.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # Windows Icon support for PIL
6
+ #
7
+ # History:
8
+ # 96-05-27 fl Created
9
+ #
10
+ # Copyright (c) Secret Labs AB 1997.
11
+ # Copyright (c) Fredrik Lundh 1996.
12
+ #
13
+ # See the README file for information on usage and redistribution.
14
+ #
15
+
16
+ # This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
17
18
+ # https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
19
+ #
20
+ # Icon format references:
21
+ # * https://en.wikipedia.org/wiki/ICO_(file_format)
22
+ # * https://msdn.microsoft.com/en-us/library/ms997538.aspx
23
+
24
+
25
+ import warnings
26
+ from io import BytesIO
27
+ from math import ceil, log
28
+
29
+ from . import BmpImagePlugin, Image, ImageFile, PngImagePlugin
30
+ from ._binary import i16le as i16
31
+ from ._binary import i32le as i32
32
+ from ._binary import o8
33
+ from ._binary import o16le as o16
34
+ from ._binary import o32le as o32
35
+
36
+ #
37
+ # --------------------------------------------------------------------
38
+
39
+ _MAGIC = b"\0\0\1\0"
40
+
41
+
42
+ def _save(im, fp, filename):
43
+ fp.write(_MAGIC) # (2+2)
44
+ bmp = im.encoderinfo.get("bitmap_format") == "bmp"
45
+ sizes = im.encoderinfo.get(
46
+ "sizes",
47
+ [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],
48
+ )
49
+ frames = []
50
+ provided_ims = [im] + im.encoderinfo.get("append_images", [])
51
+ width, height = im.size
52
+ for size in sorted(set(sizes)):
53
+ if size[0] > width or size[1] > height or size[0] > 256 or size[1] > 256:
54
+ continue
55
+
56
+ for provided_im in provided_ims:
57
+ if provided_im.size != size:
58
+ continue
59
+ frames.append(provided_im)
60
+ if bmp:
61
+ bits = BmpImagePlugin.SAVE[provided_im.mode][1]
62
+ bits_used = [bits]
63
+ for other_im in provided_ims:
64
+ if other_im.size != size:
65
+ continue
66
+ bits = BmpImagePlugin.SAVE[other_im.mode][1]
67
+ if bits not in bits_used:
68
+ # Another image has been supplied for this size
69
+ # with a different bit depth
70
+ frames.append(other_im)
71
+ bits_used.append(bits)
72
+ break
73
+ else:
74
+ # TODO: invent a more convenient method for proportional scalings
75
+ frame = provided_im.copy()
76
+ frame.thumbnail(size, Image.Resampling.LANCZOS, reducing_gap=None)
77
+ frames.append(frame)
78
+ fp.write(o16(len(frames))) # idCount(2)
79
+ offset = fp.tell() + len(frames) * 16
80
+ for frame in frames:
81
+ width, height = frame.size
82
+ # 0 means 256
83
+ fp.write(o8(width if width < 256 else 0)) # bWidth(1)
84
+ fp.write(o8(height if height < 256 else 0)) # bHeight(1)
85
+
86
+ bits, colors = BmpImagePlugin.SAVE[frame.mode][1:] if bmp else (32, 0)
87
+ fp.write(o8(colors)) # bColorCount(1)
88
+ fp.write(b"\0") # bReserved(1)
89
+ fp.write(b"\0\0") # wPlanes(2)
90
+ fp.write(o16(bits)) # wBitCount(2)
91
+
92
+ image_io = BytesIO()
93
+ if bmp:
94
+ frame.save(image_io, "dib")
95
+
96
+ if bits != 32:
97
+ and_mask = Image.new("1", size)
98
+ ImageFile._save(
99
+ and_mask, image_io, [("raw", (0, 0) + size, 0, ("1", 0, -1))]
100
+ )
101
+ else:
102
+ frame.save(image_io, "png")
103
+ image_io.seek(0)
104
+ image_bytes = image_io.read()
105
+ if bmp:
106
+ image_bytes = image_bytes[:8] + o32(height * 2) + image_bytes[12:]
107
+ bytes_len = len(image_bytes)
108
+ fp.write(o32(bytes_len)) # dwBytesInRes(4)
109
+ fp.write(o32(offset)) # dwImageOffset(4)
110
+ current = fp.tell()
111
+ fp.seek(offset)
112
+ fp.write(image_bytes)
113
+ offset = offset + bytes_len
114
+ fp.seek(current)
115
+
116
+
117
+ def _accept(prefix):
118
+ return prefix[:4] == _MAGIC
119
+
120
+
121
+ class IcoFile:
122
+ def __init__(self, buf):
123
+ """
124
+ Parse image from file-like object containing ico file data
125
+ """
126
+
127
+ # check magic
128
+ s = buf.read(6)
129
+ if not _accept(s):
130
+ msg = "not an ICO file"
131
+ raise SyntaxError(msg)
132
+
133
+ self.buf = buf
134
+ self.entry = []
135
+
136
+ # Number of items in file
137
+ self.nb_items = i16(s, 4)
138
+
139
+ # Get headers for each item
140
+ for i in range(self.nb_items):
141
+ s = buf.read(16)
142
+
143
+ icon_header = {
144
+ "width": s[0],
145
+ "height": s[1],
146
+ "nb_color": s[2], # No. of colors in image (0 if >=8bpp)
147
+ "reserved": s[3],
148
+ "planes": i16(s, 4),
149
+ "bpp": i16(s, 6),
150
+ "size": i32(s, 8),
151
+ "offset": i32(s, 12),
152
+ }
153
+
154
+ # See Wikipedia
155
+ for j in ("width", "height"):
156
+ if not icon_header[j]:
157
+ icon_header[j] = 256
158
+
159
+ # See Wikipedia notes about color depth.
160
+ # We need this just to differ images with equal sizes
161
+ icon_header["color_depth"] = (
162
+ icon_header["bpp"]
163
+ or (
164
+ icon_header["nb_color"] != 0
165
+ and ceil(log(icon_header["nb_color"], 2))
166
+ )
167
+ or 256
168
+ )
169
+
170
+ icon_header["dim"] = (icon_header["width"], icon_header["height"])
171
+ icon_header["square"] = icon_header["width"] * icon_header["height"]
172
+
173
+ self.entry.append(icon_header)
174
+
175
+ self.entry = sorted(self.entry, key=lambda x: x["color_depth"])
176
+ # ICO images are usually squares
177
+ # self.entry = sorted(self.entry, key=lambda x: x['width'])
178
+ self.entry = sorted(self.entry, key=lambda x: x["square"])
179
+ self.entry.reverse()
180
+
181
+ def sizes(self):
182
+ """
183
+ Get a list of all available icon sizes and color depths.
184
+ """
185
+ return {(h["width"], h["height"]) for h in self.entry}
186
+
187
+ def getentryindex(self, size, bpp=False):
188
+ for i, h in enumerate(self.entry):
189
+ if size == h["dim"] and (bpp is False or bpp == h["color_depth"]):
190
+ return i
191
+ return 0
192
+
193
+ def getimage(self, size, bpp=False):
194
+ """
195
+ Get an image from the icon
196
+ """
197
+ return self.frame(self.getentryindex(size, bpp))
198
+
199
+ def frame(self, idx):
200
+ """
201
+ Get an image from frame idx
202
+ """
203
+
204
+ header = self.entry[idx]
205
+
206
+ self.buf.seek(header["offset"])
207
+ data = self.buf.read(8)
208
+ self.buf.seek(header["offset"])
209
+
210
+ if data[:8] == PngImagePlugin._MAGIC:
211
+ # png frame
212
+ im = PngImagePlugin.PngImageFile(self.buf)
213
+ Image._decompression_bomb_check(im.size)
214
+ else:
215
+ # XOR + AND mask bmp frame
216
+ im = BmpImagePlugin.DibImageFile(self.buf)
217
+ Image._decompression_bomb_check(im.size)
218
+
219
+ # change tile dimension to only encompass XOR image
220
+ im._size = (im.size[0], int(im.size[1] / 2))
221
+ d, e, o, a = im.tile[0]
222
+ im.tile[0] = d, (0, 0) + im.size, o, a
223
+
224
+ # figure out where AND mask image starts
225
+ bpp = header["bpp"]
226
+ if 32 == bpp:
227
+ # 32-bit color depth icon image allows semitransparent areas
228
+ # PIL's DIB format ignores transparency bits, recover them.
229
+ # The DIB is packed in BGRX byte order where X is the alpha
230
+ # channel.
231
+
232
+ # Back up to start of bmp data
233
+ self.buf.seek(o)
234
+ # extract every 4th byte (eg. 3,7,11,15,...)
235
+ alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4]
236
+
237
+ # convert to an 8bpp grayscale image
238
+ mask = Image.frombuffer(
239
+ "L", # 8bpp
240
+ im.size, # (w, h)
241
+ alpha_bytes, # source chars
242
+ "raw", # raw decoder
243
+ ("L", 0, -1), # 8bpp inverted, unpadded, reversed
244
+ )
245
+ else:
246
+ # get AND image from end of bitmap
247
+ w = im.size[0]
248
+ if (w % 32) > 0:
249
+ # bitmap row data is aligned to word boundaries
250
+ w += 32 - (im.size[0] % 32)
251
+
252
+ # the total mask data is
253
+ # padded row size * height / bits per char
254
+
255
+ total_bytes = int((w * im.size[1]) / 8)
256
+ and_mask_offset = header["offset"] + header["size"] - total_bytes
257
+
258
+ self.buf.seek(and_mask_offset)
259
+ mask_data = self.buf.read(total_bytes)
260
+
261
+ # convert raw data to image
262
+ mask = Image.frombuffer(
263
+ "1", # 1 bpp
264
+ im.size, # (w, h)
265
+ mask_data, # source chars
266
+ "raw", # raw decoder
267
+ ("1;I", int(w / 8), -1), # 1bpp inverted, padded, reversed
268
+ )
269
+
270
+ # now we have two images, im is XOR image and mask is AND image
271
+
272
+ # apply mask image as alpha channel
273
+ im = im.convert("RGBA")
274
+ im.putalpha(mask)
275
+
276
+ return im
277
+
278
+
279
+ ##
280
+ # Image plugin for Windows Icon files.
281
+
282
+
283
+ class IcoImageFile(ImageFile.ImageFile):
284
+ """
285
+ PIL read-only image support for Microsoft Windows .ico files.
286
+
287
+ By default the largest resolution image in the file will be loaded. This
288
+ can be changed by altering the 'size' attribute before calling 'load'.
289
+
290
+ The info dictionary has a key 'sizes' that is a list of the sizes available
291
+ in the icon file.
292
+
293
+ Handles classic, XP and Vista icon formats.
294
+
295
+ When saving, PNG compression is used. Support for this was only added in
296
+ Windows Vista. If you are unable to view the icon in Windows, convert the
297
+ image to "RGBA" mode before saving.
298
+
299
+ This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
300
301
+ https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
302
+ """
303
+
304
+ format = "ICO"
305
+ format_description = "Windows Icon"
306
+
307
+ def _open(self):
308
+ self.ico = IcoFile(self.fp)
309
+ self.info["sizes"] = self.ico.sizes()
310
+ self.size = self.ico.entry[0]["dim"]
311
+ self.load()
312
+
313
+ @property
314
+ def size(self):
315
+ return self._size
316
+
317
+ @size.setter
318
+ def size(self, value):
319
+ if value not in self.info["sizes"]:
320
+ msg = "This is not one of the allowed sizes of this image"
321
+ raise ValueError(msg)
322
+ self._size = value
323
+
324
+ def load(self):
325
+ if self.im is not None and self.im.size == self.size:
326
+ # Already loaded
327
+ return Image.Image.load(self)
328
+ im = self.ico.getimage(self.size)
329
+ # if tile is PNG, it won't really be loaded yet
330
+ im.load()
331
+ self.im = im.im
332
+ self.pyaccess = None
333
+ self.mode = im.mode
334
+ if im.size != self.size:
335
+ warnings.warn("Image was not the expected size")
336
+
337
+ index = self.ico.getentryindex(self.size)
338
+ sizes = list(self.info["sizes"])
339
+ sizes[index] = im.size
340
+ self.info["sizes"] = set(sizes)
341
+
342
+ self.size = im.size
343
+
344
+ def load_seek(self):
345
+ # Flag the ImageFile.Parser so that it
346
+ # just does all the decode at the end.
347
+ pass
348
+
349
+
350
+ #
351
+ # --------------------------------------------------------------------
352
+
353
+
354
+ Image.register_open(IcoImageFile.format, IcoImageFile, _accept)
355
+ Image.register_save(IcoImageFile.format, _save)
356
+ Image.register_extension(IcoImageFile.format, ".ico")
357
+
358
+ Image.register_mime(IcoImageFile.format, "image/x-icon")
Lib/site-packages/PIL/ImImagePlugin.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # IFUNC IM file handling for PIL
6
+ #
7
+ # history:
8
+ # 1995-09-01 fl Created.
9
+ # 1997-01-03 fl Save palette images
10
+ # 1997-01-08 fl Added sequence support
11
+ # 1997-01-23 fl Added P and RGB save support
12
+ # 1997-05-31 fl Read floating point images
13
+ # 1997-06-22 fl Save floating point images
14
+ # 1997-08-27 fl Read and save 1-bit images
15
+ # 1998-06-25 fl Added support for RGB+LUT images
16
+ # 1998-07-02 fl Added support for YCC images
17
+ # 1998-07-15 fl Renamed offset attribute to avoid name clash
18
+ # 1998-12-29 fl Added I;16 support
19
+ # 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.7)
20
+ # 2003-09-26 fl Added LA/PA support
21
+ #
22
+ # Copyright (c) 1997-2003 by Secret Labs AB.
23
+ # Copyright (c) 1995-2001 by Fredrik Lundh.
24
+ #
25
+ # See the README file for information on usage and redistribution.
26
+ #
27
+
28
+
29
+ import os
30
+ import re
31
+
32
+ from . import Image, ImageFile, ImagePalette
33
+
34
+ # --------------------------------------------------------------------
35
+ # Standard tags
36
+
37
+ COMMENT = "Comment"
38
+ DATE = "Date"
39
+ EQUIPMENT = "Digitalization equipment"
40
+ FRAMES = "File size (no of images)"
41
+ LUT = "Lut"
42
+ NAME = "Name"
43
+ SCALE = "Scale (x,y)"
44
+ SIZE = "Image size (x*y)"
45
+ MODE = "Image type"
46
+
47
+ TAGS = {
48
+ COMMENT: 0,
49
+ DATE: 0,
50
+ EQUIPMENT: 0,
51
+ FRAMES: 0,
52
+ LUT: 0,
53
+ NAME: 0,
54
+ SCALE: 0,
55
+ SIZE: 0,
56
+ MODE: 0,
57
+ }
58
+
59
+ OPEN = {
60
+ # ifunc93/p3cfunc formats
61
+ "0 1 image": ("1", "1"),
62
+ "L 1 image": ("1", "1"),
63
+ "Greyscale image": ("L", "L"),
64
+ "Grayscale image": ("L", "L"),
65
+ "RGB image": ("RGB", "RGB;L"),
66
+ "RLB image": ("RGB", "RLB"),
67
+ "RYB image": ("RGB", "RLB"),
68
+ "B1 image": ("1", "1"),
69
+ "B2 image": ("P", "P;2"),
70
+ "B4 image": ("P", "P;4"),
71
+ "X 24 image": ("RGB", "RGB"),
72
+ "L 32 S image": ("I", "I;32"),
73
+ "L 32 F image": ("F", "F;32"),
74
+ # old p3cfunc formats
75
+ "RGB3 image": ("RGB", "RGB;T"),
76
+ "RYB3 image": ("RGB", "RYB;T"),
77
+ # extensions
78
+ "LA image": ("LA", "LA;L"),
79
+ "PA image": ("LA", "PA;L"),
80
+ "RGBA image": ("RGBA", "RGBA;L"),
81
+ "RGBX image": ("RGBX", "RGBX;L"),
82
+ "CMYK image": ("CMYK", "CMYK;L"),
83
+ "YCC image": ("YCbCr", "YCbCr;L"),
84
+ }
85
+
86
+ # ifunc95 extensions
87
+ for i in ["8", "8S", "16", "16S", "32", "32F"]:
88
+ OPEN[f"L {i} image"] = ("F", f"F;{i}")
89
+ OPEN[f"L*{i} image"] = ("F", f"F;{i}")
90
+ for i in ["16", "16L", "16B"]:
91
+ OPEN[f"L {i} image"] = (f"I;{i}", f"I;{i}")
92
+ OPEN[f"L*{i} image"] = (f"I;{i}", f"I;{i}")
93
+ for i in ["32S"]:
94
+ OPEN[f"L {i} image"] = ("I", f"I;{i}")
95
+ OPEN[f"L*{i} image"] = ("I", f"I;{i}")
96
+ for i in range(2, 33):
97
+ OPEN[f"L*{i} image"] = ("F", f"F;{i}")
98
+
99
+
100
+ # --------------------------------------------------------------------
101
+ # Read IM directory
102
+
103
+ split = re.compile(rb"^([A-Za-z][^:]*):[ \t]*(.*)[ \t]*$")
104
+
105
+
106
+ def number(s):
107
+ try:
108
+ return int(s)
109
+ except ValueError:
110
+ return float(s)
111
+
112
+
113
+ ##
114
+ # Image plugin for the IFUNC IM file format.
115
+
116
+
117
+ class ImImageFile(ImageFile.ImageFile):
118
+ format = "IM"
119
+ format_description = "IFUNC Image Memory"
120
+ _close_exclusive_fp_after_loading = False
121
+
122
+ def _open(self):
123
+ # Quick rejection: if there's not an LF among the first
124
+ # 100 bytes, this is (probably) not a text header.
125
+
126
+ if b"\n" not in self.fp.read(100):
127
+ msg = "not an IM file"
128
+ raise SyntaxError(msg)
129
+ self.fp.seek(0)
130
+
131
+ n = 0
132
+
133
+ # Default values
134
+ self.info[MODE] = "L"
135
+ self.info[SIZE] = (512, 512)
136
+ self.info[FRAMES] = 1
137
+
138
+ self.rawmode = "L"
139
+
140
+ while True:
141
+ s = self.fp.read(1)
142
+
143
+ # Some versions of IFUNC uses \n\r instead of \r\n...
144
+ if s == b"\r":
145
+ continue
146
+
147
+ if not s or s == b"\0" or s == b"\x1A":
148
+ break
149
+
150
+ # FIXME: this may read whole file if not a text file
151
+ s = s + self.fp.readline()
152
+
153
+ if len(s) > 100:
154
+ msg = "not an IM file"
155
+ raise SyntaxError(msg)
156
+
157
+ if s[-2:] == b"\r\n":
158
+ s = s[:-2]
159
+ elif s[-1:] == b"\n":
160
+ s = s[:-1]
161
+
162
+ try:
163
+ m = split.match(s)
164
+ except re.error as e:
165
+ msg = "not an IM file"
166
+ raise SyntaxError(msg) from e
167
+
168
+ if m:
169
+ k, v = m.group(1, 2)
170
+
171
+ # Don't know if this is the correct encoding,
172
+ # but a decent guess (I guess)
173
+ k = k.decode("latin-1", "replace")
174
+ v = v.decode("latin-1", "replace")
175
+
176
+ # Convert value as appropriate
177
+ if k in [FRAMES, SCALE, SIZE]:
178
+ v = v.replace("*", ",")
179
+ v = tuple(map(number, v.split(",")))
180
+ if len(v) == 1:
181
+ v = v[0]
182
+ elif k == MODE and v in OPEN:
183
+ v, self.rawmode = OPEN[v]
184
+
185
+ # Add to dictionary. Note that COMMENT tags are
186
+ # combined into a list of strings.
187
+ if k == COMMENT:
188
+ if k in self.info:
189
+ self.info[k].append(v)
190
+ else:
191
+ self.info[k] = [v]
192
+ else:
193
+ self.info[k] = v
194
+
195
+ if k in TAGS:
196
+ n += 1
197
+
198
+ else:
199
+ msg = "Syntax error in IM header: " + s.decode("ascii", "replace")
200
+ raise SyntaxError(msg)
201
+
202
+ if not n:
203
+ msg = "Not an IM file"
204
+ raise SyntaxError(msg)
205
+
206
+ # Basic attributes
207
+ self._size = self.info[SIZE]
208
+ self.mode = self.info[MODE]
209
+
210
+ # Skip forward to start of image data
211
+ while s and s[:1] != b"\x1A":
212
+ s = self.fp.read(1)
213
+ if not s:
214
+ msg = "File truncated"
215
+ raise SyntaxError(msg)
216
+
217
+ if LUT in self.info:
218
+ # convert lookup table to palette or lut attribute
219
+ palette = self.fp.read(768)
220
+ greyscale = 1 # greyscale palette
221
+ linear = 1 # linear greyscale palette
222
+ for i in range(256):
223
+ if palette[i] == palette[i + 256] == palette[i + 512]:
224
+ if palette[i] != i:
225
+ linear = 0
226
+ else:
227
+ greyscale = 0
228
+ if self.mode in ["L", "LA", "P", "PA"]:
229
+ if greyscale:
230
+ if not linear:
231
+ self.lut = list(palette[:256])
232
+ else:
233
+ if self.mode in ["L", "P"]:
234
+ self.mode = self.rawmode = "P"
235
+ elif self.mode in ["LA", "PA"]:
236
+ self.mode = "PA"
237
+ self.rawmode = "PA;L"
238
+ self.palette = ImagePalette.raw("RGB;L", palette)
239
+ elif self.mode == "RGB":
240
+ if not greyscale or not linear:
241
+ self.lut = list(palette)
242
+
243
+ self.frame = 0
244
+
245
+ self.__offset = offs = self.fp.tell()
246
+
247
+ self._fp = self.fp # FIXME: hack
248
+
249
+ if self.rawmode[:2] == "F;":
250
+ # ifunc95 formats
251
+ try:
252
+ # use bit decoder (if necessary)
253
+ bits = int(self.rawmode[2:])
254
+ if bits not in [8, 16, 32]:
255
+ self.tile = [("bit", (0, 0) + self.size, offs, (bits, 8, 3, 0, -1))]
256
+ return
257
+ except ValueError:
258
+ pass
259
+
260
+ if self.rawmode in ["RGB;T", "RYB;T"]:
261
+ # Old LabEye/3PC files. Would be very surprised if anyone
262
+ # ever stumbled upon such a file ;-)
263
+ size = self.size[0] * self.size[1]
264
+ self.tile = [
265
+ ("raw", (0, 0) + self.size, offs, ("G", 0, -1)),
266
+ ("raw", (0, 0) + self.size, offs + size, ("R", 0, -1)),
267
+ ("raw", (0, 0) + self.size, offs + 2 * size, ("B", 0, -1)),
268
+ ]
269
+ else:
270
+ # LabEye/IFUNC files
271
+ self.tile = [("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))]
272
+
273
+ @property
274
+ def n_frames(self):
275
+ return self.info[FRAMES]
276
+
277
+ @property
278
+ def is_animated(self):
279
+ return self.info[FRAMES] > 1
280
+
281
+ def seek(self, frame):
282
+ if not self._seek_check(frame):
283
+ return
284
+
285
+ self.frame = frame
286
+
287
+ if self.mode == "1":
288
+ bits = 1
289
+ else:
290
+ bits = 8 * len(self.mode)
291
+
292
+ size = ((self.size[0] * bits + 7) // 8) * self.size[1]
293
+ offs = self.__offset + frame * size
294
+
295
+ self.fp = self._fp
296
+
297
+ self.tile = [("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))]
298
+
299
+ def tell(self):
300
+ return self.frame
301
+
302
+
303
+ #
304
+ # --------------------------------------------------------------------
305
+ # Save IM files
306
+
307
+
308
+ SAVE = {
309
+ # mode: (im type, raw mode)
310
+ "1": ("0 1", "1"),
311
+ "L": ("Greyscale", "L"),
312
+ "LA": ("LA", "LA;L"),
313
+ "P": ("Greyscale", "P"),
314
+ "PA": ("LA", "PA;L"),
315
+ "I": ("L 32S", "I;32S"),
316
+ "I;16": ("L 16", "I;16"),
317
+ "I;16L": ("L 16L", "I;16L"),
318
+ "I;16B": ("L 16B", "I;16B"),
319
+ "F": ("L 32F", "F;32F"),
320
+ "RGB": ("RGB", "RGB;L"),
321
+ "RGBA": ("RGBA", "RGBA;L"),
322
+ "RGBX": ("RGBX", "RGBX;L"),
323
+ "CMYK": ("CMYK", "CMYK;L"),
324
+ "YCbCr": ("YCC", "YCbCr;L"),
325
+ }
326
+
327
+
328
+ def _save(im, fp, filename):
329
+ try:
330
+ image_type, rawmode = SAVE[im.mode]
331
+ except KeyError as e:
332
+ msg = f"Cannot save {im.mode} images as IM"
333
+ raise ValueError(msg) from e
334
+
335
+ frames = im.encoderinfo.get("frames", 1)
336
+
337
+ fp.write(f"Image type: {image_type} image\r\n".encode("ascii"))
338
+ if filename:
339
+ # Each line must be 100 characters or less,
340
+ # or: SyntaxError("not an IM file")
341
+ # 8 characters are used for "Name: " and "\r\n"
342
+ # Keep just the filename, ditch the potentially overlong path
343
+ name, ext = os.path.splitext(os.path.basename(filename))
344
+ name = "".join([name[: 92 - len(ext)], ext])
345
+
346
+ fp.write(f"Name: {name}\r\n".encode("ascii"))
347
+ fp.write(("Image size (x*y): %d*%d\r\n" % im.size).encode("ascii"))
348
+ fp.write(f"File size (no of images): {frames}\r\n".encode("ascii"))
349
+ if im.mode in ["P", "PA"]:
350
+ fp.write(b"Lut: 1\r\n")
351
+ fp.write(b"\000" * (511 - fp.tell()) + b"\032")
352
+ if im.mode in ["P", "PA"]:
353
+ im_palette = im.im.getpalette("RGB", "RGB;L")
354
+ colors = len(im_palette) // 3
355
+ palette = b""
356
+ for i in range(3):
357
+ palette += im_palette[colors * i : colors * (i + 1)]
358
+ palette += b"\x00" * (256 - colors)
359
+ fp.write(palette) # 768 bytes
360
+ ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, -1))])
361
+
362
+
363
+ #
364
+ # --------------------------------------------------------------------
365
+ # Registry
366
+
367
+
368
+ Image.register_open(ImImageFile.format, ImImageFile)
369
+ Image.register_save(ImImageFile.format, _save)
370
+
371
+ Image.register_extension(ImImageFile.format, ".im")
Lib/site-packages/PIL/Image.py ADDED
The diff for this file is too large to render. See raw diff
 
Lib/site-packages/PIL/ImageChops.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # standard channel operations
6
+ #
7
+ # History:
8
+ # 1996-03-24 fl Created
9
+ # 1996-08-13 fl Added logical operations (for "1" images)
10
+ # 2000-10-12 fl Added offset method (from Image.py)
11
+ #
12
+ # Copyright (c) 1997-2000 by Secret Labs AB
13
+ # Copyright (c) 1996-2000 by Fredrik Lundh
14
+ #
15
+ # See the README file for information on usage and redistribution.
16
+ #
17
+
18
+ from . import Image
19
+
20
+
21
+ def constant(image, value):
22
+ """Fill a channel with a given grey level.
23
+
24
+ :rtype: :py:class:`~PIL.Image.Image`
25
+ """
26
+
27
+ return Image.new("L", image.size, value)
28
+
29
+
30
+ def duplicate(image):
31
+ """Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`.
32
+
33
+ :rtype: :py:class:`~PIL.Image.Image`
34
+ """
35
+
36
+ return image.copy()
37
+
38
+
39
+ def invert(image):
40
+ """
41
+ Invert an image (channel). ::
42
+
43
+ out = MAX - image
44
+
45
+ :rtype: :py:class:`~PIL.Image.Image`
46
+ """
47
+
48
+ image.load()
49
+ return image._new(image.im.chop_invert())
50
+
51
+
52
+ def lighter(image1, image2):
53
+ """
54
+ Compares the two images, pixel by pixel, and returns a new image containing
55
+ the lighter values. ::
56
+
57
+ out = max(image1, image2)
58
+
59
+ :rtype: :py:class:`~PIL.Image.Image`
60
+ """
61
+
62
+ image1.load()
63
+ image2.load()
64
+ return image1._new(image1.im.chop_lighter(image2.im))
65
+
66
+
67
+ def darker(image1, image2):
68
+ """
69
+ Compares the two images, pixel by pixel, and returns a new image containing
70
+ the darker values. ::
71
+
72
+ out = min(image1, image2)
73
+
74
+ :rtype: :py:class:`~PIL.Image.Image`
75
+ """
76
+
77
+ image1.load()
78
+ image2.load()
79
+ return image1._new(image1.im.chop_darker(image2.im))
80
+
81
+
82
+ def difference(image1, image2):
83
+ """
84
+ Returns the absolute value of the pixel-by-pixel difference between the two
85
+ images. ::
86
+
87
+ out = abs(image1 - image2)
88
+
89
+ :rtype: :py:class:`~PIL.Image.Image`
90
+ """
91
+
92
+ image1.load()
93
+ image2.load()
94
+ return image1._new(image1.im.chop_difference(image2.im))
95
+
96
+
97
+ def multiply(image1, image2):
98
+ """
99
+ Superimposes two images on top of each other.
100
+
101
+ If you multiply an image with a solid black image, the result is black. If
102
+ you multiply with a solid white image, the image is unaffected. ::
103
+
104
+ out = image1 * image2 / MAX
105
+
106
+ :rtype: :py:class:`~PIL.Image.Image`
107
+ """
108
+
109
+ image1.load()
110
+ image2.load()
111
+ return image1._new(image1.im.chop_multiply(image2.im))
112
+
113
+
114
+ def screen(image1, image2):
115
+ """
116
+ Superimposes two inverted images on top of each other. ::
117
+
118
+ out = MAX - ((MAX - image1) * (MAX - image2) / MAX)
119
+
120
+ :rtype: :py:class:`~PIL.Image.Image`
121
+ """
122
+
123
+ image1.load()
124
+ image2.load()
125
+ return image1._new(image1.im.chop_screen(image2.im))
126
+
127
+
128
+ def soft_light(image1, image2):
129
+ """
130
+ Superimposes two images on top of each other using the Soft Light algorithm
131
+
132
+ :rtype: :py:class:`~PIL.Image.Image`
133
+ """
134
+
135
+ image1.load()
136
+ image2.load()
137
+ return image1._new(image1.im.chop_soft_light(image2.im))
138
+
139
+
140
+ def hard_light(image1, image2):
141
+ """
142
+ Superimposes two images on top of each other using the Hard Light algorithm
143
+
144
+ :rtype: :py:class:`~PIL.Image.Image`
145
+ """
146
+
147
+ image1.load()
148
+ image2.load()
149
+ return image1._new(image1.im.chop_hard_light(image2.im))
150
+
151
+
152
+ def overlay(image1, image2):
153
+ """
154
+ Superimposes two images on top of each other using the Overlay algorithm
155
+
156
+ :rtype: :py:class:`~PIL.Image.Image`
157
+ """
158
+
159
+ image1.load()
160
+ image2.load()
161
+ return image1._new(image1.im.chop_overlay(image2.im))
162
+
163
+
164
+ def add(image1, image2, scale=1.0, offset=0):
165
+ """
166
+ Adds two images, dividing the result by scale and adding the
167
+ offset. If omitted, scale defaults to 1.0, and offset to 0.0. ::
168
+
169
+ out = ((image1 + image2) / scale + offset)
170
+
171
+ :rtype: :py:class:`~PIL.Image.Image`
172
+ """
173
+
174
+ image1.load()
175
+ image2.load()
176
+ return image1._new(image1.im.chop_add(image2.im, scale, offset))
177
+
178
+
179
+ def subtract(image1, image2, scale=1.0, offset=0):
180
+ """
181
+ Subtracts two images, dividing the result by scale and adding the offset.
182
+ If omitted, scale defaults to 1.0, and offset to 0.0. ::
183
+
184
+ out = ((image1 - image2) / scale + offset)
185
+
186
+ :rtype: :py:class:`~PIL.Image.Image`
187
+ """
188
+
189
+ image1.load()
190
+ image2.load()
191
+ return image1._new(image1.im.chop_subtract(image2.im, scale, offset))
192
+
193
+
194
+ def add_modulo(image1, image2):
195
+ """Add two images, without clipping the result. ::
196
+
197
+ out = ((image1 + image2) % MAX)
198
+
199
+ :rtype: :py:class:`~PIL.Image.Image`
200
+ """
201
+
202
+ image1.load()
203
+ image2.load()
204
+ return image1._new(image1.im.chop_add_modulo(image2.im))
205
+
206
+
207
+ def subtract_modulo(image1, image2):
208
+ """Subtract two images, without clipping the result. ::
209
+
210
+ out = ((image1 - image2) % MAX)
211
+
212
+ :rtype: :py:class:`~PIL.Image.Image`
213
+ """
214
+
215
+ image1.load()
216
+ image2.load()
217
+ return image1._new(image1.im.chop_subtract_modulo(image2.im))
218
+
219
+
220
+ def logical_and(image1, image2):
221
+ """Logical AND between two images.
222
+
223
+ Both of the images must have mode "1". If you would like to perform a
224
+ logical AND on an image with a mode other than "1", try
225
+ :py:meth:`~PIL.ImageChops.multiply` instead, using a black-and-white mask
226
+ as the second image. ::
227
+
228
+ out = ((image1 and image2) % MAX)
229
+
230
+ :rtype: :py:class:`~PIL.Image.Image`
231
+ """
232
+
233
+ image1.load()
234
+ image2.load()
235
+ return image1._new(image1.im.chop_and(image2.im))
236
+
237
+
238
+ def logical_or(image1, image2):
239
+ """Logical OR between two images.
240
+
241
+ Both of the images must have mode "1". ::
242
+
243
+ out = ((image1 or image2) % MAX)
244
+
245
+ :rtype: :py:class:`~PIL.Image.Image`
246
+ """
247
+
248
+ image1.load()
249
+ image2.load()
250
+ return image1._new(image1.im.chop_or(image2.im))
251
+
252
+
253
+ def logical_xor(image1, image2):
254
+ """Logical XOR between two images.
255
+
256
+ Both of the images must have mode "1". ::
257
+
258
+ out = ((bool(image1) != bool(image2)) % MAX)
259
+
260
+ :rtype: :py:class:`~PIL.Image.Image`
261
+ """
262
+
263
+ image1.load()
264
+ image2.load()
265
+ return image1._new(image1.im.chop_xor(image2.im))
266
+
267
+
268
+ def blend(image1, image2, alpha):
269
+ """Blend images using constant transparency weight. Alias for
270
+ :py:func:`PIL.Image.blend`.
271
+
272
+ :rtype: :py:class:`~PIL.Image.Image`
273
+ """
274
+
275
+ return Image.blend(image1, image2, alpha)
276
+
277
+
278
+ def composite(image1, image2, mask):
279
+ """Create composite using transparency mask. Alias for
280
+ :py:func:`PIL.Image.composite`.
281
+
282
+ :rtype: :py:class:`~PIL.Image.Image`
283
+ """
284
+
285
+ return Image.composite(image1, image2, mask)
286
+
287
+
288
+ def offset(image, xoffset, yoffset=None):
289
+ """Returns a copy of the image where data has been offset by the given
290
+ distances. Data wraps around the edges. If ``yoffset`` is omitted, it
291
+ is assumed to be equal to ``xoffset``.
292
+
293
+ :param image: Input image.
294
+ :param xoffset: The horizontal distance.
295
+ :param yoffset: The vertical distance. If omitted, both
296
+ distances are set to the same value.
297
+ :rtype: :py:class:`~PIL.Image.Image`
298
+ """
299
+
300
+ if yoffset is None:
301
+ yoffset = xoffset
302
+ image.load()
303
+ return image._new(image.im.offset(xoffset, yoffset))
Lib/site-packages/PIL/ImageCms.py ADDED
@@ -0,0 +1,1009 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The Python Imaging Library.
2
+ # $Id$
3
+
4
+ # Optional color management support, based on Kevin Cazabon's PyCMS
5
+ # library.
6
+
7
+ # History:
8
+
9
+ # 2009-03-08 fl Added to PIL.
10
+
11
+ # Copyright (C) 2002-2003 Kevin Cazabon
12
+ # Copyright (c) 2009 by Fredrik Lundh
13
+ # Copyright (c) 2013 by Eric Soroos
14
+
15
+ # See the README file for information on usage and redistribution. See
16
+ # below for the original description.
17
+
18
+ import sys
19
+ from enum import IntEnum
20
+
21
+ from . import Image
22
+
23
+ try:
24
+ from . import _imagingcms
25
+ except ImportError as ex:
26
+ # Allow error import for doc purposes, but error out when accessing
27
+ # anything in core.
28
+ from ._util import DeferredError
29
+
30
+ _imagingcms = DeferredError(ex)
31
+
32
+ DESCRIPTION = """
33
+ pyCMS
34
+
35
+ a Python / PIL interface to the littleCMS ICC Color Management System
36
+ Copyright (C) 2002-2003 Kevin Cazabon
37
38
+ https://www.cazabon.com
39
+
40
+ pyCMS home page: https://www.cazabon.com/pyCMS
41
+ littleCMS home page: https://www.littlecms.com
42
+ (littleCMS is Copyright (C) 1998-2001 Marti Maria)
43
+
44
+ Originally released under LGPL. Graciously donated to PIL in
45
+ March 2009, for distribution under the standard PIL license
46
+
47
+ The pyCMS.py module provides a "clean" interface between Python/PIL and
48
+ pyCMSdll, taking care of some of the more complex handling of the direct
49
+ pyCMSdll functions, as well as error-checking and making sure that all
50
+ relevant data is kept together.
51
+
52
+ While it is possible to call pyCMSdll functions directly, it's not highly
53
+ recommended.
54
+
55
+ Version History:
56
+
57
+ 1.0.0 pil Oct 2013 Port to LCMS 2.
58
+
59
+ 0.1.0 pil mod March 10, 2009
60
+
61
+ Renamed display profile to proof profile. The proof
62
+ profile is the profile of the device that is being
63
+ simulated, not the profile of the device which is
64
+ actually used to display/print the final simulation
65
+ (that'd be the output profile) - also see LCMSAPI.txt
66
+ input colorspace -> using 'renderingIntent' -> proof
67
+ colorspace -> using 'proofRenderingIntent' -> output
68
+ colorspace
69
+
70
+ Added LCMS FLAGS support.
71
+ Added FLAGS["SOFTPROOFING"] as default flag for
72
+ buildProofTransform (otherwise the proof profile/intent
73
+ would be ignored).
74
+
75
+ 0.1.0 pil March 2009 - added to PIL, as PIL.ImageCms
76
+
77
+ 0.0.2 alpha Jan 6, 2002
78
+
79
+ Added try/except statements around type() checks of
80
+ potential CObjects... Python won't let you use type()
81
+ on them, and raises a TypeError (stupid, if you ask
82
+ me!)
83
+
84
+ Added buildProofTransformFromOpenProfiles() function.
85
+ Additional fixes in DLL, see DLL code for details.
86
+
87
+ 0.0.1 alpha first public release, Dec. 26, 2002
88
+
89
+ Known to-do list with current version (of Python interface, not pyCMSdll):
90
+
91
+ none
92
+
93
+ """
94
+
95
+ VERSION = "1.0.0 pil"
96
+
97
+ # --------------------------------------------------------------------.
98
+
99
+ core = _imagingcms
100
+
101
+ #
102
+ # intent/direction values
103
+
104
+
105
+ class Intent(IntEnum):
106
+ PERCEPTUAL = 0
107
+ RELATIVE_COLORIMETRIC = 1
108
+ SATURATION = 2
109
+ ABSOLUTE_COLORIMETRIC = 3
110
+
111
+
112
+ class Direction(IntEnum):
113
+ INPUT = 0
114
+ OUTPUT = 1
115
+ PROOF = 2
116
+
117
+
118
+ #
119
+ # flags
120
+
121
+ FLAGS = {
122
+ "MATRIXINPUT": 1,
123
+ "MATRIXOUTPUT": 2,
124
+ "MATRIXONLY": (1 | 2),
125
+ "NOWHITEONWHITEFIXUP": 4, # Don't hot fix scum dot
126
+ # Don't create prelinearization tables on precalculated transforms
127
+ # (internal use):
128
+ "NOPRELINEARIZATION": 16,
129
+ "GUESSDEVICECLASS": 32, # Guess device class (for transform2devicelink)
130
+ "NOTCACHE": 64, # Inhibit 1-pixel cache
131
+ "NOTPRECALC": 256,
132
+ "NULLTRANSFORM": 512, # Don't transform anyway
133
+ "HIGHRESPRECALC": 1024, # Use more memory to give better accuracy
134
+ "LOWRESPRECALC": 2048, # Use less memory to minimize resources
135
+ "WHITEBLACKCOMPENSATION": 8192,
136
+ "BLACKPOINTCOMPENSATION": 8192,
137
+ "GAMUTCHECK": 4096, # Out of Gamut alarm
138
+ "SOFTPROOFING": 16384, # Do softproofing
139
+ "PRESERVEBLACK": 32768, # Black preservation
140
+ "NODEFAULTRESOURCEDEF": 16777216, # CRD special
141
+ "GRIDPOINTS": lambda n: (n & 0xFF) << 16, # Gridpoints
142
+ }
143
+
144
+ _MAX_FLAG = 0
145
+ for flag in FLAGS.values():
146
+ if isinstance(flag, int):
147
+ _MAX_FLAG = _MAX_FLAG | flag
148
+
149
+
150
+ # --------------------------------------------------------------------.
151
+ # Experimental PIL-level API
152
+ # --------------------------------------------------------------------.
153
+
154
+ ##
155
+ # Profile.
156
+
157
+
158
+ class ImageCmsProfile:
159
+ def __init__(self, profile):
160
+ """
161
+ :param profile: Either a string representing a filename,
162
+ a file like object containing a profile or a
163
+ low-level profile object
164
+
165
+ """
166
+
167
+ if isinstance(profile, str):
168
+ if sys.platform == "win32":
169
+ profile_bytes_path = profile.encode()
170
+ try:
171
+ profile_bytes_path.decode("ascii")
172
+ except UnicodeDecodeError:
173
+ with open(profile, "rb") as f:
174
+ self._set(core.profile_frombytes(f.read()))
175
+ return
176
+ self._set(core.profile_open(profile), profile)
177
+ elif hasattr(profile, "read"):
178
+ self._set(core.profile_frombytes(profile.read()))
179
+ elif isinstance(profile, _imagingcms.CmsProfile):
180
+ self._set(profile)
181
+ else:
182
+ msg = "Invalid type for Profile"
183
+ raise TypeError(msg)
184
+
185
+ def _set(self, profile, filename=None):
186
+ self.profile = profile
187
+ self.filename = filename
188
+ self.product_name = None # profile.product_name
189
+ self.product_info = None # profile.product_info
190
+
191
+ def tobytes(self):
192
+ """
193
+ Returns the profile in a format suitable for embedding in
194
+ saved images.
195
+
196
+ :returns: a bytes object containing the ICC profile.
197
+ """
198
+
199
+ return core.profile_tobytes(self.profile)
200
+
201
+
202
+ class ImageCmsTransform(Image.ImagePointHandler):
203
+
204
+ """
205
+ Transform. This can be used with the procedural API, or with the standard
206
+ :py:func:`~PIL.Image.Image.point` method.
207
+
208
+ Will return the output profile in the ``output.info['icc_profile']``.
209
+ """
210
+
211
+ def __init__(
212
+ self,
213
+ input,
214
+ output,
215
+ input_mode,
216
+ output_mode,
217
+ intent=Intent.PERCEPTUAL,
218
+ proof=None,
219
+ proof_intent=Intent.ABSOLUTE_COLORIMETRIC,
220
+ flags=0,
221
+ ):
222
+ if proof is None:
223
+ self.transform = core.buildTransform(
224
+ input.profile, output.profile, input_mode, output_mode, intent, flags
225
+ )
226
+ else:
227
+ self.transform = core.buildProofTransform(
228
+ input.profile,
229
+ output.profile,
230
+ proof.profile,
231
+ input_mode,
232
+ output_mode,
233
+ intent,
234
+ proof_intent,
235
+ flags,
236
+ )
237
+ # Note: inputMode and outputMode are for pyCMS compatibility only
238
+ self.input_mode = self.inputMode = input_mode
239
+ self.output_mode = self.outputMode = output_mode
240
+
241
+ self.output_profile = output
242
+
243
+ def point(self, im):
244
+ return self.apply(im)
245
+
246
+ def apply(self, im, imOut=None):
247
+ im.load()
248
+ if imOut is None:
249
+ imOut = Image.new(self.output_mode, im.size, None)
250
+ self.transform.apply(im.im.id, imOut.im.id)
251
+ imOut.info["icc_profile"] = self.output_profile.tobytes()
252
+ return imOut
253
+
254
+ def apply_in_place(self, im):
255
+ im.load()
256
+ if im.mode != self.output_mode:
257
+ msg = "mode mismatch"
258
+ raise ValueError(msg) # wrong output mode
259
+ self.transform.apply(im.im.id, im.im.id)
260
+ im.info["icc_profile"] = self.output_profile.tobytes()
261
+ return im
262
+
263
+
264
+ def get_display_profile(handle=None):
265
+ """
266
+ (experimental) Fetches the profile for the current display device.
267
+
268
+ :returns: ``None`` if the profile is not known.
269
+ """
270
+
271
+ if sys.platform != "win32":
272
+ return None
273
+
274
+ from . import ImageWin
275
+
276
+ if isinstance(handle, ImageWin.HDC):
277
+ profile = core.get_display_profile_win32(handle, 1)
278
+ else:
279
+ profile = core.get_display_profile_win32(handle or 0)
280
+ if profile is None:
281
+ return None
282
+ return ImageCmsProfile(profile)
283
+
284
+
285
+ # --------------------------------------------------------------------.
286
+ # pyCMS compatible layer
287
+ # --------------------------------------------------------------------.
288
+
289
+
290
+ class PyCMSError(Exception):
291
+
292
+ """(pyCMS) Exception class.
293
+ This is used for all errors in the pyCMS API."""
294
+
295
+ pass
296
+
297
+
298
+ def profileToProfile(
299
+ im,
300
+ inputProfile,
301
+ outputProfile,
302
+ renderingIntent=Intent.PERCEPTUAL,
303
+ outputMode=None,
304
+ inPlace=False,
305
+ flags=0,
306
+ ):
307
+ """
308
+ (pyCMS) Applies an ICC transformation to a given image, mapping from
309
+ ``inputProfile`` to ``outputProfile``.
310
+
311
+ If the input or output profiles specified are not valid filenames, a
312
+ :exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and
313
+ ``outputMode != im.mode``, a :exc:`PyCMSError` will be raised.
314
+ If an error occurs during application of the profiles,
315
+ a :exc:`PyCMSError` will be raised.
316
+ If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS),
317
+ a :exc:`PyCMSError` will be raised.
318
+
319
+ This function applies an ICC transformation to im from ``inputProfile``'s
320
+ color space to ``outputProfile``'s color space using the specified rendering
321
+ intent to decide how to handle out-of-gamut colors.
322
+
323
+ ``outputMode`` can be used to specify that a color mode conversion is to
324
+ be done using these profiles, but the specified profiles must be able
325
+ to handle that mode. I.e., if converting im from RGB to CMYK using
326
+ profiles, the input profile must handle RGB data, and the output
327
+ profile must handle CMYK data.
328
+
329
+ :param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...)
330
+ or Image.open(...), etc.)
331
+ :param inputProfile: String, as a valid filename path to the ICC input
332
+ profile you wish to use for this image, or a profile object
333
+ :param outputProfile: String, as a valid filename path to the ICC output
334
+ profile you wish to use for this image, or a profile object
335
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
336
+ wish to use for the transform
337
+
338
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
339
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
340
+ ImageCms.Intent.SATURATION = 2
341
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
342
+
343
+ see the pyCMS documentation for details on rendering intents and what
344
+ they do.
345
+ :param outputMode: A valid PIL mode for the output image (i.e. "RGB",
346
+ "CMYK", etc.). Note: if rendering the image "inPlace", outputMode
347
+ MUST be the same mode as the input, or omitted completely. If
348
+ omitted, the outputMode will be the same as the mode of the input
349
+ image (im.mode)
350
+ :param inPlace: Boolean. If ``True``, the original image is modified in-place,
351
+ and ``None`` is returned. If ``False`` (default), a new
352
+ :py:class:`~PIL.Image.Image` object is returned with the transform applied.
353
+ :param flags: Integer (0-...) specifying additional flags
354
+ :returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on
355
+ the value of ``inPlace``
356
+ :exception PyCMSError:
357
+ """
358
+
359
+ if outputMode is None:
360
+ outputMode = im.mode
361
+
362
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
363
+ msg = "renderingIntent must be an integer between 0 and 3"
364
+ raise PyCMSError(msg)
365
+
366
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
367
+ msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
368
+ raise PyCMSError(msg)
369
+
370
+ try:
371
+ if not isinstance(inputProfile, ImageCmsProfile):
372
+ inputProfile = ImageCmsProfile(inputProfile)
373
+ if not isinstance(outputProfile, ImageCmsProfile):
374
+ outputProfile = ImageCmsProfile(outputProfile)
375
+ transform = ImageCmsTransform(
376
+ inputProfile,
377
+ outputProfile,
378
+ im.mode,
379
+ outputMode,
380
+ renderingIntent,
381
+ flags=flags,
382
+ )
383
+ if inPlace:
384
+ transform.apply_in_place(im)
385
+ imOut = None
386
+ else:
387
+ imOut = transform.apply(im)
388
+ except (OSError, TypeError, ValueError) as v:
389
+ raise PyCMSError(v) from v
390
+
391
+ return imOut
392
+
393
+
394
+ def getOpenProfile(profileFilename):
395
+ """
396
+ (pyCMS) Opens an ICC profile file.
397
+
398
+ The PyCMSProfile object can be passed back into pyCMS for use in creating
399
+ transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
400
+
401
+ If ``profileFilename`` is not a valid filename for an ICC profile,
402
+ a :exc:`PyCMSError` will be raised.
403
+
404
+ :param profileFilename: String, as a valid filename path to the ICC profile
405
+ you wish to open, or a file-like object.
406
+ :returns: A CmsProfile class object.
407
+ :exception PyCMSError:
408
+ """
409
+
410
+ try:
411
+ return ImageCmsProfile(profileFilename)
412
+ except (OSError, TypeError, ValueError) as v:
413
+ raise PyCMSError(v) from v
414
+
415
+
416
+ def buildTransform(
417
+ inputProfile,
418
+ outputProfile,
419
+ inMode,
420
+ outMode,
421
+ renderingIntent=Intent.PERCEPTUAL,
422
+ flags=0,
423
+ ):
424
+ """
425
+ (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
426
+ ``outputProfile``. Use applyTransform to apply the transform to a given
427
+ image.
428
+
429
+ If the input or output profiles specified are not valid filenames, a
430
+ :exc:`PyCMSError` will be raised. If an error occurs during creation
431
+ of the transform, a :exc:`PyCMSError` will be raised.
432
+
433
+ If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
434
+ (or by pyCMS), a :exc:`PyCMSError` will be raised.
435
+
436
+ This function builds and returns an ICC transform from the ``inputProfile``
437
+ to the ``outputProfile`` using the ``renderingIntent`` to determine what to do
438
+ with out-of-gamut colors. It will ONLY work for converting images that
439
+ are in ``inMode`` to images that are in ``outMode`` color format (PIL mode,
440
+ i.e. "RGB", "RGBA", "CMYK", etc.).
441
+
442
+ Building the transform is a fair part of the overhead in
443
+ ImageCms.profileToProfile(), so if you're planning on converting multiple
444
+ images using the same input/output settings, this can save you time.
445
+ Once you have a transform object, it can be used with
446
+ ImageCms.applyProfile() to convert images without the need to re-compute
447
+ the lookup table for the transform.
448
+
449
+ The reason pyCMS returns a class object rather than a handle directly
450
+ to the transform is that it needs to keep track of the PIL input/output
451
+ modes that the transform is meant for. These attributes are stored in
452
+ the ``inMode`` and ``outMode`` attributes of the object (which can be
453
+ manually overridden if you really want to, but I don't know of any
454
+ time that would be of use, or would even work).
455
+
456
+ :param inputProfile: String, as a valid filename path to the ICC input
457
+ profile you wish to use for this transform, or a profile object
458
+ :param outputProfile: String, as a valid filename path to the ICC output
459
+ profile you wish to use for this transform, or a profile object
460
+ :param inMode: String, as a valid PIL mode that the appropriate profile
461
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
462
+ :param outMode: String, as a valid PIL mode that the appropriate profile
463
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
464
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
465
+ wish to use for the transform
466
+
467
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
468
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
469
+ ImageCms.Intent.SATURATION = 2
470
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
471
+
472
+ see the pyCMS documentation for details on rendering intents and what
473
+ they do.
474
+ :param flags: Integer (0-...) specifying additional flags
475
+ :returns: A CmsTransform class object.
476
+ :exception PyCMSError:
477
+ """
478
+
479
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
480
+ msg = "renderingIntent must be an integer between 0 and 3"
481
+ raise PyCMSError(msg)
482
+
483
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
484
+ msg = "flags must be an integer between 0 and %s" + _MAX_FLAG
485
+ raise PyCMSError(msg)
486
+
487
+ try:
488
+ if not isinstance(inputProfile, ImageCmsProfile):
489
+ inputProfile = ImageCmsProfile(inputProfile)
490
+ if not isinstance(outputProfile, ImageCmsProfile):
491
+ outputProfile = ImageCmsProfile(outputProfile)
492
+ return ImageCmsTransform(
493
+ inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags
494
+ )
495
+ except (OSError, TypeError, ValueError) as v:
496
+ raise PyCMSError(v) from v
497
+
498
+
499
+ def buildProofTransform(
500
+ inputProfile,
501
+ outputProfile,
502
+ proofProfile,
503
+ inMode,
504
+ outMode,
505
+ renderingIntent=Intent.PERCEPTUAL,
506
+ proofRenderingIntent=Intent.ABSOLUTE_COLORIMETRIC,
507
+ flags=FLAGS["SOFTPROOFING"],
508
+ ):
509
+ """
510
+ (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
511
+ ``outputProfile``, but tries to simulate the result that would be
512
+ obtained on the ``proofProfile`` device.
513
+
514
+ If the input, output, or proof profiles specified are not valid
515
+ filenames, a :exc:`PyCMSError` will be raised.
516
+
517
+ If an error occurs during creation of the transform,
518
+ a :exc:`PyCMSError` will be raised.
519
+
520
+ If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
521
+ (or by pyCMS), a :exc:`PyCMSError` will be raised.
522
+
523
+ This function builds and returns an ICC transform from the ``inputProfile``
524
+ to the ``outputProfile``, but tries to simulate the result that would be
525
+ obtained on the ``proofProfile`` device using ``renderingIntent`` and
526
+ ``proofRenderingIntent`` to determine what to do with out-of-gamut
527
+ colors. This is known as "soft-proofing". It will ONLY work for
528
+ converting images that are in ``inMode`` to images that are in outMode
529
+ color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.).
530
+
531
+ Usage of the resulting transform object is exactly the same as with
532
+ ImageCms.buildTransform().
533
+
534
+ Proof profiling is generally used when using an output device to get a
535
+ good idea of what the final printed/displayed image would look like on
536
+ the ``proofProfile`` device when it's quicker and easier to use the
537
+ output device for judging color. Generally, this means that the
538
+ output device is a monitor, or a dye-sub printer (etc.), and the simulated
539
+ device is something more expensive, complicated, or time consuming
540
+ (making it difficult to make a real print for color judgement purposes).
541
+
542
+ Soft-proofing basically functions by adjusting the colors on the
543
+ output device to match the colors of the device being simulated. However,
544
+ when the simulated device has a much wider gamut than the output
545
+ device, you may obtain marginal results.
546
+
547
+ :param inputProfile: String, as a valid filename path to the ICC input
548
+ profile you wish to use for this transform, or a profile object
549
+ :param outputProfile: String, as a valid filename path to the ICC output
550
+ (monitor, usually) profile you wish to use for this transform, or a
551
+ profile object
552
+ :param proofProfile: String, as a valid filename path to the ICC proof
553
+ profile you wish to use for this transform, or a profile object
554
+ :param inMode: String, as a valid PIL mode that the appropriate profile
555
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
556
+ :param outMode: String, as a valid PIL mode that the appropriate profile
557
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
558
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
559
+ wish to use for the input->proof (simulated) transform
560
+
561
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
562
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
563
+ ImageCms.Intent.SATURATION = 2
564
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
565
+
566
+ see the pyCMS documentation for details on rendering intents and what
567
+ they do.
568
+ :param proofRenderingIntent: Integer (0-3) specifying the rendering intent
569
+ you wish to use for proof->output transform
570
+
571
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
572
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
573
+ ImageCms.Intent.SATURATION = 2
574
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
575
+
576
+ see the pyCMS documentation for details on rendering intents and what
577
+ they do.
578
+ :param flags: Integer (0-...) specifying additional flags
579
+ :returns: A CmsTransform class object.
580
+ :exception PyCMSError:
581
+ """
582
+
583
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
584
+ msg = "renderingIntent must be an integer between 0 and 3"
585
+ raise PyCMSError(msg)
586
+
587
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
588
+ msg = "flags must be an integer between 0 and %s" + _MAX_FLAG
589
+ raise PyCMSError(msg)
590
+
591
+ try:
592
+ if not isinstance(inputProfile, ImageCmsProfile):
593
+ inputProfile = ImageCmsProfile(inputProfile)
594
+ if not isinstance(outputProfile, ImageCmsProfile):
595
+ outputProfile = ImageCmsProfile(outputProfile)
596
+ if not isinstance(proofProfile, ImageCmsProfile):
597
+ proofProfile = ImageCmsProfile(proofProfile)
598
+ return ImageCmsTransform(
599
+ inputProfile,
600
+ outputProfile,
601
+ inMode,
602
+ outMode,
603
+ renderingIntent,
604
+ proofProfile,
605
+ proofRenderingIntent,
606
+ flags,
607
+ )
608
+ except (OSError, TypeError, ValueError) as v:
609
+ raise PyCMSError(v) from v
610
+
611
+
612
+ buildTransformFromOpenProfiles = buildTransform
613
+ buildProofTransformFromOpenProfiles = buildProofTransform
614
+
615
+
616
+ def applyTransform(im, transform, inPlace=False):
617
+ """
618
+ (pyCMS) Applies a transform to a given image.
619
+
620
+ If ``im.mode != transform.inMode``, a :exc:`PyCMSError` is raised.
621
+
622
+ If ``inPlace`` is ``True`` and ``transform.inMode != transform.outMode``, a
623
+ :exc:`PyCMSError` is raised.
624
+
625
+ If ``im.mode``, ``transform.inMode`` or ``transform.outMode`` is not
626
+ supported by pyCMSdll or the profiles you used for the transform, a
627
+ :exc:`PyCMSError` is raised.
628
+
629
+ If an error occurs while the transform is being applied,
630
+ a :exc:`PyCMSError` is raised.
631
+
632
+ This function applies a pre-calculated transform (from
633
+ ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles())
634
+ to an image. The transform can be used for multiple images, saving
635
+ considerable calculation time if doing the same conversion multiple times.
636
+
637
+ If you want to modify im in-place instead of receiving a new image as
638
+ the return value, set ``inPlace`` to ``True``. This can only be done if
639
+ ``transform.inMode`` and ``transform.outMode`` are the same, because we can't
640
+ change the mode in-place (the buffer sizes for some modes are
641
+ different). The default behavior is to return a new :py:class:`~PIL.Image.Image`
642
+ object of the same dimensions in mode ``transform.outMode``.
643
+
644
+ :param im: An :py:class:`~PIL.Image.Image` object, and im.mode must be the same
645
+ as the ``inMode`` supported by the transform.
646
+ :param transform: A valid CmsTransform class object
647
+ :param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is
648
+ returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the
649
+ transform applied is returned (and ``im`` is not changed). The default is
650
+ ``False``.
651
+ :returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object,
652
+ depending on the value of ``inPlace``. The profile will be returned in
653
+ the image's ``info['icc_profile']``.
654
+ :exception PyCMSError:
655
+ """
656
+
657
+ try:
658
+ if inPlace:
659
+ transform.apply_in_place(im)
660
+ imOut = None
661
+ else:
662
+ imOut = transform.apply(im)
663
+ except (TypeError, ValueError) as v:
664
+ raise PyCMSError(v) from v
665
+
666
+ return imOut
667
+
668
+
669
+ def createProfile(colorSpace, colorTemp=-1):
670
+ """
671
+ (pyCMS) Creates a profile.
672
+
673
+ If colorSpace not in ``["LAB", "XYZ", "sRGB"]``,
674
+ a :exc:`PyCMSError` is raised.
675
+
676
+ If using LAB and ``colorTemp`` is not a positive integer,
677
+ a :exc:`PyCMSError` is raised.
678
+
679
+ If an error occurs while creating the profile,
680
+ a :exc:`PyCMSError` is raised.
681
+
682
+ Use this function to create common profiles on-the-fly instead of
683
+ having to supply a profile on disk and knowing the path to it. It
684
+ returns a normal CmsProfile object that can be passed to
685
+ ImageCms.buildTransformFromOpenProfiles() to create a transform to apply
686
+ to images.
687
+
688
+ :param colorSpace: String, the color space of the profile you wish to
689
+ create.
690
+ Currently only "LAB", "XYZ", and "sRGB" are supported.
691
+ :param colorTemp: Positive integer for the white point for the profile, in
692
+ degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50
693
+ illuminant if omitted (5000k). colorTemp is ONLY applied to LAB
694
+ profiles, and is ignored for XYZ and sRGB.
695
+ :returns: A CmsProfile class object
696
+ :exception PyCMSError:
697
+ """
698
+
699
+ if colorSpace not in ["LAB", "XYZ", "sRGB"]:
700
+ msg = (
701
+ f"Color space not supported for on-the-fly profile creation ({colorSpace})"
702
+ )
703
+ raise PyCMSError(msg)
704
+
705
+ if colorSpace == "LAB":
706
+ try:
707
+ colorTemp = float(colorTemp)
708
+ except (TypeError, ValueError) as e:
709
+ msg = f'Color temperature must be numeric, "{colorTemp}" not valid'
710
+ raise PyCMSError(msg) from e
711
+
712
+ try:
713
+ return core.createProfile(colorSpace, colorTemp)
714
+ except (TypeError, ValueError) as v:
715
+ raise PyCMSError(v) from v
716
+
717
+
718
+ def getProfileName(profile):
719
+ """
720
+
721
+ (pyCMS) Gets the internal product name for the given profile.
722
+
723
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile,
724
+ a :exc:`PyCMSError` is raised If an error occurs while trying
725
+ to obtain the name tag, a :exc:`PyCMSError` is raised.
726
+
727
+ Use this function to obtain the INTERNAL name of the profile (stored
728
+ in an ICC tag in the profile itself), usually the one used when the
729
+ profile was originally created. Sometimes this tag also contains
730
+ additional information supplied by the creator.
731
+
732
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
733
+ filename of an ICC profile.
734
+ :returns: A string containing the internal name of the profile as stored
735
+ in an ICC tag.
736
+ :exception PyCMSError:
737
+ """
738
+
739
+ try:
740
+ # add an extra newline to preserve pyCMS compatibility
741
+ if not isinstance(profile, ImageCmsProfile):
742
+ profile = ImageCmsProfile(profile)
743
+ # do it in python, not c.
744
+ # // name was "%s - %s" (model, manufacturer) || Description ,
745
+ # // but if the Model and Manufacturer were the same or the model
746
+ # // was long, Just the model, in 1.x
747
+ model = profile.profile.model
748
+ manufacturer = profile.profile.manufacturer
749
+
750
+ if not (model or manufacturer):
751
+ return (profile.profile.profile_description or "") + "\n"
752
+ if not manufacturer or len(model) > 30:
753
+ return model + "\n"
754
+ return f"{model} - {manufacturer}\n"
755
+
756
+ except (AttributeError, OSError, TypeError, ValueError) as v:
757
+ raise PyCMSError(v) from v
758
+
759
+
760
+ def getProfileInfo(profile):
761
+ """
762
+ (pyCMS) Gets the internal product information for the given profile.
763
+
764
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile,
765
+ a :exc:`PyCMSError` is raised.
766
+
767
+ If an error occurs while trying to obtain the info tag,
768
+ a :exc:`PyCMSError` is raised.
769
+
770
+ Use this function to obtain the information stored in the profile's
771
+ info tag. This often contains details about the profile, and how it
772
+ was created, as supplied by the creator.
773
+
774
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
775
+ filename of an ICC profile.
776
+ :returns: A string containing the internal profile information stored in
777
+ an ICC tag.
778
+ :exception PyCMSError:
779
+ """
780
+
781
+ try:
782
+ if not isinstance(profile, ImageCmsProfile):
783
+ profile = ImageCmsProfile(profile)
784
+ # add an extra newline to preserve pyCMS compatibility
785
+ # Python, not C. the white point bits weren't working well,
786
+ # so skipping.
787
+ # info was description \r\n\r\n copyright \r\n\r\n K007 tag \r\n\r\n whitepoint
788
+ description = profile.profile.profile_description
789
+ cpright = profile.profile.copyright
790
+ arr = []
791
+ for elt in (description, cpright):
792
+ if elt:
793
+ arr.append(elt)
794
+ return "\r\n\r\n".join(arr) + "\r\n\r\n"
795
+
796
+ except (AttributeError, OSError, TypeError, ValueError) as v:
797
+ raise PyCMSError(v) from v
798
+
799
+
800
+ def getProfileCopyright(profile):
801
+ """
802
+ (pyCMS) Gets the copyright for the given profile.
803
+
804
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
805
+ :exc:`PyCMSError` is raised.
806
+
807
+ If an error occurs while trying to obtain the copyright tag,
808
+ a :exc:`PyCMSError` is raised.
809
+
810
+ Use this function to obtain the information stored in the profile's
811
+ copyright tag.
812
+
813
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
814
+ filename of an ICC profile.
815
+ :returns: A string containing the internal profile information stored in
816
+ an ICC tag.
817
+ :exception PyCMSError:
818
+ """
819
+ try:
820
+ # add an extra newline to preserve pyCMS compatibility
821
+ if not isinstance(profile, ImageCmsProfile):
822
+ profile = ImageCmsProfile(profile)
823
+ return (profile.profile.copyright or "") + "\n"
824
+ except (AttributeError, OSError, TypeError, ValueError) as v:
825
+ raise PyCMSError(v) from v
826
+
827
+
828
+ def getProfileManufacturer(profile):
829
+ """
830
+ (pyCMS) Gets the manufacturer for the given profile.
831
+
832
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
833
+ :exc:`PyCMSError` is raised.
834
+
835
+ If an error occurs while trying to obtain the manufacturer tag, a
836
+ :exc:`PyCMSError` is raised.
837
+
838
+ Use this function to obtain the information stored in the profile's
839
+ manufacturer tag.
840
+
841
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
842
+ filename of an ICC profile.
843
+ :returns: A string containing the internal profile information stored in
844
+ an ICC tag.
845
+ :exception PyCMSError:
846
+ """
847
+ try:
848
+ # add an extra newline to preserve pyCMS compatibility
849
+ if not isinstance(profile, ImageCmsProfile):
850
+ profile = ImageCmsProfile(profile)
851
+ return (profile.profile.manufacturer or "") + "\n"
852
+ except (AttributeError, OSError, TypeError, ValueError) as v:
853
+ raise PyCMSError(v) from v
854
+
855
+
856
+ def getProfileModel(profile):
857
+ """
858
+ (pyCMS) Gets the model for the given profile.
859
+
860
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
861
+ :exc:`PyCMSError` is raised.
862
+
863
+ If an error occurs while trying to obtain the model tag,
864
+ a :exc:`PyCMSError` is raised.
865
+
866
+ Use this function to obtain the information stored in the profile's
867
+ model tag.
868
+
869
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
870
+ filename of an ICC profile.
871
+ :returns: A string containing the internal profile information stored in
872
+ an ICC tag.
873
+ :exception PyCMSError:
874
+ """
875
+
876
+ try:
877
+ # add an extra newline to preserve pyCMS compatibility
878
+ if not isinstance(profile, ImageCmsProfile):
879
+ profile = ImageCmsProfile(profile)
880
+ return (profile.profile.model or "") + "\n"
881
+ except (AttributeError, OSError, TypeError, ValueError) as v:
882
+ raise PyCMSError(v) from v
883
+
884
+
885
+ def getProfileDescription(profile):
886
+ """
887
+ (pyCMS) Gets the description for the given profile.
888
+
889
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
890
+ :exc:`PyCMSError` is raised.
891
+
892
+ If an error occurs while trying to obtain the description tag,
893
+ a :exc:`PyCMSError` is raised.
894
+
895
+ Use this function to obtain the information stored in the profile's
896
+ description tag.
897
+
898
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
899
+ filename of an ICC profile.
900
+ :returns: A string containing the internal profile information stored in an
901
+ ICC tag.
902
+ :exception PyCMSError:
903
+ """
904
+
905
+ try:
906
+ # add an extra newline to preserve pyCMS compatibility
907
+ if not isinstance(profile, ImageCmsProfile):
908
+ profile = ImageCmsProfile(profile)
909
+ return (profile.profile.profile_description or "") + "\n"
910
+ except (AttributeError, OSError, TypeError, ValueError) as v:
911
+ raise PyCMSError(v) from v
912
+
913
+
914
+ def getDefaultIntent(profile):
915
+ """
916
+ (pyCMS) Gets the default intent name for the given profile.
917
+
918
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
919
+ :exc:`PyCMSError` is raised.
920
+
921
+ If an error occurs while trying to obtain the default intent, a
922
+ :exc:`PyCMSError` is raised.
923
+
924
+ Use this function to determine the default (and usually best optimized)
925
+ rendering intent for this profile. Most profiles support multiple
926
+ rendering intents, but are intended mostly for one type of conversion.
927
+ If you wish to use a different intent than returned, use
928
+ ImageCms.isIntentSupported() to verify it will work first.
929
+
930
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
931
+ filename of an ICC profile.
932
+ :returns: Integer 0-3 specifying the default rendering intent for this
933
+ profile.
934
+
935
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
936
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
937
+ ImageCms.Intent.SATURATION = 2
938
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
939
+
940
+ see the pyCMS documentation for details on rendering intents and what
941
+ they do.
942
+ :exception PyCMSError:
943
+ """
944
+
945
+ try:
946
+ if not isinstance(profile, ImageCmsProfile):
947
+ profile = ImageCmsProfile(profile)
948
+ return profile.profile.rendering_intent
949
+ except (AttributeError, OSError, TypeError, ValueError) as v:
950
+ raise PyCMSError(v) from v
951
+
952
+
953
+ def isIntentSupported(profile, intent, direction):
954
+ """
955
+ (pyCMS) Checks if a given intent is supported.
956
+
957
+ Use this function to verify that you can use your desired
958
+ ``intent`` with ``profile``, and that ``profile`` can be used for the
959
+ input/output/proof profile as you desire.
960
+
961
+ Some profiles are created specifically for one "direction", can cannot
962
+ be used for others. Some profiles can only be used for certain
963
+ rendering intents, so it's best to either verify this before trying
964
+ to create a transform with them (using this function), or catch the
965
+ potential :exc:`PyCMSError` that will occur if they don't
966
+ support the modes you select.
967
+
968
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
969
+ filename of an ICC profile.
970
+ :param intent: Integer (0-3) specifying the rendering intent you wish to
971
+ use with this profile
972
+
973
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
974
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
975
+ ImageCms.Intent.SATURATION = 2
976
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
977
+
978
+ see the pyCMS documentation for details on rendering intents and what
979
+ they do.
980
+ :param direction: Integer specifying if the profile is to be used for
981
+ input, output, or proof
982
+
983
+ INPUT = 0 (or use ImageCms.Direction.INPUT)
984
+ OUTPUT = 1 (or use ImageCms.Direction.OUTPUT)
985
+ PROOF = 2 (or use ImageCms.Direction.PROOF)
986
+
987
+ :returns: 1 if the intent/direction are supported, -1 if they are not.
988
+ :exception PyCMSError:
989
+ """
990
+
991
+ try:
992
+ if not isinstance(profile, ImageCmsProfile):
993
+ profile = ImageCmsProfile(profile)
994
+ # FIXME: I get different results for the same data w. different
995
+ # compilers. Bug in LittleCMS or in the binding?
996
+ if profile.profile.is_intent_supported(intent, direction):
997
+ return 1
998
+ else:
999
+ return -1
1000
+ except (AttributeError, OSError, TypeError, ValueError) as v:
1001
+ raise PyCMSError(v) from v
1002
+
1003
+
1004
+ def versions():
1005
+ """
1006
+ (pyCMS) Fetches versions.
1007
+ """
1008
+
1009
+ return VERSION, core.littlecms_version, sys.version.split()[0], Image.__version__
Lib/site-packages/PIL/ImageColor.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # map CSS3-style colour description strings to RGB
6
+ #
7
+ # History:
8
+ # 2002-10-24 fl Added support for CSS-style color strings
9
+ # 2002-12-15 fl Added RGBA support
10
+ # 2004-03-27 fl Fixed remaining int() problems for Python 1.5.2
11
+ # 2004-07-19 fl Fixed gray/grey spelling issues
12
+ # 2009-03-05 fl Fixed rounding error in grayscale calculation
13
+ #
14
+ # Copyright (c) 2002-2004 by Secret Labs AB
15
+ # Copyright (c) 2002-2004 by Fredrik Lundh
16
+ #
17
+ # See the README file for information on usage and redistribution.
18
+ #
19
+
20
+ import re
21
+
22
+ from . import Image
23
+
24
+
25
+ def getrgb(color):
26
+ """
27
+ Convert a color string to an RGB or RGBA tuple. If the string cannot be
28
+ parsed, this function raises a :py:exc:`ValueError` exception.
29
+
30
+ .. versionadded:: 1.1.4
31
+
32
+ :param color: A color string
33
+ :return: ``(red, green, blue[, alpha])``
34
+ """
35
+ if len(color) > 100:
36
+ msg = "color specifier is too long"
37
+ raise ValueError(msg)
38
+ color = color.lower()
39
+
40
+ rgb = colormap.get(color, None)
41
+ if rgb:
42
+ if isinstance(rgb, tuple):
43
+ return rgb
44
+ colormap[color] = rgb = getrgb(rgb)
45
+ return rgb
46
+
47
+ # check for known string formats
48
+ if re.match("#[a-f0-9]{3}$", color):
49
+ return int(color[1] * 2, 16), int(color[2] * 2, 16), int(color[3] * 2, 16)
50
+
51
+ if re.match("#[a-f0-9]{4}$", color):
52
+ return (
53
+ int(color[1] * 2, 16),
54
+ int(color[2] * 2, 16),
55
+ int(color[3] * 2, 16),
56
+ int(color[4] * 2, 16),
57
+ )
58
+
59
+ if re.match("#[a-f0-9]{6}$", color):
60
+ return int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)
61
+
62
+ if re.match("#[a-f0-9]{8}$", color):
63
+ return (
64
+ int(color[1:3], 16),
65
+ int(color[3:5], 16),
66
+ int(color[5:7], 16),
67
+ int(color[7:9], 16),
68
+ )
69
+
70
+ m = re.match(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
71
+ if m:
72
+ return int(m.group(1)), int(m.group(2)), int(m.group(3))
73
+
74
+ m = re.match(r"rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$", color)
75
+ if m:
76
+ return (
77
+ int((int(m.group(1)) * 255) / 100.0 + 0.5),
78
+ int((int(m.group(2)) * 255) / 100.0 + 0.5),
79
+ int((int(m.group(3)) * 255) / 100.0 + 0.5),
80
+ )
81
+
82
+ m = re.match(
83
+ r"hsl\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
84
+ )
85
+ if m:
86
+ from colorsys import hls_to_rgb
87
+
88
+ rgb = hls_to_rgb(
89
+ float(m.group(1)) / 360.0,
90
+ float(m.group(3)) / 100.0,
91
+ float(m.group(2)) / 100.0,
92
+ )
93
+ return (
94
+ int(rgb[0] * 255 + 0.5),
95
+ int(rgb[1] * 255 + 0.5),
96
+ int(rgb[2] * 255 + 0.5),
97
+ )
98
+
99
+ m = re.match(
100
+ r"hs[bv]\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
101
+ )
102
+ if m:
103
+ from colorsys import hsv_to_rgb
104
+
105
+ rgb = hsv_to_rgb(
106
+ float(m.group(1)) / 360.0,
107
+ float(m.group(2)) / 100.0,
108
+ float(m.group(3)) / 100.0,
109
+ )
110
+ return (
111
+ int(rgb[0] * 255 + 0.5),
112
+ int(rgb[1] * 255 + 0.5),
113
+ int(rgb[2] * 255 + 0.5),
114
+ )
115
+
116
+ m = re.match(r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
117
+ if m:
118
+ return int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))
119
+ msg = f"unknown color specifier: {repr(color)}"
120
+ raise ValueError(msg)
121
+
122
+
123
+ def getcolor(color, mode):
124
+ """
125
+ Same as :py:func:`~PIL.ImageColor.getrgb` for most modes. However, if
126
+ ``mode`` is HSV, converts the RGB value to a HSV value, or if ``mode`` is
127
+ not color or a palette image, converts the RGB value to a greyscale value.
128
+ If the string cannot be parsed, this function raises a :py:exc:`ValueError`
129
+ exception.
130
+
131
+ .. versionadded:: 1.1.4
132
+
133
+ :param color: A color string
134
+ :param mode: Convert result to this mode
135
+ :return: ``(graylevel[, alpha]) or (red, green, blue[, alpha])``
136
+ """
137
+ # same as getrgb, but converts the result to the given mode
138
+ color, alpha = getrgb(color), 255
139
+ if len(color) == 4:
140
+ color, alpha = color[:3], color[3]
141
+
142
+ if mode == "HSV":
143
+ from colorsys import rgb_to_hsv
144
+
145
+ r, g, b = color
146
+ h, s, v = rgb_to_hsv(r / 255, g / 255, b / 255)
147
+ return int(h * 255), int(s * 255), int(v * 255)
148
+ elif Image.getmodebase(mode) == "L":
149
+ r, g, b = color
150
+ # ITU-R Recommendation 601-2 for nonlinear RGB
151
+ # scaled to 24 bits to match the convert's implementation.
152
+ color = (r * 19595 + g * 38470 + b * 7471 + 0x8000) >> 16
153
+ if mode[-1] == "A":
154
+ return color, alpha
155
+ else:
156
+ if mode[-1] == "A":
157
+ return color + (alpha,)
158
+ return color
159
+
160
+
161
+ colormap = {
162
+ # X11 colour table from https://drafts.csswg.org/css-color-4/, with
163
+ # gray/grey spelling issues fixed. This is a superset of HTML 4.0
164
+ # colour names used in CSS 1.
165
+ "aliceblue": "#f0f8ff",
166
+ "antiquewhite": "#faebd7",
167
+ "aqua": "#00ffff",
168
+ "aquamarine": "#7fffd4",
169
+ "azure": "#f0ffff",
170
+ "beige": "#f5f5dc",
171
+ "bisque": "#ffe4c4",
172
+ "black": "#000000",
173
+ "blanchedalmond": "#ffebcd",
174
+ "blue": "#0000ff",
175
+ "blueviolet": "#8a2be2",
176
+ "brown": "#a52a2a",
177
+ "burlywood": "#deb887",
178
+ "cadetblue": "#5f9ea0",
179
+ "chartreuse": "#7fff00",
180
+ "chocolate": "#d2691e",
181
+ "coral": "#ff7f50",
182
+ "cornflowerblue": "#6495ed",
183
+ "cornsilk": "#fff8dc",
184
+ "crimson": "#dc143c",
185
+ "cyan": "#00ffff",
186
+ "darkblue": "#00008b",
187
+ "darkcyan": "#008b8b",
188
+ "darkgoldenrod": "#b8860b",
189
+ "darkgray": "#a9a9a9",
190
+ "darkgrey": "#a9a9a9",
191
+ "darkgreen": "#006400",
192
+ "darkkhaki": "#bdb76b",
193
+ "darkmagenta": "#8b008b",
194
+ "darkolivegreen": "#556b2f",
195
+ "darkorange": "#ff8c00",
196
+ "darkorchid": "#9932cc",
197
+ "darkred": "#8b0000",
198
+ "darksalmon": "#e9967a",
199
+ "darkseagreen": "#8fbc8f",
200
+ "darkslateblue": "#483d8b",
201
+ "darkslategray": "#2f4f4f",
202
+ "darkslategrey": "#2f4f4f",
203
+ "darkturquoise": "#00ced1",
204
+ "darkviolet": "#9400d3",
205
+ "deeppink": "#ff1493",
206
+ "deepskyblue": "#00bfff",
207
+ "dimgray": "#696969",
208
+ "dimgrey": "#696969",
209
+ "dodgerblue": "#1e90ff",
210
+ "firebrick": "#b22222",
211
+ "floralwhite": "#fffaf0",
212
+ "forestgreen": "#228b22",
213
+ "fuchsia": "#ff00ff",
214
+ "gainsboro": "#dcdcdc",
215
+ "ghostwhite": "#f8f8ff",
216
+ "gold": "#ffd700",
217
+ "goldenrod": "#daa520",
218
+ "gray": "#808080",
219
+ "grey": "#808080",
220
+ "green": "#008000",
221
+ "greenyellow": "#adff2f",
222
+ "honeydew": "#f0fff0",
223
+ "hotpink": "#ff69b4",
224
+ "indianred": "#cd5c5c",
225
+ "indigo": "#4b0082",
226
+ "ivory": "#fffff0",
227
+ "khaki": "#f0e68c",
228
+ "lavender": "#e6e6fa",
229
+ "lavenderblush": "#fff0f5",
230
+ "lawngreen": "#7cfc00",
231
+ "lemonchiffon": "#fffacd",
232
+ "lightblue": "#add8e6",
233
+ "lightcoral": "#f08080",
234
+ "lightcyan": "#e0ffff",
235
+ "lightgoldenrodyellow": "#fafad2",
236
+ "lightgreen": "#90ee90",
237
+ "lightgray": "#d3d3d3",
238
+ "lightgrey": "#d3d3d3",
239
+ "lightpink": "#ffb6c1",
240
+ "lightsalmon": "#ffa07a",
241
+ "lightseagreen": "#20b2aa",
242
+ "lightskyblue": "#87cefa",
243
+ "lightslategray": "#778899",
244
+ "lightslategrey": "#778899",
245
+ "lightsteelblue": "#b0c4de",
246
+ "lightyellow": "#ffffe0",
247
+ "lime": "#00ff00",
248
+ "limegreen": "#32cd32",
249
+ "linen": "#faf0e6",
250
+ "magenta": "#ff00ff",
251
+ "maroon": "#800000",
252
+ "mediumaquamarine": "#66cdaa",
253
+ "mediumblue": "#0000cd",
254
+ "mediumorchid": "#ba55d3",
255
+ "mediumpurple": "#9370db",
256
+ "mediumseagreen": "#3cb371",
257
+ "mediumslateblue": "#7b68ee",
258
+ "mediumspringgreen": "#00fa9a",
259
+ "mediumturquoise": "#48d1cc",
260
+ "mediumvioletred": "#c71585",
261
+ "midnightblue": "#191970",
262
+ "mintcream": "#f5fffa",
263
+ "mistyrose": "#ffe4e1",
264
+ "moccasin": "#ffe4b5",
265
+ "navajowhite": "#ffdead",
266
+ "navy": "#000080",
267
+ "oldlace": "#fdf5e6",
268
+ "olive": "#808000",
269
+ "olivedrab": "#6b8e23",
270
+ "orange": "#ffa500",
271
+ "orangered": "#ff4500",
272
+ "orchid": "#da70d6",
273
+ "palegoldenrod": "#eee8aa",
274
+ "palegreen": "#98fb98",
275
+ "paleturquoise": "#afeeee",
276
+ "palevioletred": "#db7093",
277
+ "papayawhip": "#ffefd5",
278
+ "peachpuff": "#ffdab9",
279
+ "peru": "#cd853f",
280
+ "pink": "#ffc0cb",
281
+ "plum": "#dda0dd",
282
+ "powderblue": "#b0e0e6",
283
+ "purple": "#800080",
284
+ "rebeccapurple": "#663399",
285
+ "red": "#ff0000",
286
+ "rosybrown": "#bc8f8f",
287
+ "royalblue": "#4169e1",
288
+ "saddlebrown": "#8b4513",
289
+ "salmon": "#fa8072",
290
+ "sandybrown": "#f4a460",
291
+ "seagreen": "#2e8b57",
292
+ "seashell": "#fff5ee",
293
+ "sienna": "#a0522d",
294
+ "silver": "#c0c0c0",
295
+ "skyblue": "#87ceeb",
296
+ "slateblue": "#6a5acd",
297
+ "slategray": "#708090",
298
+ "slategrey": "#708090",
299
+ "snow": "#fffafa",
300
+ "springgreen": "#00ff7f",
301
+ "steelblue": "#4682b4",
302
+ "tan": "#d2b48c",
303
+ "teal": "#008080",
304
+ "thistle": "#d8bfd8",
305
+ "tomato": "#ff6347",
306
+ "turquoise": "#40e0d0",
307
+ "violet": "#ee82ee",
308
+ "wheat": "#f5deb3",
309
+ "white": "#ffffff",
310
+ "whitesmoke": "#f5f5f5",
311
+ "yellow": "#ffff00",
312
+ "yellowgreen": "#9acd32",
313
+ }
Lib/site-packages/PIL/ImageDraw.py ADDED
@@ -0,0 +1,1038 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # drawing interface operations
6
+ #
7
+ # History:
8
+ # 1996-04-13 fl Created (experimental)
9
+ # 1996-08-07 fl Filled polygons, ellipses.
10
+ # 1996-08-13 fl Added text support
11
+ # 1998-06-28 fl Handle I and F images
12
+ # 1998-12-29 fl Added arc; use arc primitive to draw ellipses
13
+ # 1999-01-10 fl Added shape stuff (experimental)
14
+ # 1999-02-06 fl Added bitmap support
15
+ # 1999-02-11 fl Changed all primitives to take options
16
+ # 1999-02-20 fl Fixed backwards compatibility
17
+ # 2000-10-12 fl Copy on write, when necessary
18
+ # 2001-02-18 fl Use default ink for bitmap/text also in fill mode
19
+ # 2002-10-24 fl Added support for CSS-style color strings
20
+ # 2002-12-10 fl Added experimental support for RGBA-on-RGB drawing
21
+ # 2002-12-11 fl Refactored low-level drawing API (work in progress)
22
+ # 2004-08-26 fl Made Draw() a factory function, added getdraw() support
23
+ # 2004-09-04 fl Added width support to line primitive
24
+ # 2004-09-10 fl Added font mode handling
25
+ # 2006-06-19 fl Added font bearing support (getmask2)
26
+ #
27
+ # Copyright (c) 1997-2006 by Secret Labs AB
28
+ # Copyright (c) 1996-2006 by Fredrik Lundh
29
+ #
30
+ # See the README file for information on usage and redistribution.
31
+ #
32
+
33
+ import math
34
+ import numbers
35
+
36
+ from . import Image, ImageColor
37
+
38
+ """
39
+ A simple 2D drawing interface for PIL images.
40
+ <p>
41
+ Application code should use the <b>Draw</b> factory, instead of
42
+ directly.
43
+ """
44
+
45
+
46
+ class ImageDraw:
47
+ font = None
48
+
49
+ def __init__(self, im, mode=None):
50
+ """
51
+ Create a drawing instance.
52
+
53
+ :param im: The image to draw in.
54
+ :param mode: Optional mode to use for color values. For RGB
55
+ images, this argument can be RGB or RGBA (to blend the
56
+ drawing into the image). For all other modes, this argument
57
+ must be the same as the image mode. If omitted, the mode
58
+ defaults to the mode of the image.
59
+ """
60
+ im.load()
61
+ if im.readonly:
62
+ im._copy() # make it writeable
63
+ blend = 0
64
+ if mode is None:
65
+ mode = im.mode
66
+ if mode != im.mode:
67
+ if mode == "RGBA" and im.mode == "RGB":
68
+ blend = 1
69
+ else:
70
+ msg = "mode mismatch"
71
+ raise ValueError(msg)
72
+ if mode == "P":
73
+ self.palette = im.palette
74
+ else:
75
+ self.palette = None
76
+ self._image = im
77
+ self.im = im.im
78
+ self.draw = Image.core.draw(self.im, blend)
79
+ self.mode = mode
80
+ if mode in ("I", "F"):
81
+ self.ink = self.draw.draw_ink(1)
82
+ else:
83
+ self.ink = self.draw.draw_ink(-1)
84
+ if mode in ("1", "P", "I", "F"):
85
+ # FIXME: fix Fill2 to properly support matte for I+F images
86
+ self.fontmode = "1"
87
+ else:
88
+ self.fontmode = "L" # aliasing is okay for other modes
89
+ self.fill = False
90
+
91
+ def getfont(self):
92
+ """
93
+ Get the current default font.
94
+
95
+ To set the default font for this ImageDraw instance::
96
+
97
+ from PIL import ImageDraw, ImageFont
98
+ draw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf")
99
+
100
+ To set the default font for all future ImageDraw instances::
101
+
102
+ from PIL import ImageDraw, ImageFont
103
+ ImageDraw.ImageDraw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf")
104
+
105
+ If the current default font is ``None``,
106
+ it is initialized with ``ImageFont.load_default()``.
107
+
108
+ :returns: An image font."""
109
+ if not self.font:
110
+ # FIXME: should add a font repository
111
+ from . import ImageFont
112
+
113
+ self.font = ImageFont.load_default()
114
+ return self.font
115
+
116
+ def _getink(self, ink, fill=None):
117
+ if ink is None and fill is None:
118
+ if self.fill:
119
+ fill = self.ink
120
+ else:
121
+ ink = self.ink
122
+ else:
123
+ if ink is not None:
124
+ if isinstance(ink, str):
125
+ ink = ImageColor.getcolor(ink, self.mode)
126
+ if self.palette and not isinstance(ink, numbers.Number):
127
+ ink = self.palette.getcolor(ink, self._image)
128
+ ink = self.draw.draw_ink(ink)
129
+ if fill is not None:
130
+ if isinstance(fill, str):
131
+ fill = ImageColor.getcolor(fill, self.mode)
132
+ if self.palette and not isinstance(fill, numbers.Number):
133
+ fill = self.palette.getcolor(fill, self._image)
134
+ fill = self.draw.draw_ink(fill)
135
+ return ink, fill
136
+
137
+ def arc(self, xy, start, end, fill=None, width=1):
138
+ """Draw an arc."""
139
+ ink, fill = self._getink(fill)
140
+ if ink is not None:
141
+ self.draw.draw_arc(xy, start, end, ink, width)
142
+
143
+ def bitmap(self, xy, bitmap, fill=None):
144
+ """Draw a bitmap."""
145
+ bitmap.load()
146
+ ink, fill = self._getink(fill)
147
+ if ink is None:
148
+ ink = fill
149
+ if ink is not None:
150
+ self.draw.draw_bitmap(xy, bitmap.im, ink)
151
+
152
+ def chord(self, xy, start, end, fill=None, outline=None, width=1):
153
+ """Draw a chord."""
154
+ ink, fill = self._getink(outline, fill)
155
+ if fill is not None:
156
+ self.draw.draw_chord(xy, start, end, fill, 1)
157
+ if ink is not None and ink != fill and width != 0:
158
+ self.draw.draw_chord(xy, start, end, ink, 0, width)
159
+
160
+ def ellipse(self, xy, fill=None, outline=None, width=1):
161
+ """Draw an ellipse."""
162
+ ink, fill = self._getink(outline, fill)
163
+ if fill is not None:
164
+ self.draw.draw_ellipse(xy, fill, 1)
165
+ if ink is not None and ink != fill and width != 0:
166
+ self.draw.draw_ellipse(xy, ink, 0, width)
167
+
168
+ def line(self, xy, fill=None, width=0, joint=None):
169
+ """Draw a line, or a connected sequence of line segments."""
170
+ ink = self._getink(fill)[0]
171
+ if ink is not None:
172
+ self.draw.draw_lines(xy, ink, width)
173
+ if joint == "curve" and width > 4:
174
+ if not isinstance(xy[0], (list, tuple)):
175
+ xy = [tuple(xy[i : i + 2]) for i in range(0, len(xy), 2)]
176
+ for i in range(1, len(xy) - 1):
177
+ point = xy[i]
178
+ angles = [
179
+ math.degrees(math.atan2(end[0] - start[0], start[1] - end[1]))
180
+ % 360
181
+ for start, end in ((xy[i - 1], point), (point, xy[i + 1]))
182
+ ]
183
+ if angles[0] == angles[1]:
184
+ # This is a straight line, so no joint is required
185
+ continue
186
+
187
+ def coord_at_angle(coord, angle):
188
+ x, y = coord
189
+ angle -= 90
190
+ distance = width / 2 - 1
191
+ return tuple(
192
+ p + (math.floor(p_d) if p_d > 0 else math.ceil(p_d))
193
+ for p, p_d in (
194
+ (x, distance * math.cos(math.radians(angle))),
195
+ (y, distance * math.sin(math.radians(angle))),
196
+ )
197
+ )
198
+
199
+ flipped = (
200
+ angles[1] > angles[0] and angles[1] - 180 > angles[0]
201
+ ) or (angles[1] < angles[0] and angles[1] + 180 > angles[0])
202
+ coords = [
203
+ (point[0] - width / 2 + 1, point[1] - width / 2 + 1),
204
+ (point[0] + width / 2 - 1, point[1] + width / 2 - 1),
205
+ ]
206
+ if flipped:
207
+ start, end = (angles[1] + 90, angles[0] + 90)
208
+ else:
209
+ start, end = (angles[0] - 90, angles[1] - 90)
210
+ self.pieslice(coords, start - 90, end - 90, fill)
211
+
212
+ if width > 8:
213
+ # Cover potential gaps between the line and the joint
214
+ if flipped:
215
+ gap_coords = [
216
+ coord_at_angle(point, angles[0] + 90),
217
+ point,
218
+ coord_at_angle(point, angles[1] + 90),
219
+ ]
220
+ else:
221
+ gap_coords = [
222
+ coord_at_angle(point, angles[0] - 90),
223
+ point,
224
+ coord_at_angle(point, angles[1] - 90),
225
+ ]
226
+ self.line(gap_coords, fill, width=3)
227
+
228
+ def shape(self, shape, fill=None, outline=None):
229
+ """(Experimental) Draw a shape."""
230
+ shape.close()
231
+ ink, fill = self._getink(outline, fill)
232
+ if fill is not None:
233
+ self.draw.draw_outline(shape, fill, 1)
234
+ if ink is not None and ink != fill:
235
+ self.draw.draw_outline(shape, ink, 0)
236
+
237
+ def pieslice(self, xy, start, end, fill=None, outline=None, width=1):
238
+ """Draw a pieslice."""
239
+ ink, fill = self._getink(outline, fill)
240
+ if fill is not None:
241
+ self.draw.draw_pieslice(xy, start, end, fill, 1)
242
+ if ink is not None and ink != fill and width != 0:
243
+ self.draw.draw_pieslice(xy, start, end, ink, 0, width)
244
+
245
+ def point(self, xy, fill=None):
246
+ """Draw one or more individual pixels."""
247
+ ink, fill = self._getink(fill)
248
+ if ink is not None:
249
+ self.draw.draw_points(xy, ink)
250
+
251
+ def polygon(self, xy, fill=None, outline=None, width=1):
252
+ """Draw a polygon."""
253
+ ink, fill = self._getink(outline, fill)
254
+ if fill is not None:
255
+ self.draw.draw_polygon(xy, fill, 1)
256
+ if ink is not None and ink != fill and width != 0:
257
+ if width == 1:
258
+ self.draw.draw_polygon(xy, ink, 0, width)
259
+ else:
260
+ # To avoid expanding the polygon outwards,
261
+ # use the fill as a mask
262
+ mask = Image.new("1", self.im.size)
263
+ mask_ink = self._getink(1)[0]
264
+
265
+ fill_im = mask.copy()
266
+ draw = Draw(fill_im)
267
+ draw.draw.draw_polygon(xy, mask_ink, 1)
268
+
269
+ ink_im = mask.copy()
270
+ draw = Draw(ink_im)
271
+ width = width * 2 - 1
272
+ draw.draw.draw_polygon(xy, mask_ink, 0, width)
273
+
274
+ mask.paste(ink_im, mask=fill_im)
275
+
276
+ im = Image.new(self.mode, self.im.size)
277
+ draw = Draw(im)
278
+ draw.draw.draw_polygon(xy, ink, 0, width)
279
+ self.im.paste(im.im, (0, 0) + im.size, mask.im)
280
+
281
+ def regular_polygon(
282
+ self, bounding_circle, n_sides, rotation=0, fill=None, outline=None, width=1
283
+ ):
284
+ """Draw a regular polygon."""
285
+ xy = _compute_regular_polygon_vertices(bounding_circle, n_sides, rotation)
286
+ self.polygon(xy, fill, outline, width)
287
+
288
+ def rectangle(self, xy, fill=None, outline=None, width=1):
289
+ """Draw a rectangle."""
290
+ ink, fill = self._getink(outline, fill)
291
+ if fill is not None:
292
+ self.draw.draw_rectangle(xy, fill, 1)
293
+ if ink is not None and ink != fill and width != 0:
294
+ self.draw.draw_rectangle(xy, ink, 0, width)
295
+
296
+ def rounded_rectangle(
297
+ self, xy, radius=0, fill=None, outline=None, width=1, *, corners=None
298
+ ):
299
+ """Draw a rounded rectangle."""
300
+ if isinstance(xy[0], (list, tuple)):
301
+ (x0, y0), (x1, y1) = xy
302
+ else:
303
+ x0, y0, x1, y1 = xy
304
+ if x1 < x0:
305
+ msg = "x1 must be greater than or equal to x0"
306
+ raise ValueError(msg)
307
+ if y1 < y0:
308
+ msg = "y1 must be greater than or equal to y0"
309
+ raise ValueError(msg)
310
+ if corners is None:
311
+ corners = (True, True, True, True)
312
+
313
+ d = radius * 2
314
+
315
+ full_x, full_y = False, False
316
+ if all(corners):
317
+ full_x = d >= x1 - x0 - 1
318
+ if full_x:
319
+ # The two left and two right corners are joined
320
+ d = x1 - x0
321
+ full_y = d >= y1 - y0 - 1
322
+ if full_y:
323
+ # The two top and two bottom corners are joined
324
+ d = y1 - y0
325
+ if full_x and full_y:
326
+ # If all corners are joined, that is a circle
327
+ return self.ellipse(xy, fill, outline, width)
328
+
329
+ if d == 0 or not any(corners):
330
+ # If the corners have no curve,
331
+ # or there are no corners,
332
+ # that is a rectangle
333
+ return self.rectangle(xy, fill, outline, width)
334
+
335
+ r = d // 2
336
+ ink, fill = self._getink(outline, fill)
337
+
338
+ def draw_corners(pieslice):
339
+ if full_x:
340
+ # Draw top and bottom halves
341
+ parts = (
342
+ ((x0, y0, x0 + d, y0 + d), 180, 360),
343
+ ((x0, y1 - d, x0 + d, y1), 0, 180),
344
+ )
345
+ elif full_y:
346
+ # Draw left and right halves
347
+ parts = (
348
+ ((x0, y0, x0 + d, y0 + d), 90, 270),
349
+ ((x1 - d, y0, x1, y0 + d), 270, 90),
350
+ )
351
+ else:
352
+ # Draw four separate corners
353
+ parts = []
354
+ for i, part in enumerate(
355
+ (
356
+ ((x0, y0, x0 + d, y0 + d), 180, 270),
357
+ ((x1 - d, y0, x1, y0 + d), 270, 360),
358
+ ((x1 - d, y1 - d, x1, y1), 0, 90),
359
+ ((x0, y1 - d, x0 + d, y1), 90, 180),
360
+ )
361
+ ):
362
+ if corners[i]:
363
+ parts.append(part)
364
+ for part in parts:
365
+ if pieslice:
366
+ self.draw.draw_pieslice(*(part + (fill, 1)))
367
+ else:
368
+ self.draw.draw_arc(*(part + (ink, width)))
369
+
370
+ if fill is not None:
371
+ draw_corners(True)
372
+
373
+ if full_x:
374
+ self.draw.draw_rectangle((x0, y0 + r + 1, x1, y1 - r - 1), fill, 1)
375
+ else:
376
+ self.draw.draw_rectangle((x0 + r + 1, y0, x1 - r - 1, y1), fill, 1)
377
+ if not full_x and not full_y:
378
+ left = [x0, y0, x0 + r, y1]
379
+ if corners[0]:
380
+ left[1] += r + 1
381
+ if corners[3]:
382
+ left[3] -= r + 1
383
+ self.draw.draw_rectangle(left, fill, 1)
384
+
385
+ right = [x1 - r, y0, x1, y1]
386
+ if corners[1]:
387
+ right[1] += r + 1
388
+ if corners[2]:
389
+ right[3] -= r + 1
390
+ self.draw.draw_rectangle(right, fill, 1)
391
+ if ink is not None and ink != fill and width != 0:
392
+ draw_corners(False)
393
+
394
+ if not full_x:
395
+ top = [x0, y0, x1, y0 + width - 1]
396
+ if corners[0]:
397
+ top[0] += r + 1
398
+ if corners[1]:
399
+ top[2] -= r + 1
400
+ self.draw.draw_rectangle(top, ink, 1)
401
+
402
+ bottom = [x0, y1 - width + 1, x1, y1]
403
+ if corners[3]:
404
+ bottom[0] += r + 1
405
+ if corners[2]:
406
+ bottom[2] -= r + 1
407
+ self.draw.draw_rectangle(bottom, ink, 1)
408
+ if not full_y:
409
+ left = [x0, y0, x0 + width - 1, y1]
410
+ if corners[0]:
411
+ left[1] += r + 1
412
+ if corners[3]:
413
+ left[3] -= r + 1
414
+ self.draw.draw_rectangle(left, ink, 1)
415
+
416
+ right = [x1 - width + 1, y0, x1, y1]
417
+ if corners[1]:
418
+ right[1] += r + 1
419
+ if corners[2]:
420
+ right[3] -= r + 1
421
+ self.draw.draw_rectangle(right, ink, 1)
422
+
423
+ def _multiline_check(self, text):
424
+ split_character = "\n" if isinstance(text, str) else b"\n"
425
+
426
+ return split_character in text
427
+
428
+ def _multiline_split(self, text):
429
+ split_character = "\n" if isinstance(text, str) else b"\n"
430
+
431
+ return text.split(split_character)
432
+
433
+ def _multiline_spacing(self, font, spacing, stroke_width):
434
+ return (
435
+ self.textbbox((0, 0), "A", font, stroke_width=stroke_width)[3]
436
+ + stroke_width
437
+ + spacing
438
+ )
439
+
440
+ def text(
441
+ self,
442
+ xy,
443
+ text,
444
+ fill=None,
445
+ font=None,
446
+ anchor=None,
447
+ spacing=4,
448
+ align="left",
449
+ direction=None,
450
+ features=None,
451
+ language=None,
452
+ stroke_width=0,
453
+ stroke_fill=None,
454
+ embedded_color=False,
455
+ *args,
456
+ **kwargs,
457
+ ):
458
+ """Draw text."""
459
+ if self._multiline_check(text):
460
+ return self.multiline_text(
461
+ xy,
462
+ text,
463
+ fill,
464
+ font,
465
+ anchor,
466
+ spacing,
467
+ align,
468
+ direction,
469
+ features,
470
+ language,
471
+ stroke_width,
472
+ stroke_fill,
473
+ embedded_color,
474
+ )
475
+
476
+ if embedded_color and self.mode not in ("RGB", "RGBA"):
477
+ msg = "Embedded color supported only in RGB and RGBA modes"
478
+ raise ValueError(msg)
479
+
480
+ if font is None:
481
+ font = self.getfont()
482
+
483
+ def getink(fill):
484
+ ink, fill = self._getink(fill)
485
+ if ink is None:
486
+ return fill
487
+ return ink
488
+
489
+ def draw_text(ink, stroke_width=0, stroke_offset=None):
490
+ mode = self.fontmode
491
+ if stroke_width == 0 and embedded_color:
492
+ mode = "RGBA"
493
+ coord = []
494
+ start = []
495
+ for i in range(2):
496
+ coord.append(int(xy[i]))
497
+ start.append(math.modf(xy[i])[0])
498
+ try:
499
+ mask, offset = font.getmask2(
500
+ text,
501
+ mode,
502
+ direction=direction,
503
+ features=features,
504
+ language=language,
505
+ stroke_width=stroke_width,
506
+ anchor=anchor,
507
+ ink=ink,
508
+ start=start,
509
+ *args,
510
+ **kwargs,
511
+ )
512
+ coord = coord[0] + offset[0], coord[1] + offset[1]
513
+ except AttributeError:
514
+ try:
515
+ mask = font.getmask(
516
+ text,
517
+ mode,
518
+ direction,
519
+ features,
520
+ language,
521
+ stroke_width,
522
+ anchor,
523
+ ink,
524
+ start=start,
525
+ *args,
526
+ **kwargs,
527
+ )
528
+ except TypeError:
529
+ mask = font.getmask(text)
530
+ if stroke_offset:
531
+ coord = coord[0] + stroke_offset[0], coord[1] + stroke_offset[1]
532
+ if mode == "RGBA":
533
+ # font.getmask2(mode="RGBA") returns color in RGB bands and mask in A
534
+ # extract mask and set text alpha
535
+ color, mask = mask, mask.getband(3)
536
+ color.fillband(3, (ink >> 24) & 0xFF)
537
+ x, y = coord
538
+ self.im.paste(color, (x, y, x + mask.size[0], y + mask.size[1]), mask)
539
+ else:
540
+ self.draw.draw_bitmap(coord, mask, ink)
541
+
542
+ ink = getink(fill)
543
+ if ink is not None:
544
+ stroke_ink = None
545
+ if stroke_width:
546
+ stroke_ink = getink(stroke_fill) if stroke_fill is not None else ink
547
+
548
+ if stroke_ink is not None:
549
+ # Draw stroked text
550
+ draw_text(stroke_ink, stroke_width)
551
+
552
+ # Draw normal text
553
+ draw_text(ink, 0)
554
+ else:
555
+ # Only draw normal text
556
+ draw_text(ink)
557
+
558
+ def multiline_text(
559
+ self,
560
+ xy,
561
+ text,
562
+ fill=None,
563
+ font=None,
564
+ anchor=None,
565
+ spacing=4,
566
+ align="left",
567
+ direction=None,
568
+ features=None,
569
+ language=None,
570
+ stroke_width=0,
571
+ stroke_fill=None,
572
+ embedded_color=False,
573
+ ):
574
+ if direction == "ttb":
575
+ msg = "ttb direction is unsupported for multiline text"
576
+ raise ValueError(msg)
577
+
578
+ if anchor is None:
579
+ anchor = "la"
580
+ elif len(anchor) != 2:
581
+ msg = "anchor must be a 2 character string"
582
+ raise ValueError(msg)
583
+ elif anchor[1] in "tb":
584
+ msg = "anchor not supported for multiline text"
585
+ raise ValueError(msg)
586
+
587
+ widths = []
588
+ max_width = 0
589
+ lines = self._multiline_split(text)
590
+ line_spacing = self._multiline_spacing(font, spacing, stroke_width)
591
+ for line in lines:
592
+ line_width = self.textlength(
593
+ line, font, direction=direction, features=features, language=language
594
+ )
595
+ widths.append(line_width)
596
+ max_width = max(max_width, line_width)
597
+
598
+ top = xy[1]
599
+ if anchor[1] == "m":
600
+ top -= (len(lines) - 1) * line_spacing / 2.0
601
+ elif anchor[1] == "d":
602
+ top -= (len(lines) - 1) * line_spacing
603
+
604
+ for idx, line in enumerate(lines):
605
+ left = xy[0]
606
+ width_difference = max_width - widths[idx]
607
+
608
+ # first align left by anchor
609
+ if anchor[0] == "m":
610
+ left -= width_difference / 2.0
611
+ elif anchor[0] == "r":
612
+ left -= width_difference
613
+
614
+ # then align by align parameter
615
+ if align == "left":
616
+ pass
617
+ elif align == "center":
618
+ left += width_difference / 2.0
619
+ elif align == "right":
620
+ left += width_difference
621
+ else:
622
+ msg = 'align must be "left", "center" or "right"'
623
+ raise ValueError(msg)
624
+
625
+ self.text(
626
+ (left, top),
627
+ line,
628
+ fill,
629
+ font,
630
+ anchor,
631
+ direction=direction,
632
+ features=features,
633
+ language=language,
634
+ stroke_width=stroke_width,
635
+ stroke_fill=stroke_fill,
636
+ embedded_color=embedded_color,
637
+ )
638
+ top += line_spacing
639
+
640
+ def textlength(
641
+ self,
642
+ text,
643
+ font=None,
644
+ direction=None,
645
+ features=None,
646
+ language=None,
647
+ embedded_color=False,
648
+ ):
649
+ """Get the length of a given string, in pixels with 1/64 precision."""
650
+ if self._multiline_check(text):
651
+ msg = "can't measure length of multiline text"
652
+ raise ValueError(msg)
653
+ if embedded_color and self.mode not in ("RGB", "RGBA"):
654
+ msg = "Embedded color supported only in RGB and RGBA modes"
655
+ raise ValueError(msg)
656
+
657
+ if font is None:
658
+ font = self.getfont()
659
+ mode = "RGBA" if embedded_color else self.fontmode
660
+ return font.getlength(text, mode, direction, features, language)
661
+
662
+ def textbbox(
663
+ self,
664
+ xy,
665
+ text,
666
+ font=None,
667
+ anchor=None,
668
+ spacing=4,
669
+ align="left",
670
+ direction=None,
671
+ features=None,
672
+ language=None,
673
+ stroke_width=0,
674
+ embedded_color=False,
675
+ ):
676
+ """Get the bounding box of a given string, in pixels."""
677
+ if embedded_color and self.mode not in ("RGB", "RGBA"):
678
+ msg = "Embedded color supported only in RGB and RGBA modes"
679
+ raise ValueError(msg)
680
+
681
+ if self._multiline_check(text):
682
+ return self.multiline_textbbox(
683
+ xy,
684
+ text,
685
+ font,
686
+ anchor,
687
+ spacing,
688
+ align,
689
+ direction,
690
+ features,
691
+ language,
692
+ stroke_width,
693
+ embedded_color,
694
+ )
695
+
696
+ if font is None:
697
+ font = self.getfont()
698
+ mode = "RGBA" if embedded_color else self.fontmode
699
+ bbox = font.getbbox(
700
+ text, mode, direction, features, language, stroke_width, anchor
701
+ )
702
+ return bbox[0] + xy[0], bbox[1] + xy[1], bbox[2] + xy[0], bbox[3] + xy[1]
703
+
704
+ def multiline_textbbox(
705
+ self,
706
+ xy,
707
+ text,
708
+ font=None,
709
+ anchor=None,
710
+ spacing=4,
711
+ align="left",
712
+ direction=None,
713
+ features=None,
714
+ language=None,
715
+ stroke_width=0,
716
+ embedded_color=False,
717
+ ):
718
+ if direction == "ttb":
719
+ msg = "ttb direction is unsupported for multiline text"
720
+ raise ValueError(msg)
721
+
722
+ if anchor is None:
723
+ anchor = "la"
724
+ elif len(anchor) != 2:
725
+ msg = "anchor must be a 2 character string"
726
+ raise ValueError(msg)
727
+ elif anchor[1] in "tb":
728
+ msg = "anchor not supported for multiline text"
729
+ raise ValueError(msg)
730
+
731
+ widths = []
732
+ max_width = 0
733
+ lines = self._multiline_split(text)
734
+ line_spacing = self._multiline_spacing(font, spacing, stroke_width)
735
+ for line in lines:
736
+ line_width = self.textlength(
737
+ line,
738
+ font,
739
+ direction=direction,
740
+ features=features,
741
+ language=language,
742
+ embedded_color=embedded_color,
743
+ )
744
+ widths.append(line_width)
745
+ max_width = max(max_width, line_width)
746
+
747
+ top = xy[1]
748
+ if anchor[1] == "m":
749
+ top -= (len(lines) - 1) * line_spacing / 2.0
750
+ elif anchor[1] == "d":
751
+ top -= (len(lines) - 1) * line_spacing
752
+
753
+ bbox = None
754
+
755
+ for idx, line in enumerate(lines):
756
+ left = xy[0]
757
+ width_difference = max_width - widths[idx]
758
+
759
+ # first align left by anchor
760
+ if anchor[0] == "m":
761
+ left -= width_difference / 2.0
762
+ elif anchor[0] == "r":
763
+ left -= width_difference
764
+
765
+ # then align by align parameter
766
+ if align == "left":
767
+ pass
768
+ elif align == "center":
769
+ left += width_difference / 2.0
770
+ elif align == "right":
771
+ left += width_difference
772
+ else:
773
+ msg = 'align must be "left", "center" or "right"'
774
+ raise ValueError(msg)
775
+
776
+ bbox_line = self.textbbox(
777
+ (left, top),
778
+ line,
779
+ font,
780
+ anchor,
781
+ direction=direction,
782
+ features=features,
783
+ language=language,
784
+ stroke_width=stroke_width,
785
+ embedded_color=embedded_color,
786
+ )
787
+ if bbox is None:
788
+ bbox = bbox_line
789
+ else:
790
+ bbox = (
791
+ min(bbox[0], bbox_line[0]),
792
+ min(bbox[1], bbox_line[1]),
793
+ max(bbox[2], bbox_line[2]),
794
+ max(bbox[3], bbox_line[3]),
795
+ )
796
+
797
+ top += line_spacing
798
+
799
+ if bbox is None:
800
+ return xy[0], xy[1], xy[0], xy[1]
801
+ return bbox
802
+
803
+
804
+ def Draw(im, mode=None):
805
+ """
806
+ A simple 2D drawing interface for PIL images.
807
+
808
+ :param im: The image to draw in.
809
+ :param mode: Optional mode to use for color values. For RGB
810
+ images, this argument can be RGB or RGBA (to blend the
811
+ drawing into the image). For all other modes, this argument
812
+ must be the same as the image mode. If omitted, the mode
813
+ defaults to the mode of the image.
814
+ """
815
+ try:
816
+ return im.getdraw(mode)
817
+ except AttributeError:
818
+ return ImageDraw(im, mode)
819
+
820
+
821
+ # experimental access to the outline API
822
+ try:
823
+ Outline = Image.core.outline
824
+ except AttributeError:
825
+ Outline = None
826
+
827
+
828
+ def getdraw(im=None, hints=None):
829
+ """
830
+ (Experimental) A more advanced 2D drawing interface for PIL images,
831
+ based on the WCK interface.
832
+
833
+ :param im: The image to draw in.
834
+ :param hints: An optional list of hints.
835
+ :returns: A (drawing context, drawing resource factory) tuple.
836
+ """
837
+ # FIXME: this needs more work!
838
+ # FIXME: come up with a better 'hints' scheme.
839
+ handler = None
840
+ if not hints or "nicest" in hints:
841
+ try:
842
+ from . import _imagingagg as handler
843
+ except ImportError:
844
+ pass
845
+ if handler is None:
846
+ from . import ImageDraw2 as handler
847
+ if im:
848
+ im = handler.Draw(im)
849
+ return im, handler
850
+
851
+
852
+ def floodfill(image, xy, value, border=None, thresh=0):
853
+ """
854
+ (experimental) Fills a bounded region with a given color.
855
+
856
+ :param image: Target image.
857
+ :param xy: Seed position (a 2-item coordinate tuple). See
858
+ :ref:`coordinate-system`.
859
+ :param value: Fill color.
860
+ :param border: Optional border value. If given, the region consists of
861
+ pixels with a color different from the border color. If not given,
862
+ the region consists of pixels having the same color as the seed
863
+ pixel.
864
+ :param thresh: Optional threshold value which specifies a maximum
865
+ tolerable difference of a pixel value from the 'background' in
866
+ order for it to be replaced. Useful for filling regions of
867
+ non-homogeneous, but similar, colors.
868
+ """
869
+ # based on an implementation by Eric S. Raymond
870
+ # amended by yo1995 @20180806
871
+ pixel = image.load()
872
+ x, y = xy
873
+ try:
874
+ background = pixel[x, y]
875
+ if _color_diff(value, background) <= thresh:
876
+ return # seed point already has fill color
877
+ pixel[x, y] = value
878
+ except (ValueError, IndexError):
879
+ return # seed point outside image
880
+ edge = {(x, y)}
881
+ # use a set to keep record of current and previous edge pixels
882
+ # to reduce memory consumption
883
+ full_edge = set()
884
+ while edge:
885
+ new_edge = set()
886
+ for x, y in edge: # 4 adjacent method
887
+ for s, t in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
888
+ # If already processed, or if a coordinate is negative, skip
889
+ if (s, t) in full_edge or s < 0 or t < 0:
890
+ continue
891
+ try:
892
+ p = pixel[s, t]
893
+ except (ValueError, IndexError):
894
+ pass
895
+ else:
896
+ full_edge.add((s, t))
897
+ if border is None:
898
+ fill = _color_diff(p, background) <= thresh
899
+ else:
900
+ fill = p != value and p != border
901
+ if fill:
902
+ pixel[s, t] = value
903
+ new_edge.add((s, t))
904
+ full_edge = edge # discard pixels processed
905
+ edge = new_edge
906
+
907
+
908
+ def _compute_regular_polygon_vertices(bounding_circle, n_sides, rotation):
909
+ """
910
+ Generate a list of vertices for a 2D regular polygon.
911
+
912
+ :param bounding_circle: The bounding circle is a tuple defined
913
+ by a point and radius. The polygon is inscribed in this circle.
914
+ (e.g. ``bounding_circle=(x, y, r)`` or ``((x, y), r)``)
915
+ :param n_sides: Number of sides
916
+ (e.g. ``n_sides=3`` for a triangle, ``6`` for a hexagon)
917
+ :param rotation: Apply an arbitrary rotation to the polygon
918
+ (e.g. ``rotation=90``, applies a 90 degree rotation)
919
+ :return: List of regular polygon vertices
920
+ (e.g. ``[(25, 50), (50, 50), (50, 25), (25, 25)]``)
921
+
922
+ How are the vertices computed?
923
+ 1. Compute the following variables
924
+ - theta: Angle between the apothem & the nearest polygon vertex
925
+ - side_length: Length of each polygon edge
926
+ - centroid: Center of bounding circle (1st, 2nd elements of bounding_circle)
927
+ - polygon_radius: Polygon radius (last element of bounding_circle)
928
+ - angles: Location of each polygon vertex in polar grid
929
+ (e.g. A square with 0 degree rotation => [225.0, 315.0, 45.0, 135.0])
930
+
931
+ 2. For each angle in angles, get the polygon vertex at that angle
932
+ The vertex is computed using the equation below.
933
+ X= xcos(φ) + ysin(φ)
934
+ Y= −xsin(φ) + ycos(φ)
935
+
936
+ Note:
937
+ φ = angle in degrees
938
+ x = 0
939
+ y = polygon_radius
940
+
941
+ The formula above assumes rotation around the origin.
942
+ In our case, we are rotating around the centroid.
943
+ To account for this, we use the formula below
944
+ X = xcos(φ) + ysin(φ) + centroid_x
945
+ Y = −xsin(φ) + ycos(φ) + centroid_y
946
+ """
947
+ # 1. Error Handling
948
+ # 1.1 Check `n_sides` has an appropriate value
949
+ if not isinstance(n_sides, int):
950
+ msg = "n_sides should be an int"
951
+ raise TypeError(msg)
952
+ if n_sides < 3:
953
+ msg = "n_sides should be an int > 2"
954
+ raise ValueError(msg)
955
+
956
+ # 1.2 Check `bounding_circle` has an appropriate value
957
+ if not isinstance(bounding_circle, (list, tuple)):
958
+ msg = "bounding_circle should be a tuple"
959
+ raise TypeError(msg)
960
+
961
+ if len(bounding_circle) == 3:
962
+ *centroid, polygon_radius = bounding_circle
963
+ elif len(bounding_circle) == 2:
964
+ centroid, polygon_radius = bounding_circle
965
+ else:
966
+ msg = (
967
+ "bounding_circle should contain 2D coordinates "
968
+ "and a radius (e.g. (x, y, r) or ((x, y), r) )"
969
+ )
970
+ raise ValueError(msg)
971
+
972
+ if not all(isinstance(i, (int, float)) for i in (*centroid, polygon_radius)):
973
+ msg = "bounding_circle should only contain numeric data"
974
+ raise ValueError(msg)
975
+
976
+ if not len(centroid) == 2:
977
+ msg = "bounding_circle centre should contain 2D coordinates (e.g. (x, y))"
978
+ raise ValueError(msg)
979
+
980
+ if polygon_radius <= 0:
981
+ msg = "bounding_circle radius should be > 0"
982
+ raise ValueError(msg)
983
+
984
+ # 1.3 Check `rotation` has an appropriate value
985
+ if not isinstance(rotation, (int, float)):
986
+ msg = "rotation should be an int or float"
987
+ raise ValueError(msg)
988
+
989
+ # 2. Define Helper Functions
990
+ def _apply_rotation(point, degrees, centroid):
991
+ return (
992
+ round(
993
+ point[0] * math.cos(math.radians(360 - degrees))
994
+ - point[1] * math.sin(math.radians(360 - degrees))
995
+ + centroid[0],
996
+ 2,
997
+ ),
998
+ round(
999
+ point[1] * math.cos(math.radians(360 - degrees))
1000
+ + point[0] * math.sin(math.radians(360 - degrees))
1001
+ + centroid[1],
1002
+ 2,
1003
+ ),
1004
+ )
1005
+
1006
+ def _compute_polygon_vertex(centroid, polygon_radius, angle):
1007
+ start_point = [polygon_radius, 0]
1008
+ return _apply_rotation(start_point, angle, centroid)
1009
+
1010
+ def _get_angles(n_sides, rotation):
1011
+ angles = []
1012
+ degrees = 360 / n_sides
1013
+ # Start with the bottom left polygon vertex
1014
+ current_angle = (270 - 0.5 * degrees) + rotation
1015
+ for _ in range(0, n_sides):
1016
+ angles.append(current_angle)
1017
+ current_angle += degrees
1018
+ if current_angle > 360:
1019
+ current_angle -= 360
1020
+ return angles
1021
+
1022
+ # 3. Variable Declarations
1023
+ angles = _get_angles(n_sides, rotation)
1024
+
1025
+ # 4. Compute Vertices
1026
+ return [
1027
+ _compute_polygon_vertex(centroid, polygon_radius, angle) for angle in angles
1028
+ ]
1029
+
1030
+
1031
+ def _color_diff(color1, color2):
1032
+ """
1033
+ Uses 1-norm distance to calculate difference between two values.
1034
+ """
1035
+ if isinstance(color2, tuple):
1036
+ return sum(abs(color1[i] - color2[i]) for i in range(0, len(color2)))
1037
+ else:
1038
+ return abs(color1 - color2)
Lib/site-packages/PIL/ImageDraw2.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # WCK-style drawing interface operations
6
+ #
7
+ # History:
8
+ # 2003-12-07 fl created
9
+ # 2005-05-15 fl updated; added to PIL as ImageDraw2
10
+ # 2005-05-15 fl added text support
11
+ # 2005-05-20 fl added arc/chord/pieslice support
12
+ #
13
+ # Copyright (c) 2003-2005 by Secret Labs AB
14
+ # Copyright (c) 2003-2005 by Fredrik Lundh
15
+ #
16
+ # See the README file for information on usage and redistribution.
17
+ #
18
+
19
+
20
+ """
21
+ (Experimental) WCK-style drawing interface operations
22
+
23
+ .. seealso:: :py:mod:`PIL.ImageDraw`
24
+ """
25
+
26
+
27
+ from . import Image, ImageColor, ImageDraw, ImageFont, ImagePath
28
+
29
+
30
+ class Pen:
31
+ """Stores an outline color and width."""
32
+
33
+ def __init__(self, color, width=1, opacity=255):
34
+ self.color = ImageColor.getrgb(color)
35
+ self.width = width
36
+
37
+
38
+ class Brush:
39
+ """Stores a fill color"""
40
+
41
+ def __init__(self, color, opacity=255):
42
+ self.color = ImageColor.getrgb(color)
43
+
44
+
45
+ class Font:
46
+ """Stores a TrueType font and color"""
47
+
48
+ def __init__(self, color, file, size=12):
49
+ # FIXME: add support for bitmap fonts
50
+ self.color = ImageColor.getrgb(color)
51
+ self.font = ImageFont.truetype(file, size)
52
+
53
+
54
+ class Draw:
55
+ """
56
+ (Experimental) WCK-style drawing interface
57
+ """
58
+
59
+ def __init__(self, image, size=None, color=None):
60
+ if not hasattr(image, "im"):
61
+ image = Image.new(image, size, color)
62
+ self.draw = ImageDraw.Draw(image)
63
+ self.image = image
64
+ self.transform = None
65
+
66
+ def flush(self):
67
+ return self.image
68
+
69
+ def render(self, op, xy, pen, brush=None):
70
+ # handle color arguments
71
+ outline = fill = None
72
+ width = 1
73
+ if isinstance(pen, Pen):
74
+ outline = pen.color
75
+ width = pen.width
76
+ elif isinstance(brush, Pen):
77
+ outline = brush.color
78
+ width = brush.width
79
+ if isinstance(brush, Brush):
80
+ fill = brush.color
81
+ elif isinstance(pen, Brush):
82
+ fill = pen.color
83
+ # handle transformation
84
+ if self.transform:
85
+ xy = ImagePath.Path(xy)
86
+ xy.transform(self.transform)
87
+ # render the item
88
+ if op == "line":
89
+ self.draw.line(xy, fill=outline, width=width)
90
+ else:
91
+ getattr(self.draw, op)(xy, fill=fill, outline=outline)
92
+
93
+ def settransform(self, offset):
94
+ """Sets a transformation offset."""
95
+ (xoffset, yoffset) = offset
96
+ self.transform = (1, 0, xoffset, 0, 1, yoffset)
97
+
98
+ def arc(self, xy, start, end, *options):
99
+ """
100
+ Draws an arc (a portion of a circle outline) between the start and end
101
+ angles, inside the given bounding box.
102
+
103
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.arc`
104
+ """
105
+ self.render("arc", xy, start, end, *options)
106
+
107
+ def chord(self, xy, start, end, *options):
108
+ """
109
+ Same as :py:meth:`~PIL.ImageDraw2.Draw.arc`, but connects the end points
110
+ with a straight line.
111
+
112
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.chord`
113
+ """
114
+ self.render("chord", xy, start, end, *options)
115
+
116
+ def ellipse(self, xy, *options):
117
+ """
118
+ Draws an ellipse inside the given bounding box.
119
+
120
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.ellipse`
121
+ """
122
+ self.render("ellipse", xy, *options)
123
+
124
+ def line(self, xy, *options):
125
+ """
126
+ Draws a line between the coordinates in the ``xy`` list.
127
+
128
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.line`
129
+ """
130
+ self.render("line", xy, *options)
131
+
132
+ def pieslice(self, xy, start, end, *options):
133
+ """
134
+ Same as arc, but also draws straight lines between the end points and the
135
+ center of the bounding box.
136
+
137
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.pieslice`
138
+ """
139
+ self.render("pieslice", xy, start, end, *options)
140
+
141
+ def polygon(self, xy, *options):
142
+ """
143
+ Draws a polygon.
144
+
145
+ The polygon outline consists of straight lines between the given
146
+ coordinates, plus a straight line between the last and the first
147
+ coordinate.
148
+
149
+
150
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.polygon`
151
+ """
152
+ self.render("polygon", xy, *options)
153
+
154
+ def rectangle(self, xy, *options):
155
+ """
156
+ Draws a rectangle.
157
+
158
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.rectangle`
159
+ """
160
+ self.render("rectangle", xy, *options)
161
+
162
+ def text(self, xy, text, font):
163
+ """
164
+ Draws the string at the given position.
165
+
166
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.text`
167
+ """
168
+ if self.transform:
169
+ xy = ImagePath.Path(xy)
170
+ xy.transform(self.transform)
171
+ self.draw.text(xy, text, font=font.font, fill=font.color)
172
+
173
+ def textbbox(self, xy, text, font):
174
+ """
175
+ Returns bounding box (in pixels) of given text.
176
+
177
+ :return: ``(left, top, right, bottom)`` bounding box
178
+
179
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textbbox`
180
+ """
181
+ if self.transform:
182
+ xy = ImagePath.Path(xy)
183
+ xy.transform(self.transform)
184
+ return self.draw.textbbox(xy, text, font=font.font)
185
+
186
+ def textlength(self, text, font):
187
+ """
188
+ Returns length (in pixels) of given text.
189
+ This is the amount by which following text should be offset.
190
+
191
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textlength`
192
+ """
193
+ return self.draw.textlength(text, font=font.font)
Lib/site-packages/PIL/ImageEnhance.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # image enhancement classes
6
+ #
7
+ # For a background, see "Image Processing By Interpolation and
8
+ # Extrapolation", Paul Haeberli and Douglas Voorhies. Available
9
+ # at http://www.graficaobscura.com/interp/index.html
10
+ #
11
+ # History:
12
+ # 1996-03-23 fl Created
13
+ # 2009-06-16 fl Fixed mean calculation
14
+ #
15
+ # Copyright (c) Secret Labs AB 1997.
16
+ # Copyright (c) Fredrik Lundh 1996.
17
+ #
18
+ # See the README file for information on usage and redistribution.
19
+ #
20
+
21
+ from . import Image, ImageFilter, ImageStat
22
+
23
+
24
+ class _Enhance:
25
+ def enhance(self, factor):
26
+ """
27
+ Returns an enhanced image.
28
+
29
+ :param factor: A floating point value controlling the enhancement.
30
+ Factor 1.0 always returns a copy of the original image,
31
+ lower factors mean less color (brightness, contrast,
32
+ etc), and higher values more. There are no restrictions
33
+ on this value.
34
+ :rtype: :py:class:`~PIL.Image.Image`
35
+ """
36
+ return Image.blend(self.degenerate, self.image, factor)
37
+
38
+
39
+ class Color(_Enhance):
40
+ """Adjust image color balance.
41
+
42
+ This class can be used to adjust the colour balance of an image, in
43
+ a manner similar to the controls on a colour TV set. An enhancement
44
+ factor of 0.0 gives a black and white image. A factor of 1.0 gives
45
+ the original image.
46
+ """
47
+
48
+ def __init__(self, image):
49
+ self.image = image
50
+ self.intermediate_mode = "L"
51
+ if "A" in image.getbands():
52
+ self.intermediate_mode = "LA"
53
+
54
+ self.degenerate = image.convert(self.intermediate_mode).convert(image.mode)
55
+
56
+
57
+ class Contrast(_Enhance):
58
+ """Adjust image contrast.
59
+
60
+ This class can be used to control the contrast of an image, similar
61
+ to the contrast control on a TV set. An enhancement factor of 0.0
62
+ gives a solid grey image. A factor of 1.0 gives the original image.
63
+ """
64
+
65
+ def __init__(self, image):
66
+ self.image = image
67
+ mean = int(ImageStat.Stat(image.convert("L")).mean[0] + 0.5)
68
+ self.degenerate = Image.new("L", image.size, mean).convert(image.mode)
69
+
70
+ if "A" in image.getbands():
71
+ self.degenerate.putalpha(image.getchannel("A"))
72
+
73
+
74
+ class Brightness(_Enhance):
75
+ """Adjust image brightness.
76
+
77
+ This class can be used to control the brightness of an image. An
78
+ enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the
79
+ original image.
80
+ """
81
+
82
+ def __init__(self, image):
83
+ self.image = image
84
+ self.degenerate = Image.new(image.mode, image.size, 0)
85
+
86
+ if "A" in image.getbands():
87
+ self.degenerate.putalpha(image.getchannel("A"))
88
+
89
+
90
+ class Sharpness(_Enhance):
91
+ """Adjust image sharpness.
92
+
93
+ This class can be used to adjust the sharpness of an image. An
94
+ enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the
95
+ original image, and a factor of 2.0 gives a sharpened image.
96
+ """
97
+
98
+ def __init__(self, image):
99
+ self.image = image
100
+ self.degenerate = image.filter(ImageFilter.SMOOTH)
101
+
102
+ if "A" in image.getbands():
103
+ self.degenerate.putalpha(image.getchannel("A"))
Lib/site-packages/PIL/ImageFile.py ADDED
@@ -0,0 +1,773 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # base class for image file handlers
6
+ #
7
+ # history:
8
+ # 1995-09-09 fl Created
9
+ # 1996-03-11 fl Fixed load mechanism.
10
+ # 1996-04-15 fl Added pcx/xbm decoders.
11
+ # 1996-04-30 fl Added encoders.
12
+ # 1996-12-14 fl Added load helpers
13
+ # 1997-01-11 fl Use encode_to_file where possible
14
+ # 1997-08-27 fl Flush output in _save
15
+ # 1998-03-05 fl Use memory mapping for some modes
16
+ # 1999-02-04 fl Use memory mapping also for "I;16" and "I;16B"
17
+ # 1999-05-31 fl Added image parser
18
+ # 2000-10-12 fl Set readonly flag on memory-mapped images
19
+ # 2002-03-20 fl Use better messages for common decoder errors
20
+ # 2003-04-21 fl Fall back on mmap/map_buffer if map is not available
21
+ # 2003-10-30 fl Added StubImageFile class
22
+ # 2004-02-25 fl Made incremental parser more robust
23
+ #
24
+ # Copyright (c) 1997-2004 by Secret Labs AB
25
+ # Copyright (c) 1995-2004 by Fredrik Lundh
26
+ #
27
+ # See the README file for information on usage and redistribution.
28
+ #
29
+
30
+ import io
31
+ import itertools
32
+ import struct
33
+ import sys
34
+
35
+ from . import Image
36
+ from ._util import is_path
37
+
38
+ MAXBLOCK = 65536
39
+
40
+ SAFEBLOCK = 1024 * 1024
41
+
42
+ LOAD_TRUNCATED_IMAGES = False
43
+ """Whether or not to load truncated image files. User code may change this."""
44
+
45
+ ERRORS = {
46
+ -1: "image buffer overrun error",
47
+ -2: "decoding error",
48
+ -3: "unknown error",
49
+ -8: "bad configuration",
50
+ -9: "out of memory error",
51
+ }
52
+ """
53
+ Dict of known error codes returned from :meth:`.PyDecoder.decode`,
54
+ :meth:`.PyEncoder.encode` :meth:`.PyEncoder.encode_to_pyfd` and
55
+ :meth:`.PyEncoder.encode_to_file`.
56
+ """
57
+
58
+
59
+ #
60
+ # --------------------------------------------------------------------
61
+ # Helpers
62
+
63
+
64
+ def raise_oserror(error):
65
+ try:
66
+ msg = Image.core.getcodecstatus(error)
67
+ except AttributeError:
68
+ msg = ERRORS.get(error)
69
+ if not msg:
70
+ msg = f"decoder error {error}"
71
+ msg += " when reading image file"
72
+ raise OSError(msg)
73
+
74
+
75
+ def _tilesort(t):
76
+ # sort on offset
77
+ return t[2]
78
+
79
+
80
+ #
81
+ # --------------------------------------------------------------------
82
+ # ImageFile base class
83
+
84
+
85
+ class ImageFile(Image.Image):
86
+ """Base class for image file format handlers."""
87
+
88
+ def __init__(self, fp=None, filename=None):
89
+ super().__init__()
90
+
91
+ self._min_frame = 0
92
+
93
+ self.custom_mimetype = None
94
+
95
+ self.tile = None
96
+ """ A list of tile descriptors, or ``None`` """
97
+
98
+ self.readonly = 1 # until we know better
99
+
100
+ self.decoderconfig = ()
101
+ self.decodermaxblock = MAXBLOCK
102
+
103
+ if is_path(fp):
104
+ # filename
105
+ self.fp = open(fp, "rb")
106
+ self.filename = fp
107
+ self._exclusive_fp = True
108
+ else:
109
+ # stream
110
+ self.fp = fp
111
+ self.filename = filename
112
+ # can be overridden
113
+ self._exclusive_fp = None
114
+
115
+ try:
116
+ try:
117
+ self._open()
118
+ except (
119
+ IndexError, # end of data
120
+ TypeError, # end of data (ord)
121
+ KeyError, # unsupported mode
122
+ EOFError, # got header but not the first frame
123
+ struct.error,
124
+ ) as v:
125
+ raise SyntaxError(v) from v
126
+
127
+ if not self.mode or self.size[0] <= 0 or self.size[1] <= 0:
128
+ msg = "not identified by this driver"
129
+ raise SyntaxError(msg)
130
+ except BaseException:
131
+ # close the file only if we have opened it this constructor
132
+ if self._exclusive_fp:
133
+ self.fp.close()
134
+ raise
135
+
136
+ def get_format_mimetype(self):
137
+ if self.custom_mimetype:
138
+ return self.custom_mimetype
139
+ if self.format is not None:
140
+ return Image.MIME.get(self.format.upper())
141
+
142
+ def __setstate__(self, state):
143
+ self.tile = []
144
+ super().__setstate__(state)
145
+
146
+ def verify(self):
147
+ """Check file integrity"""
148
+
149
+ # raise exception if something's wrong. must be called
150
+ # directly after open, and closes file when finished.
151
+ if self._exclusive_fp:
152
+ self.fp.close()
153
+ self.fp = None
154
+
155
+ def load(self):
156
+ """Load image data based on tile list"""
157
+
158
+ if self.tile is None:
159
+ msg = "cannot load this image"
160
+ raise OSError(msg)
161
+
162
+ pixel = Image.Image.load(self)
163
+ if not self.tile:
164
+ return pixel
165
+
166
+ self.map = None
167
+ use_mmap = self.filename and len(self.tile) == 1
168
+ # As of pypy 2.1.0, memory mapping was failing here.
169
+ use_mmap = use_mmap and not hasattr(sys, "pypy_version_info")
170
+
171
+ readonly = 0
172
+
173
+ # look for read/seek overrides
174
+ try:
175
+ read = self.load_read
176
+ # don't use mmap if there are custom read/seek functions
177
+ use_mmap = False
178
+ except AttributeError:
179
+ read = self.fp.read
180
+
181
+ try:
182
+ seek = self.load_seek
183
+ use_mmap = False
184
+ except AttributeError:
185
+ seek = self.fp.seek
186
+
187
+ if use_mmap:
188
+ # try memory mapping
189
+ decoder_name, extents, offset, args = self.tile[0]
190
+ if (
191
+ decoder_name == "raw"
192
+ and len(args) >= 3
193
+ and args[0] == self.mode
194
+ and args[0] in Image._MAPMODES
195
+ ):
196
+ try:
197
+ # use mmap, if possible
198
+ import mmap
199
+
200
+ with open(self.filename) as fp:
201
+ self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ)
202
+ if offset + self.size[1] * args[1] > self.map.size():
203
+ # buffer is not large enough
204
+ raise OSError
205
+ self.im = Image.core.map_buffer(
206
+ self.map, self.size, decoder_name, offset, args
207
+ )
208
+ readonly = 1
209
+ # After trashing self.im,
210
+ # we might need to reload the palette data.
211
+ if self.palette:
212
+ self.palette.dirty = 1
213
+ except (AttributeError, OSError, ImportError):
214
+ self.map = None
215
+
216
+ self.load_prepare()
217
+ err_code = -3 # initialize to unknown error
218
+ if not self.map:
219
+ # sort tiles in file order
220
+ self.tile.sort(key=_tilesort)
221
+
222
+ try:
223
+ # FIXME: This is a hack to handle TIFF's JpegTables tag.
224
+ prefix = self.tile_prefix
225
+ except AttributeError:
226
+ prefix = b""
227
+
228
+ # Remove consecutive duplicates that only differ by their offset
229
+ self.tile = [
230
+ list(tiles)[-1]
231
+ for _, tiles in itertools.groupby(
232
+ self.tile, lambda tile: (tile[0], tile[1], tile[3])
233
+ )
234
+ ]
235
+ for decoder_name, extents, offset, args in self.tile:
236
+ seek(offset)
237
+ decoder = Image._getdecoder(
238
+ self.mode, decoder_name, args, self.decoderconfig
239
+ )
240
+ try:
241
+ decoder.setimage(self.im, extents)
242
+ if decoder.pulls_fd:
243
+ decoder.setfd(self.fp)
244
+ err_code = decoder.decode(b"")[1]
245
+ else:
246
+ b = prefix
247
+ while True:
248
+ try:
249
+ s = read(self.decodermaxblock)
250
+ except (IndexError, struct.error) as e:
251
+ # truncated png/gif
252
+ if LOAD_TRUNCATED_IMAGES:
253
+ break
254
+ else:
255
+ msg = "image file is truncated"
256
+ raise OSError(msg) from e
257
+
258
+ if not s: # truncated jpeg
259
+ if LOAD_TRUNCATED_IMAGES:
260
+ break
261
+ else:
262
+ msg = (
263
+ "image file is truncated "
264
+ f"({len(b)} bytes not processed)"
265
+ )
266
+ raise OSError(msg)
267
+
268
+ b = b + s
269
+ n, err_code = decoder.decode(b)
270
+ if n < 0:
271
+ break
272
+ b = b[n:]
273
+ finally:
274
+ # Need to cleanup here to prevent leaks
275
+ decoder.cleanup()
276
+
277
+ self.tile = []
278
+ self.readonly = readonly
279
+
280
+ self.load_end()
281
+
282
+ if self._exclusive_fp and self._close_exclusive_fp_after_loading:
283
+ self.fp.close()
284
+ self.fp = None
285
+
286
+ if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0:
287
+ # still raised if decoder fails to return anything
288
+ raise_oserror(err_code)
289
+
290
+ return Image.Image.load(self)
291
+
292
+ def load_prepare(self):
293
+ # create image memory if necessary
294
+ if not self.im or self.im.mode != self.mode or self.im.size != self.size:
295
+ self.im = Image.core.new(self.mode, self.size)
296
+ # create palette (optional)
297
+ if self.mode == "P":
298
+ Image.Image.load(self)
299
+
300
+ def load_end(self):
301
+ # may be overridden
302
+ pass
303
+
304
+ # may be defined for contained formats
305
+ # def load_seek(self, pos):
306
+ # pass
307
+
308
+ # may be defined for blocked formats (e.g. PNG)
309
+ # def load_read(self, bytes):
310
+ # pass
311
+
312
+ def _seek_check(self, frame):
313
+ if (
314
+ frame < self._min_frame
315
+ # Only check upper limit on frames if additional seek operations
316
+ # are not required to do so
317
+ or (
318
+ not (hasattr(self, "_n_frames") and self._n_frames is None)
319
+ and frame >= self.n_frames + self._min_frame
320
+ )
321
+ ):
322
+ msg = "attempt to seek outside sequence"
323
+ raise EOFError(msg)
324
+
325
+ return self.tell() != frame
326
+
327
+
328
+ class StubImageFile(ImageFile):
329
+ """
330
+ Base class for stub image loaders.
331
+
332
+ A stub loader is an image loader that can identify files of a
333
+ certain format, but relies on external code to load the file.
334
+ """
335
+
336
+ def _open(self):
337
+ msg = "StubImageFile subclass must implement _open"
338
+ raise NotImplementedError(msg)
339
+
340
+ def load(self):
341
+ loader = self._load()
342
+ if loader is None:
343
+ msg = f"cannot find loader for this {self.format} file"
344
+ raise OSError(msg)
345
+ image = loader.load(self)
346
+ assert image is not None
347
+ # become the other object (!)
348
+ self.__class__ = image.__class__
349
+ self.__dict__ = image.__dict__
350
+ return image.load()
351
+
352
+ def _load(self):
353
+ """(Hook) Find actual image loader."""
354
+ msg = "StubImageFile subclass must implement _load"
355
+ raise NotImplementedError(msg)
356
+
357
+
358
+ class Parser:
359
+ """
360
+ Incremental image parser. This class implements the standard
361
+ feed/close consumer interface.
362
+ """
363
+
364
+ incremental = None
365
+ image = None
366
+ data = None
367
+ decoder = None
368
+ offset = 0
369
+ finished = 0
370
+
371
+ def reset(self):
372
+ """
373
+ (Consumer) Reset the parser. Note that you can only call this
374
+ method immediately after you've created a parser; parser
375
+ instances cannot be reused.
376
+ """
377
+ assert self.data is None, "cannot reuse parsers"
378
+
379
+ def feed(self, data):
380
+ """
381
+ (Consumer) Feed data to the parser.
382
+
383
+ :param data: A string buffer.
384
+ :exception OSError: If the parser failed to parse the image file.
385
+ """
386
+ # collect data
387
+
388
+ if self.finished:
389
+ return
390
+
391
+ if self.data is None:
392
+ self.data = data
393
+ else:
394
+ self.data = self.data + data
395
+
396
+ # parse what we have
397
+ if self.decoder:
398
+ if self.offset > 0:
399
+ # skip header
400
+ skip = min(len(self.data), self.offset)
401
+ self.data = self.data[skip:]
402
+ self.offset = self.offset - skip
403
+ if self.offset > 0 or not self.data:
404
+ return
405
+
406
+ n, e = self.decoder.decode(self.data)
407
+
408
+ if n < 0:
409
+ # end of stream
410
+ self.data = None
411
+ self.finished = 1
412
+ if e < 0:
413
+ # decoding error
414
+ self.image = None
415
+ raise_oserror(e)
416
+ else:
417
+ # end of image
418
+ return
419
+ self.data = self.data[n:]
420
+
421
+ elif self.image:
422
+ # if we end up here with no decoder, this file cannot
423
+ # be incrementally parsed. wait until we've gotten all
424
+ # available data
425
+ pass
426
+
427
+ else:
428
+ # attempt to open this file
429
+ try:
430
+ with io.BytesIO(self.data) as fp:
431
+ im = Image.open(fp)
432
+ except OSError:
433
+ # traceback.print_exc()
434
+ pass # not enough data
435
+ else:
436
+ flag = hasattr(im, "load_seek") or hasattr(im, "load_read")
437
+ if flag or len(im.tile) != 1:
438
+ # custom load code, or multiple tiles
439
+ self.decode = None
440
+ else:
441
+ # initialize decoder
442
+ im.load_prepare()
443
+ d, e, o, a = im.tile[0]
444
+ im.tile = []
445
+ self.decoder = Image._getdecoder(im.mode, d, a, im.decoderconfig)
446
+ self.decoder.setimage(im.im, e)
447
+
448
+ # calculate decoder offset
449
+ self.offset = o
450
+ if self.offset <= len(self.data):
451
+ self.data = self.data[self.offset :]
452
+ self.offset = 0
453
+
454
+ self.image = im
455
+
456
+ def __enter__(self):
457
+ return self
458
+
459
+ def __exit__(self, *args):
460
+ self.close()
461
+
462
+ def close(self):
463
+ """
464
+ (Consumer) Close the stream.
465
+
466
+ :returns: An image object.
467
+ :exception OSError: If the parser failed to parse the image file either
468
+ because it cannot be identified or cannot be
469
+ decoded.
470
+ """
471
+ # finish decoding
472
+ if self.decoder:
473
+ # get rid of what's left in the buffers
474
+ self.feed(b"")
475
+ self.data = self.decoder = None
476
+ if not self.finished:
477
+ msg = "image was incomplete"
478
+ raise OSError(msg)
479
+ if not self.image:
480
+ msg = "cannot parse this image"
481
+ raise OSError(msg)
482
+ if self.data:
483
+ # incremental parsing not possible; reopen the file
484
+ # not that we have all data
485
+ with io.BytesIO(self.data) as fp:
486
+ try:
487
+ self.image = Image.open(fp)
488
+ finally:
489
+ self.image.load()
490
+ return self.image
491
+
492
+
493
+ # --------------------------------------------------------------------
494
+
495
+
496
+ def _save(im, fp, tile, bufsize=0):
497
+ """Helper to save image based on tile list
498
+
499
+ :param im: Image object.
500
+ :param fp: File object.
501
+ :param tile: Tile list.
502
+ :param bufsize: Optional buffer size
503
+ """
504
+
505
+ im.load()
506
+ if not hasattr(im, "encoderconfig"):
507
+ im.encoderconfig = ()
508
+ tile.sort(key=_tilesort)
509
+ # FIXME: make MAXBLOCK a configuration parameter
510
+ # It would be great if we could have the encoder specify what it needs
511
+ # But, it would need at least the image size in most cases. RawEncode is
512
+ # a tricky case.
513
+ bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.c
514
+ try:
515
+ fh = fp.fileno()
516
+ fp.flush()
517
+ _encode_tile(im, fp, tile, bufsize, fh)
518
+ except (AttributeError, io.UnsupportedOperation) as exc:
519
+ _encode_tile(im, fp, tile, bufsize, None, exc)
520
+ if hasattr(fp, "flush"):
521
+ fp.flush()
522
+
523
+
524
+ def _encode_tile(im, fp, tile, bufsize, fh, exc=None):
525
+ for e, b, o, a in tile:
526
+ if o > 0:
527
+ fp.seek(o)
528
+ encoder = Image._getencoder(im.mode, e, a, im.encoderconfig)
529
+ try:
530
+ encoder.setimage(im.im, b)
531
+ if encoder.pushes_fd:
532
+ encoder.setfd(fp)
533
+ errcode = encoder.encode_to_pyfd()[1]
534
+ else:
535
+ if exc:
536
+ # compress to Python file-compatible object
537
+ while True:
538
+ errcode, data = encoder.encode(bufsize)[1:]
539
+ fp.write(data)
540
+ if errcode:
541
+ break
542
+ else:
543
+ # slight speedup: compress to real file object
544
+ errcode = encoder.encode_to_file(fh, bufsize)
545
+ if errcode < 0:
546
+ msg = f"encoder error {errcode} when writing image file"
547
+ raise OSError(msg) from exc
548
+ finally:
549
+ encoder.cleanup()
550
+
551
+
552
+ def _safe_read(fp, size):
553
+ """
554
+ Reads large blocks in a safe way. Unlike fp.read(n), this function
555
+ doesn't trust the user. If the requested size is larger than
556
+ SAFEBLOCK, the file is read block by block.
557
+
558
+ :param fp: File handle. Must implement a <b>read</b> method.
559
+ :param size: Number of bytes to read.
560
+ :returns: A string containing <i>size</i> bytes of data.
561
+
562
+ Raises an OSError if the file is truncated and the read cannot be completed
563
+
564
+ """
565
+ if size <= 0:
566
+ return b""
567
+ if size <= SAFEBLOCK:
568
+ data = fp.read(size)
569
+ if len(data) < size:
570
+ msg = "Truncated File Read"
571
+ raise OSError(msg)
572
+ return data
573
+ data = []
574
+ remaining_size = size
575
+ while remaining_size > 0:
576
+ block = fp.read(min(remaining_size, SAFEBLOCK))
577
+ if not block:
578
+ break
579
+ data.append(block)
580
+ remaining_size -= len(block)
581
+ if sum(len(d) for d in data) < size:
582
+ msg = "Truncated File Read"
583
+ raise OSError(msg)
584
+ return b"".join(data)
585
+
586
+
587
+ class PyCodecState:
588
+ def __init__(self):
589
+ self.xsize = 0
590
+ self.ysize = 0
591
+ self.xoff = 0
592
+ self.yoff = 0
593
+
594
+ def extents(self):
595
+ return self.xoff, self.yoff, self.xoff + self.xsize, self.yoff + self.ysize
596
+
597
+
598
+ class PyCodec:
599
+ def __init__(self, mode, *args):
600
+ self.im = None
601
+ self.state = PyCodecState()
602
+ self.fd = None
603
+ self.mode = mode
604
+ self.init(args)
605
+
606
+ def init(self, args):
607
+ """
608
+ Override to perform codec specific initialization
609
+
610
+ :param args: Array of args items from the tile entry
611
+ :returns: None
612
+ """
613
+ self.args = args
614
+
615
+ def cleanup(self):
616
+ """
617
+ Override to perform codec specific cleanup
618
+
619
+ :returns: None
620
+ """
621
+ pass
622
+
623
+ def setfd(self, fd):
624
+ """
625
+ Called from ImageFile to set the Python file-like object
626
+
627
+ :param fd: A Python file-like object
628
+ :returns: None
629
+ """
630
+ self.fd = fd
631
+
632
+ def setimage(self, im, extents=None):
633
+ """
634
+ Called from ImageFile to set the core output image for the codec
635
+
636
+ :param im: A core image object
637
+ :param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectangle
638
+ for this tile
639
+ :returns: None
640
+ """
641
+
642
+ # following c code
643
+ self.im = im
644
+
645
+ if extents:
646
+ (x0, y0, x1, y1) = extents
647
+ else:
648
+ (x0, y0, x1, y1) = (0, 0, 0, 0)
649
+
650
+ if x0 == 0 and x1 == 0:
651
+ self.state.xsize, self.state.ysize = self.im.size
652
+ else:
653
+ self.state.xoff = x0
654
+ self.state.yoff = y0
655
+ self.state.xsize = x1 - x0
656
+ self.state.ysize = y1 - y0
657
+
658
+ if self.state.xsize <= 0 or self.state.ysize <= 0:
659
+ msg = "Size cannot be negative"
660
+ raise ValueError(msg)
661
+
662
+ if (
663
+ self.state.xsize + self.state.xoff > self.im.size[0]
664
+ or self.state.ysize + self.state.yoff > self.im.size[1]
665
+ ):
666
+ msg = "Tile cannot extend outside image"
667
+ raise ValueError(msg)
668
+
669
+
670
+ class PyDecoder(PyCodec):
671
+ """
672
+ Python implementation of a format decoder. Override this class and
673
+ add the decoding logic in the :meth:`decode` method.
674
+
675
+ See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`
676
+ """
677
+
678
+ _pulls_fd = False
679
+
680
+ @property
681
+ def pulls_fd(self):
682
+ return self._pulls_fd
683
+
684
+ def decode(self, buffer):
685
+ """
686
+ Override to perform the decoding process.
687
+
688
+ :param buffer: A bytes object with the data to be decoded.
689
+ :returns: A tuple of ``(bytes consumed, errcode)``.
690
+ If finished with decoding return -1 for the bytes consumed.
691
+ Err codes are from :data:`.ImageFile.ERRORS`.
692
+ """
693
+ raise NotImplementedError()
694
+
695
+ def set_as_raw(self, data, rawmode=None):
696
+ """
697
+ Convenience method to set the internal image from a stream of raw data
698
+
699
+ :param data: Bytes to be set
700
+ :param rawmode: The rawmode to be used for the decoder.
701
+ If not specified, it will default to the mode of the image
702
+ :returns: None
703
+ """
704
+
705
+ if not rawmode:
706
+ rawmode = self.mode
707
+ d = Image._getdecoder(self.mode, "raw", rawmode)
708
+ d.setimage(self.im, self.state.extents())
709
+ s = d.decode(data)
710
+
711
+ if s[0] >= 0:
712
+ msg = "not enough image data"
713
+ raise ValueError(msg)
714
+ if s[1] != 0:
715
+ msg = "cannot decode image data"
716
+ raise ValueError(msg)
717
+
718
+
719
+ class PyEncoder(PyCodec):
720
+ """
721
+ Python implementation of a format encoder. Override this class and
722
+ add the decoding logic in the :meth:`encode` method.
723
+
724
+ See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`
725
+ """
726
+
727
+ _pushes_fd = False
728
+
729
+ @property
730
+ def pushes_fd(self):
731
+ return self._pushes_fd
732
+
733
+ def encode(self, bufsize):
734
+ """
735
+ Override to perform the encoding process.
736
+
737
+ :param bufsize: Buffer size.
738
+ :returns: A tuple of ``(bytes encoded, errcode, bytes)``.
739
+ If finished with encoding return 1 for the error code.
740
+ Err codes are from :data:`.ImageFile.ERRORS`.
741
+ """
742
+ raise NotImplementedError()
743
+
744
+ def encode_to_pyfd(self):
745
+ """
746
+ If ``pushes_fd`` is ``True``, then this method will be used,
747
+ and ``encode()`` will only be called once.
748
+
749
+ :returns: A tuple of ``(bytes consumed, errcode)``.
750
+ Err codes are from :data:`.ImageFile.ERRORS`.
751
+ """
752
+ if not self.pushes_fd:
753
+ return 0, -8 # bad configuration
754
+ bytes_consumed, errcode, data = self.encode(0)
755
+ if data:
756
+ self.fd.write(data)
757
+ return bytes_consumed, errcode
758
+
759
+ def encode_to_file(self, fh, bufsize):
760
+ """
761
+ :param fh: File handle.
762
+ :param bufsize: Buffer size.
763
+
764
+ :returns: If finished successfully, return 0.
765
+ Otherwise, return an error code. Err codes are from
766
+ :data:`.ImageFile.ERRORS`.
767
+ """
768
+ errcode = 0
769
+ while errcode == 0:
770
+ status, errcode, buf = self.encode(bufsize)
771
+ if status > 0:
772
+ fh.write(buf[status:])
773
+ return errcode
Lib/site-packages/PIL/ImageFilter.py ADDED
@@ -0,0 +1,550 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # standard filters
6
+ #
7
+ # History:
8
+ # 1995-11-27 fl Created
9
+ # 2002-06-08 fl Added rank and mode filters
10
+ # 2003-09-15 fl Fixed rank calculation in rank filter; added expand call
11
+ #
12
+ # Copyright (c) 1997-2003 by Secret Labs AB.
13
+ # Copyright (c) 1995-2002 by Fredrik Lundh.
14
+ #
15
+ # See the README file for information on usage and redistribution.
16
+ #
17
+ import functools
18
+
19
+
20
+ class Filter:
21
+ pass
22
+
23
+
24
+ class MultibandFilter(Filter):
25
+ pass
26
+
27
+
28
+ class BuiltinFilter(MultibandFilter):
29
+ def filter(self, image):
30
+ if image.mode == "P":
31
+ msg = "cannot filter palette images"
32
+ raise ValueError(msg)
33
+ return image.filter(*self.filterargs)
34
+
35
+
36
+ class Kernel(BuiltinFilter):
37
+ """
38
+ Create a convolution kernel. The current version only
39
+ supports 3x3 and 5x5 integer and floating point kernels.
40
+
41
+ In the current version, kernels can only be applied to
42
+ "L" and "RGB" images.
43
+
44
+ :param size: Kernel size, given as (width, height). In the current
45
+ version, this must be (3,3) or (5,5).
46
+ :param kernel: A sequence containing kernel weights. The kernel will
47
+ be flipped vertically before being applied to the image.
48
+ :param scale: Scale factor. If given, the result for each pixel is
49
+ divided by this value. The default is the sum of the
50
+ kernel weights.
51
+ :param offset: Offset. If given, this value is added to the result,
52
+ after it has been divided by the scale factor.
53
+ """
54
+
55
+ name = "Kernel"
56
+
57
+ def __init__(self, size, kernel, scale=None, offset=0):
58
+ if scale is None:
59
+ # default scale is sum of kernel
60
+ scale = functools.reduce(lambda a, b: a + b, kernel)
61
+ if size[0] * size[1] != len(kernel):
62
+ msg = "not enough coefficients in kernel"
63
+ raise ValueError(msg)
64
+ self.filterargs = size, scale, offset, kernel
65
+
66
+
67
+ class RankFilter(Filter):
68
+ """
69
+ Create a rank filter. The rank filter sorts all pixels in
70
+ a window of the given size, and returns the ``rank``'th value.
71
+
72
+ :param size: The kernel size, in pixels.
73
+ :param rank: What pixel value to pick. Use 0 for a min filter,
74
+ ``size * size / 2`` for a median filter, ``size * size - 1``
75
+ for a max filter, etc.
76
+ """
77
+
78
+ name = "Rank"
79
+
80
+ def __init__(self, size, rank):
81
+ self.size = size
82
+ self.rank = rank
83
+
84
+ def filter(self, image):
85
+ if image.mode == "P":
86
+ msg = "cannot filter palette images"
87
+ raise ValueError(msg)
88
+ image = image.expand(self.size // 2, self.size // 2)
89
+ return image.rankfilter(self.size, self.rank)
90
+
91
+
92
+ class MedianFilter(RankFilter):
93
+ """
94
+ Create a median filter. Picks the median pixel value in a window with the
95
+ given size.
96
+
97
+ :param size: The kernel size, in pixels.
98
+ """
99
+
100
+ name = "Median"
101
+
102
+ def __init__(self, size=3):
103
+ self.size = size
104
+ self.rank = size * size // 2
105
+
106
+
107
+ class MinFilter(RankFilter):
108
+ """
109
+ Create a min filter. Picks the lowest pixel value in a window with the
110
+ given size.
111
+
112
+ :param size: The kernel size, in pixels.
113
+ """
114
+
115
+ name = "Min"
116
+
117
+ def __init__(self, size=3):
118
+ self.size = size
119
+ self.rank = 0
120
+
121
+
122
+ class MaxFilter(RankFilter):
123
+ """
124
+ Create a max filter. Picks the largest pixel value in a window with the
125
+ given size.
126
+
127
+ :param size: The kernel size, in pixels.
128
+ """
129
+
130
+ name = "Max"
131
+
132
+ def __init__(self, size=3):
133
+ self.size = size
134
+ self.rank = size * size - 1
135
+
136
+
137
+ class ModeFilter(Filter):
138
+ """
139
+ Create a mode filter. Picks the most frequent pixel value in a box with the
140
+ given size. Pixel values that occur only once or twice are ignored; if no
141
+ pixel value occurs more than twice, the original pixel value is preserved.
142
+
143
+ :param size: The kernel size, in pixels.
144
+ """
145
+
146
+ name = "Mode"
147
+
148
+ def __init__(self, size=3):
149
+ self.size = size
150
+
151
+ def filter(self, image):
152
+ return image.modefilter(self.size)
153
+
154
+
155
+ class GaussianBlur(MultibandFilter):
156
+ """Blurs the image with a sequence of extended box filters, which
157
+ approximates a Gaussian kernel. For details on accuracy see
158
+ <https://www.mia.uni-saarland.de/Publications/gwosdek-ssvm11.pdf>
159
+
160
+ :param radius: Standard deviation of the Gaussian kernel.
161
+ """
162
+
163
+ name = "GaussianBlur"
164
+
165
+ def __init__(self, radius=2):
166
+ self.radius = radius
167
+
168
+ def filter(self, image):
169
+ return image.gaussian_blur(self.radius)
170
+
171
+
172
+ class BoxBlur(MultibandFilter):
173
+ """Blurs the image by setting each pixel to the average value of the pixels
174
+ in a square box extending radius pixels in each direction.
175
+ Supports float radius of arbitrary size. Uses an optimized implementation
176
+ which runs in linear time relative to the size of the image
177
+ for any radius value.
178
+
179
+ :param radius: Size of the box in one direction. Radius 0 does not blur,
180
+ returns an identical image. Radius 1 takes 1 pixel
181
+ in each direction, i.e. 9 pixels in total.
182
+ """
183
+
184
+ name = "BoxBlur"
185
+
186
+ def __init__(self, radius):
187
+ if radius < 0:
188
+ msg = "radius must be >= 0"
189
+ raise ValueError(msg)
190
+ self.radius = radius
191
+
192
+ def filter(self, image):
193
+ return image.box_blur(self.radius)
194
+
195
+
196
+ class UnsharpMask(MultibandFilter):
197
+ """Unsharp mask filter.
198
+
199
+ See Wikipedia's entry on `digital unsharp masking`_ for an explanation of
200
+ the parameters.
201
+
202
+ :param radius: Blur Radius
203
+ :param percent: Unsharp strength, in percent
204
+ :param threshold: Threshold controls the minimum brightness change that
205
+ will be sharpened
206
+
207
+ .. _digital unsharp masking: https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking
208
+
209
+ """ # noqa: E501
210
+
211
+ name = "UnsharpMask"
212
+
213
+ def __init__(self, radius=2, percent=150, threshold=3):
214
+ self.radius = radius
215
+ self.percent = percent
216
+ self.threshold = threshold
217
+
218
+ def filter(self, image):
219
+ return image.unsharp_mask(self.radius, self.percent, self.threshold)
220
+
221
+
222
+ class BLUR(BuiltinFilter):
223
+ name = "Blur"
224
+ # fmt: off
225
+ filterargs = (5, 5), 16, 0, (
226
+ 1, 1, 1, 1, 1,
227
+ 1, 0, 0, 0, 1,
228
+ 1, 0, 0, 0, 1,
229
+ 1, 0, 0, 0, 1,
230
+ 1, 1, 1, 1, 1,
231
+ )
232
+ # fmt: on
233
+
234
+
235
+ class CONTOUR(BuiltinFilter):
236
+ name = "Contour"
237
+ # fmt: off
238
+ filterargs = (3, 3), 1, 255, (
239
+ -1, -1, -1,
240
+ -1, 8, -1,
241
+ -1, -1, -1,
242
+ )
243
+ # fmt: on
244
+
245
+
246
+ class DETAIL(BuiltinFilter):
247
+ name = "Detail"
248
+ # fmt: off
249
+ filterargs = (3, 3), 6, 0, (
250
+ 0, -1, 0,
251
+ -1, 10, -1,
252
+ 0, -1, 0,
253
+ )
254
+ # fmt: on
255
+
256
+
257
+ class EDGE_ENHANCE(BuiltinFilter):
258
+ name = "Edge-enhance"
259
+ # fmt: off
260
+ filterargs = (3, 3), 2, 0, (
261
+ -1, -1, -1,
262
+ -1, 10, -1,
263
+ -1, -1, -1,
264
+ )
265
+ # fmt: on
266
+
267
+
268
+ class EDGE_ENHANCE_MORE(BuiltinFilter):
269
+ name = "Edge-enhance More"
270
+ # fmt: off
271
+ filterargs = (3, 3), 1, 0, (
272
+ -1, -1, -1,
273
+ -1, 9, -1,
274
+ -1, -1, -1,
275
+ )
276
+ # fmt: on
277
+
278
+
279
+ class EMBOSS(BuiltinFilter):
280
+ name = "Emboss"
281
+ # fmt: off
282
+ filterargs = (3, 3), 1, 128, (
283
+ -1, 0, 0,
284
+ 0, 1, 0,
285
+ 0, 0, 0,
286
+ )
287
+ # fmt: on
288
+
289
+
290
+ class FIND_EDGES(BuiltinFilter):
291
+ name = "Find Edges"
292
+ # fmt: off
293
+ filterargs = (3, 3), 1, 0, (
294
+ -1, -1, -1,
295
+ -1, 8, -1,
296
+ -1, -1, -1,
297
+ )
298
+ # fmt: on
299
+
300
+
301
+ class SHARPEN(BuiltinFilter):
302
+ name = "Sharpen"
303
+ # fmt: off
304
+ filterargs = (3, 3), 16, 0, (
305
+ -2, -2, -2,
306
+ -2, 32, -2,
307
+ -2, -2, -2,
308
+ )
309
+ # fmt: on
310
+
311
+
312
+ class SMOOTH(BuiltinFilter):
313
+ name = "Smooth"
314
+ # fmt: off
315
+ filterargs = (3, 3), 13, 0, (
316
+ 1, 1, 1,
317
+ 1, 5, 1,
318
+ 1, 1, 1,
319
+ )
320
+ # fmt: on
321
+
322
+
323
+ class SMOOTH_MORE(BuiltinFilter):
324
+ name = "Smooth More"
325
+ # fmt: off
326
+ filterargs = (5, 5), 100, 0, (
327
+ 1, 1, 1, 1, 1,
328
+ 1, 5, 5, 5, 1,
329
+ 1, 5, 44, 5, 1,
330
+ 1, 5, 5, 5, 1,
331
+ 1, 1, 1, 1, 1,
332
+ )
333
+ # fmt: on
334
+
335
+
336
+ class Color3DLUT(MultibandFilter):
337
+ """Three-dimensional color lookup table.
338
+
339
+ Transforms 3-channel pixels using the values of the channels as coordinates
340
+ in the 3D lookup table and interpolating the nearest elements.
341
+
342
+ This method allows you to apply almost any color transformation
343
+ in constant time by using pre-calculated decimated tables.
344
+
345
+ .. versionadded:: 5.2.0
346
+
347
+ :param size: Size of the table. One int or tuple of (int, int, int).
348
+ Minimal size in any dimension is 2, maximum is 65.
349
+ :param table: Flat lookup table. A list of ``channels * size**3``
350
+ float elements or a list of ``size**3`` channels-sized
351
+ tuples with floats. Channels are changed first,
352
+ then first dimension, then second, then third.
353
+ Value 0.0 corresponds lowest value of output, 1.0 highest.
354
+ :param channels: Number of channels in the table. Could be 3 or 4.
355
+ Default is 3.
356
+ :param target_mode: A mode for the result image. Should have not less
357
+ than ``channels`` channels. Default is ``None``,
358
+ which means that mode wouldn't be changed.
359
+ """
360
+
361
+ name = "Color 3D LUT"
362
+
363
+ def __init__(self, size, table, channels=3, target_mode=None, **kwargs):
364
+ if channels not in (3, 4):
365
+ msg = "Only 3 or 4 output channels are supported"
366
+ raise ValueError(msg)
367
+ self.size = size = self._check_size(size)
368
+ self.channels = channels
369
+ self.mode = target_mode
370
+
371
+ # Hidden flag `_copy_table=False` could be used to avoid extra copying
372
+ # of the table if the table is specially made for the constructor.
373
+ copy_table = kwargs.get("_copy_table", True)
374
+ items = size[0] * size[1] * size[2]
375
+ wrong_size = False
376
+
377
+ numpy = None
378
+ if hasattr(table, "shape"):
379
+ try:
380
+ import numpy
381
+ except ImportError: # pragma: no cover
382
+ pass
383
+
384
+ if numpy and isinstance(table, numpy.ndarray):
385
+ if copy_table:
386
+ table = table.copy()
387
+
388
+ if table.shape in [
389
+ (items * channels,),
390
+ (items, channels),
391
+ (size[2], size[1], size[0], channels),
392
+ ]:
393
+ table = table.reshape(items * channels)
394
+ else:
395
+ wrong_size = True
396
+
397
+ else:
398
+ if copy_table:
399
+ table = list(table)
400
+
401
+ # Convert to a flat list
402
+ if table and isinstance(table[0], (list, tuple)):
403
+ table, raw_table = [], table
404
+ for pixel in raw_table:
405
+ if len(pixel) != channels:
406
+ msg = (
407
+ "The elements of the table should "
408
+ f"have a length of {channels}."
409
+ )
410
+ raise ValueError(msg)
411
+ table.extend(pixel)
412
+
413
+ if wrong_size or len(table) != items * channels:
414
+ msg = (
415
+ "The table should have either channels * size**3 float items "
416
+ "or size**3 items of channels-sized tuples with floats. "
417
+ f"Table should be: {channels}x{size[0]}x{size[1]}x{size[2]}. "
418
+ f"Actual length: {len(table)}"
419
+ )
420
+ raise ValueError(msg)
421
+ self.table = table
422
+
423
+ @staticmethod
424
+ def _check_size(size):
425
+ try:
426
+ _, _, _ = size
427
+ except ValueError as e:
428
+ msg = "Size should be either an integer or a tuple of three integers."
429
+ raise ValueError(msg) from e
430
+ except TypeError:
431
+ size = (size, size, size)
432
+ size = [int(x) for x in size]
433
+ for size_1d in size:
434
+ if not 2 <= size_1d <= 65:
435
+ msg = "Size should be in [2, 65] range."
436
+ raise ValueError(msg)
437
+ return size
438
+
439
+ @classmethod
440
+ def generate(cls, size, callback, channels=3, target_mode=None):
441
+ """Generates new LUT using provided callback.
442
+
443
+ :param size: Size of the table. Passed to the constructor.
444
+ :param callback: Function with three parameters which correspond
445
+ three color channels. Will be called ``size**3``
446
+ times with values from 0.0 to 1.0 and should return
447
+ a tuple with ``channels`` elements.
448
+ :param channels: The number of channels which should return callback.
449
+ :param target_mode: Passed to the constructor of the resulting
450
+ lookup table.
451
+ """
452
+ size_1d, size_2d, size_3d = cls._check_size(size)
453
+ if channels not in (3, 4):
454
+ msg = "Only 3 or 4 output channels are supported"
455
+ raise ValueError(msg)
456
+
457
+ table = [0] * (size_1d * size_2d * size_3d * channels)
458
+ idx_out = 0
459
+ for b in range(size_3d):
460
+ for g in range(size_2d):
461
+ for r in range(size_1d):
462
+ table[idx_out : idx_out + channels] = callback(
463
+ r / (size_1d - 1), g / (size_2d - 1), b / (size_3d - 1)
464
+ )
465
+ idx_out += channels
466
+
467
+ return cls(
468
+ (size_1d, size_2d, size_3d),
469
+ table,
470
+ channels=channels,
471
+ target_mode=target_mode,
472
+ _copy_table=False,
473
+ )
474
+
475
+ def transform(self, callback, with_normals=False, channels=None, target_mode=None):
476
+ """Transforms the table values using provided callback and returns
477
+ a new LUT with altered values.
478
+
479
+ :param callback: A function which takes old lookup table values
480
+ and returns a new set of values. The number
481
+ of arguments which function should take is
482
+ ``self.channels`` or ``3 + self.channels``
483
+ if ``with_normals`` flag is set.
484
+ Should return a tuple of ``self.channels`` or
485
+ ``channels`` elements if it is set.
486
+ :param with_normals: If true, ``callback`` will be called with
487
+ coordinates in the color cube as the first
488
+ three arguments. Otherwise, ``callback``
489
+ will be called only with actual color values.
490
+ :param channels: The number of channels in the resulting lookup table.
491
+ :param target_mode: Passed to the constructor of the resulting
492
+ lookup table.
493
+ """
494
+ if channels not in (None, 3, 4):
495
+ msg = "Only 3 or 4 output channels are supported"
496
+ raise ValueError(msg)
497
+ ch_in = self.channels
498
+ ch_out = channels or ch_in
499
+ size_1d, size_2d, size_3d = self.size
500
+
501
+ table = [0] * (size_1d * size_2d * size_3d * ch_out)
502
+ idx_in = 0
503
+ idx_out = 0
504
+ for b in range(size_3d):
505
+ for g in range(size_2d):
506
+ for r in range(size_1d):
507
+ values = self.table[idx_in : idx_in + ch_in]
508
+ if with_normals:
509
+ values = callback(
510
+ r / (size_1d - 1),
511
+ g / (size_2d - 1),
512
+ b / (size_3d - 1),
513
+ *values,
514
+ )
515
+ else:
516
+ values = callback(*values)
517
+ table[idx_out : idx_out + ch_out] = values
518
+ idx_in += ch_in
519
+ idx_out += ch_out
520
+
521
+ return type(self)(
522
+ self.size,
523
+ table,
524
+ channels=ch_out,
525
+ target_mode=target_mode or self.mode,
526
+ _copy_table=False,
527
+ )
528
+
529
+ def __repr__(self):
530
+ r = [
531
+ f"{self.__class__.__name__} from {self.table.__class__.__name__}",
532
+ "size={:d}x{:d}x{:d}".format(*self.size),
533
+ f"channels={self.channels:d}",
534
+ ]
535
+ if self.mode:
536
+ r.append(f"target_mode={self.mode}")
537
+ return "<{}>".format(" ".join(r))
538
+
539
+ def filter(self, image):
540
+ from . import Image
541
+
542
+ return image.color_lut_3d(
543
+ self.mode or image.mode,
544
+ Image.Resampling.BILINEAR,
545
+ self.channels,
546
+ self.size[0],
547
+ self.size[1],
548
+ self.size[2],
549
+ self.table,
550
+ )