├── .dockerignore ├── .gitignore ├── Dockerfile ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.md ├── build.sh ├── libheif ├── libheif_api.h └── libheif_build.py ├── pyheif ├── __init__.py ├── constants.py ├── data │ └── version.txt ├── error.py ├── reader.py ├── transformations.py └── writer.py ├── requirements-dev.txt ├── requirements-publish.txt ├── requirements-test.txt ├── setup.py ├── tests ├── __init__.py ├── images │ ├── arrow.heic │ ├── avif-sample-images │ │ ├── LICENSE.txt │ │ ├── README.txt │ │ ├── fox.profile0.10bpc.yuv420.avif │ │ ├── fox.profile0.10bpc.yuv420.monochrome.avif │ │ ├── fox.profile0.8bpc.yuv420.avif │ │ ├── fox.profile0.8bpc.yuv420.monochrome.avif │ │ ├── fox.profile1.10bpc.yuv444.avif │ │ ├── fox.profile1.8bpc.yuv444.avif │ │ ├── fox.profile2.10bpc.yuv422.avif │ │ ├── fox.profile2.10bpc.yuv422.monochrome.avif │ │ ├── fox.profile2.12bpc.yuv420.avif │ │ ├── fox.profile2.12bpc.yuv420.monochrome.avif │ │ ├── fox.profile2.12bpc.yuv422.avif │ │ ├── fox.profile2.12bpc.yuv422.monochrome.avif │ │ ├── fox.profile2.12bpc.yuv444.avif │ │ ├── fox.profile2.12bpc.yuv444.monochrome.avif │ │ ├── fox.profile2.8bpc.yuv422.avif │ │ └── fox.profile2.8bpc.yuv422.monochrome.avif │ ├── hif │ │ ├── 93FG5559.HIF │ │ ├── 93FG5564.HIF │ │ ├── COPYRIGHT │ │ └── README │ ├── iPhoneXR.heic │ ├── lego.heic │ ├── live-image.heic │ ├── multiimage.heic │ ├── nokia │ │ ├── COPYRIGHT │ │ ├── README │ │ ├── alpha │ │ │ └── alpha_1440x960.heic │ │ ├── bothie │ │ │ └── bothie_1440x960.heic │ │ ├── burst │ │ │ ├── bird_burst.heic │ │ │ └── rally_burst.heic │ │ ├── collection │ │ │ ├── random_collection_1440x960.heic │ │ │ └── season_collection_1440x960.heic │ │ ├── grid │ │ │ └── grid_960x640.heic │ │ ├── overlay │ │ │ └── overlay_1000x680.heic │ │ ├── sequence │ │ │ ├── sea1_animation.heic │ │ │ └── starfield_animation.heic │ │ ├── stereo │ │ │ └── stereo_1200x800.heic │ │ ├── still │ │ │ ├── autumn_1440x960.heic │ │ │ ├── cheers_1440x960.heic │ │ │ ├── crowd_1440x960.heic │ │ │ ├── old_bridge_1440x960.heic │ │ │ ├── ski_jump_1440x960.heic │ │ │ ├── spring_1440x960.heic │ │ │ ├── summer_1440x960.heic │ │ │ ├── surfer_1440x960.heic │ │ │ └── winter_1440x960.heic │ │ └── udes │ │ │ └── lights_1440x960.heic │ ├── parfait.heic │ ├── tree-with-transforms.avif │ └── tree-with-transparency.heic ├── test_read.py └── test_versions.py └── tools ├── freeze-deps.sh ├── git-push.sh └── pypi-publish.sh /.dockerignore: -------------------------------------------------------------------------------- 1 | .* 2 | build 3 | *.so 4 | Dockerfile 5 | Makefile 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | _libheif_cffi.c 28 | _libheif_cffi.o 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | .hypothesis/ 50 | .pytest_cache/ 51 | 52 | # Translations 53 | *.mo 54 | *.pot 55 | 56 | # Django stuff: 57 | *.log 58 | local_settings.py 59 | db.sqlite3 60 | 61 | # Flask stuff: 62 | instance/ 63 | .webassets-cache 64 | 65 | # Scrapy stuff: 66 | .scrapy 67 | 68 | # Sphinx documentation 69 | docs/_build/ 70 | 71 | # PyBuilder 72 | target/ 73 | 74 | # Jupyter Notebook 75 | .ipynb_checkpoints 76 | 77 | # pyenv 78 | .python-version 79 | 80 | # celery beat schedule file 81 | celerybeat-schedule 82 | 83 | # SageMath parsed files 84 | *.sage.py 85 | 86 | # Environments 87 | .env 88 | .venv 89 | env/ 90 | venv/ 91 | ENV/ 92 | env.bak/ 93 | venv.bak/ 94 | 95 | # Spyder project settings 96 | .spyderproject 97 | .spyproject 98 | 99 | # Rope project settings 100 | .ropeproject 101 | 102 | # mkdocs documentation 103 | /site 104 | 105 | # mypy 106 | .mypy_cache/ 107 | 108 | #scrath 109 | scratch/ 110 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | ARG PLAT=manylinux2014_x86_64 2 | 3 | FROM quay.io/pypa/$PLAT:2024.08.12-1 AS base 4 | 5 | 6 | ############### 7 | # Build tools # 8 | ############### 9 | 10 | FROM base AS build-tools 11 | 12 | WORKDIR /build 13 | 14 | # pkg-config 15 | RUN set -ex \ 16 | && PKG_CONFIG_VERSION="0.29.2" \ 17 | && curl -fLO https://pkg-config.freedesktop.org/releases/pkg-config-${PKG_CONFIG_VERSION}.tar.gz \ 18 | && tar xvf pkg-config-${PKG_CONFIG_VERSION}.tar.gz \ 19 | && cd pkg-config-${PKG_CONFIG_VERSION} \ 20 | && ./configure \ 21 | && make -j $(nproc) && make install \ 22 | && pkg-config --version \ 23 | && rm -rf /build 24 | 25 | # nasm 26 | RUN set -ex \ 27 | && NASM_VERSION="2.15.02" \ 28 | && curl -fLO https://www.nasm.us/pub/nasm/releasebuilds/${NASM_VERSION}/nasm-${NASM_VERSION}.tar.gz \ 29 | && tar xvf nasm-${NASM_VERSION}.tar.gz \ 30 | && cd nasm-${NASM_VERSION} \ 31 | && ./configure \ 32 | && make -j $(nproc) && make install \ 33 | && nasm --version \ 34 | && rm -rf /build 35 | 36 | 37 | ################ 38 | # Dependencies # 39 | ################ 40 | 41 | FROM build-tools AS build-deps 42 | 43 | # x265 44 | RUN set -ex \ 45 | && X265_VERSION="3.6" \ 46 | && curl -fLO https://bitbucket.org/multicoreware/x265_git/downloads/x265_${X265_VERSION}.tar.gz \ 47 | && tar xvf x265_${X265_VERSION}.tar.gz \ 48 | && cd x265_${X265_VERSION} \ 49 | && cmake -DCMAKE_INSTALL_PREFIX=/usr -G "Unix Makefiles" ./source \ 50 | && make -j $(nproc) && make install && ldconfig \ 51 | && rm -rf /build 52 | 53 | # libde265 54 | RUN set -ex \ 55 | && LIBDE265_VERSION="1.0.15" \ 56 | && curl -fLO https://github.com/strukturag/libde265/releases/download/v${LIBDE265_VERSION}/libde265-${LIBDE265_VERSION}.tar.gz \ 57 | && tar xvf libde265-${LIBDE265_VERSION}.tar.gz \ 58 | && cd libde265-${LIBDE265_VERSION} \ 59 | && ./autogen.sh \ 60 | && CXXFLAGS="-g1 -O2" ./configure --prefix /usr --disable-encoder --disable-dec265 --disable-sherlock265 --disable-dependency-tracking \ 61 | && make -j $(nproc) && make install && ldconfig \ 62 | && rm -rf /build 63 | 64 | # libaom 65 | RUN set -ex \ 66 | && LIBAOM_VERSION="v3.8.3" \ 67 | && mkdir -v aom && mkdir -v aom_build && cd aom \ 68 | && curl -fLO "https://aomedia.googlesource.com/aom/+archive/${LIBAOM_VERSION}.tar.gz" \ 69 | && tar xvf ${LIBAOM_VERSION}.tar.gz \ 70 | && cd ../aom_build \ 71 | && MINIMAL_INSTALL="-DENABLE_TESTS=0 -DENABLE_TOOLS=0 -DENABLE_EXAMPLES=0 -DENABLE_DOCS=0" \ 72 | && cmake $MINIMAL_INSTALL -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_INSTALL_LIBDIR=lib -DBUILD_SHARED_LIBS=1 ../aom \ 73 | && make -j $(nproc) && make install && ldconfig \ 74 | && rm -rf /build 75 | 76 | ################## 77 | # libheif 1.18.2 # 78 | ################## 79 | 80 | FROM build-deps AS libheif 81 | ARG LIBHEIF_VERSION=1.18.2 82 | ARG PLAT 83 | 84 | RUN set -ex \ 85 | && LIBHEIF_VERSION="$LIBHEIF_VERSION" \ 86 | && curl -fLO https://github.com/strukturag/libheif/releases/download/v${LIBHEIF_VERSION}/libheif-${LIBHEIF_VERSION}.tar.gz \ 87 | && tar xvf libheif-${LIBHEIF_VERSION}.tar.gz && mv libheif-${LIBHEIF_VERSION} libheif \ 88 | && mkdir libheif_build && cd libheif_build \ 89 | && cmake --install-prefix=/usr --preset=release-noplugins -DWITH_EXAMPLES=no ../libheif \ 90 | && make -j $(nproc) && make install && ldconfig \ 91 | && rm -rf /build 92 | 93 | COPY ./ /pyheif 94 | 95 | RUN set -ex \ 96 | && PNV="/opt/python/cp310-cp310/bin" \ 97 | && $PNV/pip wheel /pyheif \ 98 | && auditwheel repair pyheif*.whl --plat $PLAT -w /wheelhouse \ 99 | && $PNV/pip install --only-binary pillow==10.4.0 -r /pyheif/requirements-test.txt \ 100 | && $PNV/pip install /wheelhouse/*-cp310-*.whl \ 101 | && cd /pyheif && $PNV/pytest 102 | 103 | ########################## 104 | # Build manylinux wheels # 105 | ########################## 106 | 107 | FROM libheif AS all-pythons-repaired 108 | ARG PLAT 109 | 110 | COPY ./ /pyheif 111 | 112 | RUN /opt/python/cp37-cp37m/bin/pip wheel /pyheif 113 | RUN /opt/python/cp38-cp38/bin/pip wheel /pyheif 114 | RUN /opt/python/cp39-cp39/bin/pip wheel /pyheif 115 | RUN /opt/python/cp310-cp310/bin/pip wheel /pyheif 116 | RUN /opt/python/cp311-cp311/bin/pip wheel /pyheif 117 | RUN /opt/python/cp312-cp312/bin/pip wheel /pyheif 118 | RUN /opt/python/pp39-pypy39_pp73/bin/pip wheel /pyheif 119 | RUN /opt/python/pp310-pypy310_pp73/bin/pip wheel /pyheif 120 | RUN auditwheel repair pyheif*.whl --plat $PLAT -w /wheelhouse 121 | 122 | 123 | ############### 124 | # Test wheels # 125 | ############### 126 | 127 | FROM base AS tested 128 | 129 | COPY ./requirements-test.txt /tmp/requirements-test.txt 130 | 131 | RUN /opt/python/cp37-cp37m/bin/pip install --only-binary pillow==10.4.0 -r /tmp/requirements-test.txt 132 | RUN /opt/python/cp38-cp38/bin/pip install --only-binary pillow==10.4.0 -r /tmp/requirements-test.txt 133 | RUN /opt/python/cp39-cp39/bin/pip install --only-binary pillow==10.4.0 -r /tmp/requirements-test.txt 134 | RUN /opt/python/cp310-cp310/bin/pip install --only-binary pillow==10.4.0 -r /tmp/requirements-test.txt 135 | RUN /opt/python/cp311-cp311/bin/pip install --only-binary pillow==10.4.0 -r /tmp/requirements-test.txt 136 | RUN /opt/python/cp312-cp312/bin/pip install --only-binary pillow==10.4.0 -r /tmp/requirements-test.txt 137 | RUN /opt/python/pp39-pypy39_pp73/bin/pip install --only-binary pillow==10.4.0 -r /tmp/requirements-test.txt 138 | RUN /opt/python/pp310-pypy310_pp73/bin/pip install --only-binary pillow==10.4.0 -r /tmp/requirements-test.txt 139 | 140 | COPY --from=all-pythons-repaired /wheelhouse /wheelhouse 141 | COPY ./ /pyheif 142 | WORKDIR /pyheif 143 | 144 | # python 3.7 145 | RUN set -ex \ 146 | && PNV="/opt/python/cp37-cp37m/bin" \ 147 | && $PNV/pip install /wheelhouse/*-cp37-*.whl \ 148 | && $PNV/pytest 149 | # python 3.8 150 | RUN set -ex \ 151 | && PNV="/opt/python/cp38-cp38/bin" \ 152 | && $PNV/pip install /wheelhouse/*-cp38-*.whl \ 153 | && $PNV/pytest 154 | # python 3.9 155 | RUN set -ex \ 156 | && PNV="/opt/python/cp39-cp39/bin" \ 157 | && $PNV/pip install /wheelhouse/*-cp39-*.whl \ 158 | && $PNV/pytest 159 | # python 3.10 160 | RUN set -ex \ 161 | && PNV="/opt/python/cp310-cp310/bin" \ 162 | && $PNV/pip install /wheelhouse/*-cp310-*.whl \ 163 | && $PNV/pytest 164 | # python 3.11 165 | RUN set -ex \ 166 | && PNV="/opt/python/cp311-cp311/bin" \ 167 | && $PNV/pip install /wheelhouse/*-cp311-*.whl \ 168 | && $PNV/pytest 169 | # python 3.12 170 | RUN set -ex \ 171 | && PNV="/opt/python/cp312-cp312/bin" \ 172 | && $PNV/pip install /wheelhouse/*-cp312-*.whl \ 173 | && $PNV/pytest 174 | # pypy 3.9 175 | RUN set -ex \ 176 | && PNV="/opt/python/pp39-pypy39_pp73/bin" \ 177 | && $PNV/pip install /wheelhouse/*-pp39-*.whl \ 178 | && $PNV/pytest 179 | # pypy 3.10 180 | RUN set -ex \ 181 | && PNV="/opt/python/pp310-pypy310_pp73/bin" \ 182 | && $PNV/pip install /wheelhouse/*-pp310-*.whl \ 183 | && $PNV/pytest 184 | 185 | 186 | ################# 187 | # Upload wheels # 188 | ################# 189 | 190 | FROM tested AS uploaded 191 | 192 | ARG PYPI_USERNAME 193 | ARG PYPI_PASSWORD 194 | RUN set -ex \ 195 | && cd "/opt/python/cp38-cp38/bin/" \ 196 | && ./pip install twine \ 197 | && ./twine upload /wheelhouse/*manylinux2014*.whl -u ${PYPI_USERNAME} -p ${PYPI_PASSWORD} \ 198 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include libheif/* 2 | 3 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: check_libheif_versions 2 | 3 | PLAT ?= manylinux2014_x86_64 4 | 5 | check_libheif_versions: 6 | docker build --target=libheif --build-arg=PLAT=${PLAT} --build-arg=LIBHEIF_VERSION=1.16.2 . 7 | docker build --target=libheif --build-arg=PLAT=${PLAT} --build-arg=LIBHEIF_VERSION=1.17.0 . 8 | docker build --target=libheif --build-arg=PLAT=${PLAT} --build-arg=LIBHEIF_VERSION=1.17.5 . 9 | docker build --target=libheif --build-arg=PLAT=${PLAT} --build-arg=LIBHEIF_VERSION=1.17.6 . 10 | docker build --target=libheif --build-arg=PLAT=${PLAT} --build-arg=LIBHEIF_VERSION=1.18.0 . 11 | docker build --target=libheif --build-arg=PLAT=${PLAT} --build-arg=LIBHEIF_VERSION=1.18.1 . 12 | docker build --target=libheif --build-arg=PLAT=${PLAT} --build-arg=LIBHEIF_VERSION=1.18.2 . 13 | 14 | test: 15 | docker build --target=tested --build-arg=PLAT=${PLAT} . 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pyheif 2 | Python 3.6+ interface to [libheif](https://github.com/strukturag/libheif) library using CFFI 3 | 4 | *Note*: currently only reading is supported. 5 | 6 | ## Installation 7 | 8 | ### Simple installation - Linux (installs manylinux2014 wheel, doesn't work with Alpine) 9 | ``` 10 | pip install --upgrade pip 11 | pip install pyheif 12 | ``` 13 | 14 | ### Installing from source - MacOS 15 | ``` 16 | brew install libffi libheif 17 | pip install git+https://github.com/carsales/pyheif.git 18 | ``` 19 | 20 | ### Installing from source - Linux 21 | ``` 22 | apt install libffi libheif-dev libde265-dev 23 | ``` 24 | or 25 | ``` 26 | yum install libffi libheif-devel libde265-devel 27 | ``` 28 | then 29 | ``` 30 | pip install git+https://github.com/carsales/pyheif.git 31 | ``` 32 | 33 | ### Installing from source - Windows 34 | ``` 35 | Sorry, not going to happen! 36 | ``` 37 | 38 | ## Usage 39 | 40 | ### Read the primary image of a HEIF encoded file 41 | 42 | The `pyheif.read(path_or_bytes)` function can be used to read the primary image of a HEIF encoded file. It can be passed any of the following: 43 | 44 | * A string path to a file on disk 45 | * A `pathlib.Path` path object 46 | * A Python `bytes` or `bytearray` object containing HEIF content 47 | * A file-like object with a `.read()` method that returns bytes 48 | 49 | It returns a `HeifImage` object. 50 | 51 | ```python 52 | import pyheif 53 | 54 | # Using a file path: 55 | heif_file = pyheif.read("IMG_7424.HEIC") 56 | # Or using bytes directly: 57 | heif_file = pyheif.read(open("IMG_7424.HEIC", "rb").read()) 58 | ``` 59 | 60 | ### Converting to a Pillow Image object 61 | 62 | If your HEIF file contains an image that you would like to manipulate, you can do so using the [Pillow](https://pillow.readthedocs.io/) Python library. You can convert a `HeifImage` to a Pillow image like so: 63 | 64 | ```python 65 | from PIL import Image 66 | import pyheif 67 | 68 | heif_file = pyheif.read("IMG_7424.HEIC") 69 | image = Image.frombytes( 70 | heif_file.mode, 71 | heif_file.size, 72 | heif_file.data, 73 | "raw", 74 | heif_file.mode, 75 | heif_file.stride, 76 | ) 77 | ``` 78 | 79 | *Note*: the `mode` property is passed twice - once to the `mode` argument of the `frombytes` method, and again to the `mode` argument of the `raw` decoder. 80 | 81 | You can now use any Pillow method to manipulate the file. Here's how to convert it to JPEG: 82 | 83 | ```python 84 | image.save("IMG_7424.jpg", "JPEG") 85 | ``` 86 | 87 | ### Read the entire container within the HEIF file 88 | 89 | The `pyheif.open_container(path_or_bytes)` function can be used to read the HEIF container from a HEIF encoded file. It takes the same parameter as `pyheif.read()` 90 | 91 | It returns a `HeifContainer` object. 92 | 93 | ## Objects 94 | 95 | ### The HeifImage object 96 | 97 | The `HeifImage` has the following properties: 98 | 99 | * `mode` - the image mode, e.g. "RGB" or "RGBA" 100 | * `size` - the size of the image as a `(width, height)` tuple of integers 101 | * `data` - the raw decoded file data, as bytes 102 | * `metadata` - a list of metadata dictionaries 103 | * `color_profile` - a color profile dictionary 104 | * `stride` - the number of bytes in a row of decoded file data 105 | * `bit_depth` - the number of bits in each component of a pixel 106 | 107 | ### The UndecodedHeifImage object 108 | 109 | This is a HEIF image that has not been decoded. Calling the `UndecodedHeifImage.load()` method will load the data and the object will become a `HeifImage` 110 | 111 | ### The HeifContainer object 112 | 113 | The `HeifContainer` has the following properties: 114 | 115 | * `primary_image` - the `HeifTopLevelImage` object of the primary image in the file. 116 | * `top_level_images` - a list of all `HeifTopLevelImage` objects in the file. 117 | 118 | ### The HeifTopLevelImage object 119 | 120 | The `HeifTopLevelImage` has the following properties: 121 | 122 | * `id` - the id of the image 123 | * `image` - the `UndecodedHeifImage` or `HeifImage` object of the image 124 | * `is_primary` - is this the primary image in the container 125 | * `depth_image` - the `HeifDepthImage` if there is one 126 | * `auxiliary_images` - a list of `HeifAuxiliaryImage` objects 127 | 128 | ### The HeifDepthImage object 129 | 130 | The `HeifDepthImage` has the following properties: 131 | 132 | * `id` - the id of the image 133 | * `image` - the `UndecodedHeifImage` or `HeifImage` object of the image 134 | 135 | ### The HeifAuxiliaryImage object 136 | 137 | The `HeifAuxiliaryImage` has the following properties: 138 | 139 | * `id` - the id of the image 140 | * `image` - the `UndecodedHeifImage` or `HeifImage` object of the image 141 | * `type` - a string indicating the type of auxiliary image 142 | 143 | 144 | 145 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo "Pypi password for $PYPI_USERNAME: " 4 | read -s password 5 | 6 | docker build --build-arg PYPI_USERNAME --build-arg PYPI_PASSWORD=$password . 7 | 8 | -------------------------------------------------------------------------------- /libheif/libheif_api.h: -------------------------------------------------------------------------------- 1 | struct heif_context; 2 | struct heif_image_handle; 3 | struct heif_image; 4 | struct heif_reading_options; 5 | 6 | struct heif_error 7 | { 8 | // main error category 9 | enum heif_error_code code; 10 | 11 | // more detailed error code 12 | enum heif_suberror_code subcode; 13 | 14 | // textual error message (is always defined, you do not have to check for NULL) 15 | const char* message; 16 | }; 17 | 18 | typedef uint32_t heif_item_id; 19 | typedef uint32_t heif_property_id; 20 | 21 | enum heif_chroma 22 | { 23 | heif_chroma_undefined = 99, 24 | heif_chroma_monochrome = 0, 25 | heif_chroma_420 = 1, 26 | heif_chroma_422 = 2, 27 | heif_chroma_444 = 3, 28 | heif_chroma_interleaved_RGB = 10, 29 | heif_chroma_interleaved_RGBA = 11, 30 | heif_chroma_interleaved_RRGGBB_BE = 12, // HDR, big endian. 31 | heif_chroma_interleaved_RRGGBBAA_BE = 13, // HDR, big endian. 32 | heif_chroma_interleaved_RRGGBB_LE = 14, // HDR, little endian. 33 | heif_chroma_interleaved_RRGGBBAA_LE = 15 // HDR, little endian. 34 | }; 35 | 36 | enum heif_colorspace 37 | { 38 | heif_colorspace_undefined = 99, 39 | 40 | // heif_colorspace_YCbCr should be used with one of these heif_chroma values: 41 | // * heif_chroma_444 42 | // * heif_chroma_422 43 | // * heif_chroma_420 44 | heif_colorspace_YCbCr = 0, 45 | 46 | // heif_colorspace_RGB should be used with one of these heif_chroma values: 47 | // * heif_chroma_444 (for planar RGB) 48 | // * heif_chroma_interleaved_RGB 49 | // * heif_chroma_interleaved_RGBA 50 | // * heif_chroma_interleaved_RRGGBB_BE 51 | // * heif_chroma_interleaved_RRGGBBAA_BE 52 | // * heif_chroma_interleaved_RRGGBB_LE 53 | // * heif_chroma_interleaved_RRGGBBAA_LE 54 | heif_colorspace_RGB = 1, 55 | 56 | // heif_colorspace_monochrome should only be used with heif_chroma = heif_chroma_monochrome 57 | heif_colorspace_monochrome = 2 58 | }; 59 | 60 | enum heif_channel 61 | { 62 | heif_channel_Y = 0, 63 | heif_channel_Cb = 1, 64 | heif_channel_Cr = 2, 65 | heif_channel_R = 3, 66 | heif_channel_G = 4, 67 | heif_channel_B = 5, 68 | heif_channel_Alpha = 6, 69 | heif_channel_interleaved = 10 70 | }; 71 | 72 | 73 | // Version string of linked libheif library. 74 | const char* heif_get_version(void); 75 | 76 | enum heif_filetype_result 77 | { 78 | heif_filetype_no, 79 | heif_filetype_yes_supported, // it is heif and can be read by libheif 80 | heif_filetype_yes_unsupported, // it is heif, but cannot be read by libheif 81 | heif_filetype_maybe // not sure whether it is an heif, try detection with more input data 82 | }; 83 | 84 | // input data should be at least 12 bytes 85 | enum heif_filetype_result heif_check_filetype(const uint8_t* data, int len); 86 | 87 | // Allocate a new context for reading HEIF files. 88 | // Has to be freed again with heif_context_free(). 89 | struct heif_context* heif_context_alloc(void); 90 | 91 | // Free a previously allocated HEIF context. You should not free a context twice. 92 | void heif_context_free(struct heif_context*); 93 | 94 | // Same as heif_context_read_from_memory() except that the provided memory is not copied. 95 | // That means, you will have to keep the memory area alive as long as you use the heif_context. 96 | struct heif_error heif_context_read_from_memory_without_copy(struct heif_context*, 97 | const void* mem, size_t size, 98 | const struct heif_reading_options*); 99 | 100 | // Number of top-level images in the HEIF file. This does not include the thumbnails or the 101 | // tile images that are composed to an image grid. You can get access to the thumbnails via 102 | // the main image handle. 103 | int heif_context_get_number_of_top_level_images(struct heif_context* ctx); 104 | 105 | // Fills in image IDs into the user-supplied int-array 'ID_array', preallocated with 'count' entries. 106 | // Function returns the total number of IDs filled into the array. 107 | int heif_context_get_list_of_top_level_image_IDs(struct heif_context* ctx, 108 | heif_item_id* ID_array, 109 | int count); 110 | 111 | struct heif_error heif_context_get_primary_image_ID(struct heif_context* ctx, heif_item_id* id); 112 | 113 | // Get the image handle for a known image ID. 114 | struct heif_error heif_context_get_image_handle(struct heif_context* ctx, 115 | heif_item_id id, 116 | struct heif_image_handle**); 117 | 118 | // ========================= heif_image_handle ========================= 119 | 120 | // An heif_image_handle is a handle to a logical image in the HEIF file. 121 | // To get the actual pixel data, you have to decode the handle to an heif_image. 122 | // An heif_image_handle also gives you access to the thumbnails and Exif data 123 | // associated with an image. 124 | 125 | // Once you obtained an heif_image_handle, you can already release the heif_context, 126 | // since it is internally ref-counted. 127 | 128 | // Release image handle. 129 | void heif_image_handle_release(const struct heif_image_handle*); 130 | 131 | heif_item_id heif_image_handle_get_item_id(const struct heif_image_handle* handle); 132 | 133 | // Get the resolution of an image. 134 | int heif_image_handle_get_width(const struct heif_image_handle* handle); 135 | 136 | int heif_image_handle_get_height(const struct heif_image_handle* handle); 137 | 138 | int heif_image_handle_has_alpha_channel(const struct heif_image_handle*); 139 | 140 | // Get the image width from the 'ispe' box. This is the original image size without 141 | // any transformations applied to it. Do not use this unless you know exactly what 142 | // you are doing. 143 | int heif_image_handle_get_ispe_width(const struct heif_image_handle* handle); 144 | 145 | int heif_image_handle_get_ispe_height(const struct heif_image_handle* handle); 146 | 147 | // Returns -1 on error, e.g. if this information is not present in the image. 148 | int heif_image_handle_get_luma_bits_per_pixel(const struct heif_image_handle*); 149 | 150 | 151 | // ------------------------- item properties ------------------------- 152 | 153 | enum heif_item_property_type 154 | { 155 | // heif_item_property_unknown = -1, 156 | heif_item_property_type_invalid = 0, 157 | }; 158 | 159 | // Returns all transformative properties in the correct order. 160 | // This includes "irot", "imir", "clap". 161 | // The number of properties is returned, which are not more than 'count' if (out_list != nullptr). 162 | // By setting out_list==nullptr, you can query the number of properties, 'count' is ignored. 163 | int heif_item_get_transformation_properties(const struct heif_context* context, 164 | heif_item_id id, 165 | heif_property_id* out_list, 166 | int count); 167 | 168 | enum heif_item_property_type heif_item_get_property_type(const struct heif_context* context, 169 | heif_item_id id, 170 | heif_property_id property_id); 171 | 172 | enum heif_transform_mirror_direction 173 | { 174 | heif_transform_mirror_direction_vertical = 0, // flip image vertically 175 | heif_transform_mirror_direction_horizontal = 1 // flip image horizontally 176 | }; 177 | 178 | // Will return 'heif_transform_mirror_direction_invalid' in case of error. 179 | enum heif_transform_mirror_direction heif_item_get_property_transform_mirror(const struct heif_context* context, 180 | heif_item_id itemId, 181 | heif_property_id propertyId); 182 | 183 | // Returns only 0, 90, 180, or 270 angle values. 184 | // Returns -1 in case of error (but it will only return an error in case of wrong usage). 185 | int heif_item_get_property_transform_rotation_ccw(const struct heif_context* context, 186 | heif_item_id itemId, 187 | heif_property_id propertyId); 188 | 189 | // Returns the number of pixels that should be removed from the four edges. 190 | // Because of the way this data is stored, you have to pass the image size at the moment of the crop operation 191 | // to compute the cropped border sizes. 192 | void heif_item_get_property_transform_crop_borders(const struct heif_context* context, 193 | heif_item_id itemId, 194 | heif_property_id propertyId, 195 | int image_width, int image_height, 196 | int* left, int* top, int* right, int* bottom); 197 | 198 | // ------------------------- depth images ------------------------- 199 | 200 | int heif_image_handle_has_depth_image(const struct heif_image_handle*); 201 | 202 | int heif_image_handle_get_list_of_depth_image_IDs(const struct heif_image_handle* handle, 203 | heif_item_id* ids, int count); 204 | 205 | struct heif_error heif_image_handle_get_depth_image_handle(const struct heif_image_handle* handle, 206 | heif_item_id depth_image_id, 207 | struct heif_image_handle** out_depth_handle); 208 | 209 | // ------------------------- auxiliary images ------------------------- 210 | 211 | // List the number of auxiliary images assigned to this image handle. 212 | int heif_image_handle_get_number_of_auxiliary_images(const struct heif_image_handle* handle, 213 | int aux_filter); 214 | 215 | int heif_image_handle_get_list_of_auxiliary_image_IDs(const struct heif_image_handle* handle, 216 | int aux_filter, 217 | heif_item_id* ids, int count); 218 | 219 | // You are responsible to deallocate the returned buffer with heif_image_handle_release_auxiliary_type(). 220 | struct heif_error heif_image_handle_get_auxiliary_type(const struct heif_image_handle* handle, 221 | const char** out_type); 222 | 223 | void heif_image_handle_release_auxiliary_type(const struct heif_image_handle* handle, 224 | const char** out_type); 225 | 226 | // Get the image handle of an auxiliary image. 227 | struct heif_error heif_image_handle_get_auxiliary_image_handle(const struct heif_image_handle* main_image_handle, 228 | heif_item_id auxiliary_id, 229 | struct heif_image_handle** out_auxiliary_handle); 230 | 231 | 232 | // ------------------------- metadata (Exif / XMP) ------------------------- 233 | 234 | // How many metadata blocks are attached to an image. If you only want to get EXIF data, 235 | // set the type_filter to "Exif". Otherwise, set the type_filter to NULL. 236 | int heif_image_handle_get_number_of_metadata_blocks(const struct heif_image_handle* handle, 237 | const char* type_filter); 238 | 239 | // 'type_filter' can be used to get only metadata of specific types, like "Exif". 240 | // If 'type_filter' is NULL, it will return all types of metadata IDs. 241 | int heif_image_handle_get_list_of_metadata_block_IDs(const struct heif_image_handle* handle, 242 | const char* type_filter, 243 | heif_item_id* ids, int count); 244 | 245 | // Return a string indicating the type of the metadata, as specified in the HEIF file. 246 | // Exif data will have the type string "Exif". 247 | // This string will be valid until the next call to a libheif function. 248 | // You do not have to free this string. 249 | const char* heif_image_handle_get_metadata_type(const struct heif_image_handle* handle, 250 | heif_item_id metadata_id); 251 | 252 | // Get the size of the raw metadata, as stored in the HEIF file. 253 | size_t heif_image_handle_get_metadata_size(const struct heif_image_handle* handle, 254 | heif_item_id metadata_id); 255 | 256 | // 'out_data' must point to a memory area of the size reported by heif_image_handle_get_metadata_size(). 257 | // The data is returned exactly as stored in the HEIF file. 258 | // For Exif data, you probably have to skip the first four bytes of the data, since they 259 | // indicate the offset to the start of the TIFF header of the Exif data. 260 | struct heif_error heif_image_handle_get_metadata(const struct heif_image_handle* handle, 261 | heif_item_id metadata_id, 262 | void* out_data); 263 | 264 | // ------------------------- color profiles ------------------------- 265 | 266 | enum heif_color_profile_type 267 | { 268 | heif_color_profile_type_not_present = 0, 269 | }; 270 | 271 | 272 | // Returns 'heif_color_profile_type_not_present' if there is no color profile. 273 | // If there is an ICC profile and an NCLX profile, the ICC profile is returned. 274 | enum heif_color_profile_type heif_image_handle_get_color_profile_type(const struct heif_image_handle* handle); 275 | 276 | size_t heif_image_handle_get_raw_color_profile_size(const struct heif_image_handle* handle); 277 | 278 | // Returns 'heif_error_Color_profile_does_not_exist' when there is no ICC profile. 279 | struct heif_error heif_image_handle_get_raw_color_profile(const struct heif_image_handle* handle, 280 | void* out_data); 281 | 282 | struct heif_color_profile_nclx 283 | { 284 | // === version 1 fields 285 | 286 | uint8_t version; 287 | 288 | enum heif_color_primaries color_primaries; 289 | enum heif_transfer_characteristics transfer_characteristics; 290 | enum heif_matrix_coefficients matrix_coefficients; 291 | uint8_t full_range_flag; 292 | 293 | // --- decoded values (not used when saving nclx) 294 | 295 | float color_primary_red_x, color_primary_red_y; 296 | float color_primary_green_x, color_primary_green_y; 297 | float color_primary_blue_x, color_primary_blue_y; 298 | float color_primary_white_x, color_primary_white_y; 299 | }; 300 | 301 | // Returns 'heif_error_Color_profile_does_not_exist' when there is no NCLX profile. 302 | // TODO: This function does currently not return an NCLX profile if it is stored in the image bitstream. 303 | // Only NCLX profiles stored as colr boxes are returned. This may change in the future. 304 | struct heif_error heif_image_handle_get_nclx_color_profile(const struct heif_image_handle* handle, 305 | struct heif_color_profile_nclx** out_data); 306 | 307 | void heif_nclx_color_profile_free(struct heif_color_profile_nclx* nclx_profile); 308 | 309 | // ========================= heif_image ========================= 310 | 311 | // An heif_image contains a decoded pixel image in various colorspaces, chroma formats, 312 | // and bit depths. 313 | 314 | // Note: when converting images to an interleaved chroma format, the resulting 315 | // image contains only a single channel of type channel_interleaved with, e.g., 3 bytes per pixel, 316 | // containing the interleaved R,G,B values. 317 | 318 | // Planar RGB images are specified as heif_colorspace_RGB / heif_chroma_444. 319 | 320 | enum heif_progress_step 321 | { 322 | heif_progress_step_total = 0, 323 | heif_progress_step_load_tile = 1 324 | }; 325 | 326 | 327 | enum heif_chroma_downsampling_algorithm 328 | { 329 | heif_chroma_downsampling_nearest_neighbor = 1, 330 | heif_chroma_downsampling_average = 2, 331 | 332 | // Combine with 'heif_chroma_upsampling_bilinear' for best quality. 333 | // Makes edges look sharper when using YUV 420 with bilinear chroma upsampling. 334 | heif_chroma_downsampling_sharp_yuv = 3 335 | }; 336 | 337 | enum heif_chroma_upsampling_algorithm 338 | { 339 | heif_chroma_upsampling_nearest_neighbor = 1, 340 | heif_chroma_upsampling_bilinear = 2 341 | }; 342 | 343 | struct heif_color_conversion_options 344 | { 345 | uint8_t version; 346 | 347 | // --- version 1 options 348 | 349 | enum heif_chroma_downsampling_algorithm preferred_chroma_downsampling_algorithm; 350 | enum heif_chroma_upsampling_algorithm preferred_chroma_upsampling_algorithm; 351 | 352 | // When set to 'false' libheif may also use a different algorithm if the preferred one is not available 353 | // or using a different algorithm is computationally less complex. Note that currently (v1.17.0) this 354 | // means that for RGB input it will usually choose nearest-neighbor sampling because this is computationally 355 | // the simplest. 356 | // Set this field to 'true' if you want to make sure that the specified algorithm is used even 357 | // at the cost of slightly higher computation times. 358 | uint8_t only_use_preferred_chroma_algorithm; 359 | }; 360 | 361 | 362 | struct heif_decoding_options 363 | { 364 | uint8_t version; 365 | 366 | // version 1 options 367 | 368 | // Ignore geometric transformations like cropping, rotation, mirroring. 369 | // Default: false (do not ignore). 370 | uint8_t ignore_transformations; 371 | 372 | void (* start_progress)(enum heif_progress_step step, int max_progress, void* progress_user_data); 373 | 374 | void (* on_progress)(enum heif_progress_step step, int progress, void* progress_user_data); 375 | 376 | void (* end_progress)(enum heif_progress_step step, void* progress_user_data); 377 | 378 | void* progress_user_data; 379 | 380 | // version 2 options 381 | 382 | uint8_t convert_hdr_to_8bit; 383 | 384 | // version 3 options 385 | 386 | // When enabled, an error is returned for invalid input. Otherwise, it will try its best and 387 | // add decoding warnings to the decoded heif_image. Default is non-strict. 388 | uint8_t strict_decoding; 389 | 390 | // version 4 options 391 | 392 | // name_id of the decoder to use for the decoding. 393 | // If set to NULL (default), the highest priority decoder is chosen. 394 | // The priority is defined in the plugin. 395 | const char* decoder_id; 396 | 397 | 398 | // version 5 options 399 | 400 | struct heif_color_conversion_options color_conversion_options; 401 | }; 402 | 403 | 404 | // Allocate decoding options and fill with default values. 405 | // Note: you should always get the decoding options through this function since the 406 | // option structure may grow in size in future versions. 407 | struct heif_decoding_options* heif_decoding_options_alloc(void); 408 | 409 | void heif_decoding_options_free(struct heif_decoding_options*); 410 | 411 | // Decode an heif_image_handle into the actual pixel image and also carry out 412 | // all geometric transformations specified in the HEIF file (rotation, cropping, mirroring). 413 | // 414 | // If colorspace or chroma is set to heif_colorspace_undefined or heif_chroma_undefined, 415 | // respectively, the original colorspace is taken. 416 | // Decoding options may be NULL. If you want to supply options, always use 417 | // heif_decoding_options_alloc() to get the structure. 418 | struct heif_error heif_decode_image(const struct heif_image_handle* in_handle, 419 | struct heif_image** out_img, 420 | enum heif_colorspace colorspace, 421 | enum heif_chroma chroma, 422 | const struct heif_decoding_options* options); 423 | 424 | // Get a pointer to the actual pixel data. 425 | // The 'out_stride' is returned as "bytes per line". 426 | // When out_stride is NULL, no value will be written. 427 | // Returns NULL if a non-existing channel was given. 428 | const uint8_t* heif_image_get_plane_readonly(const struct heif_image*, 429 | enum heif_channel channel, 430 | int* out_stride); 431 | 432 | // Release heif_image. 433 | void heif_image_release(const struct heif_image*); 434 | -------------------------------------------------------------------------------- /libheif/libheif_build.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from cffi import FFI 4 | 5 | ffibuilder = FFI() 6 | 7 | with open("libheif/libheif_api.h") as f: 8 | ffibuilder.cdef(f.read()) 9 | 10 | include_dirs = ["/usr/local/include", "/usr/include", "/opt/local/include"] 11 | library_dirs = ["/usr/local/lib", "/usr/lib", "/lib", "/opt/local/lib"] 12 | 13 | homebrew_prefix = os.getenv("HOMEBREW_PREFIX") 14 | if homebrew_prefix: 15 | include_dirs.append(os.path.join(homebrew_prefix, "include")) 16 | library_dirs.append(os.path.join(homebrew_prefix, "lib")) 17 | 18 | ffibuilder.set_source( 19 | "_libheif_cffi", 20 | """ 21 | #include 22 | // 1.17.0+ stores properties in different files 23 | #if LIBHEIF_NUMERIC_VERSION >= 0x01110000 24 | #include 25 | #endif 26 | """, 27 | include_dirs=include_dirs, 28 | library_dirs=library_dirs, 29 | libraries=["heif"], 30 | ) 31 | 32 | if __name__ == "__main__": 33 | ffibuilder.compile(verbose=True) 34 | -------------------------------------------------------------------------------- /pyheif/__init__.py: -------------------------------------------------------------------------------- 1 | import builtins 2 | import os 3 | 4 | import _libheif_cffi 5 | 6 | from .constants import * 7 | from .reader import * 8 | from .writer import * 9 | 10 | version_path = os.path.dirname(os.path.abspath(__file__)) + "/data/version.txt" 11 | with builtins.open(version_path) as f: 12 | __version__ = f.read().strip() 13 | 14 | 15 | def libheif_version(): 16 | version = _libheif_cffi.lib.heif_get_version() 17 | version = _libheif_cffi.ffi.string(version).decode() 18 | return version 19 | -------------------------------------------------------------------------------- /pyheif/constants.py: -------------------------------------------------------------------------------- 1 | heif_chroma_undefined = 99 2 | heif_chroma_monochrome = 0 3 | heif_chroma_420 = 1 4 | heif_chroma_422 = 2 5 | heif_chroma_444 = 3 6 | heif_chroma_interleaved_RGB = 10 7 | heif_chroma_interleaved_RGBA = 11 8 | heif_chroma_interleaved_RRGGBB_BE = 12 9 | heif_chroma_interleaved_RRGGBBAA_BE = 13 10 | 11 | heif_colorspace_undefined = 99 12 | heif_colorspace_YCbCr = 0 13 | heif_colorspace_RGB = 1 14 | heif_colorspace_monochrome = 2 15 | 16 | heif_channel_Y = 0 17 | heif_channel_Cb = 1 18 | heif_channel_Cr = 2 19 | heif_channel_R = 3 20 | heif_channel_G = 4 21 | heif_channel_B = 5 22 | heif_channel_Alpha = 6 23 | heif_channel_interleaved = 10 24 | 25 | 26 | def encode_fourcc(fourcc): 27 | encoded = ( 28 | ord(fourcc[0]) << 24 29 | | ord(fourcc[1]) << 16 30 | | ord(fourcc[2]) << 8 31 | | ord(fourcc[3]) 32 | ) 33 | return encoded 34 | 35 | 36 | heif_color_profile_type_not_present = 0 37 | heif_color_profile_type_nclx = encode_fourcc("nclx") 38 | heif_color_profile_type_rICC = encode_fourcc("rICC") 39 | heif_color_profile_type_prof = encode_fourcc("prof") 40 | 41 | heif_filetype_no = 0 42 | heif_filetype_yes_supported = 1 43 | heif_filetype_yes_unsupported = 2 44 | heif_filetype_maybe = 3 45 | 46 | heif_item_property_type_user_description = encode_fourcc("udes") 47 | heif_item_property_type_transform_mirror = encode_fourcc("imir") 48 | heif_item_property_type_transform_rotation = encode_fourcc("irot") 49 | heif_item_property_type_transform_crop = encode_fourcc("clap") 50 | heif_item_property_type_image_size = encode_fourcc("ispe") 51 | 52 | heif_transform_mirror_direction_vertical = 0 53 | heif_transform_mirror_direction_horizontal = 1 54 | 55 | LIBHEIF_AUX_IMAGE_FILTER_OMIT_ALPHA = 0x2 56 | LIBHEIF_AUX_IMAGE_FILTER_OMIT_DEPTH = 0x4 57 | -------------------------------------------------------------------------------- /pyheif/data/version.txt: -------------------------------------------------------------------------------- 1 | 0.8.0 2 | -------------------------------------------------------------------------------- /pyheif/error.py: -------------------------------------------------------------------------------- 1 | from _libheif_cffi import ffi 2 | 3 | 4 | class HeifError(Exception): 5 | def __init__(self, *, code, subcode, message): 6 | self.code = code 7 | self.subcode = subcode 8 | self.message = message 9 | 10 | def __str__(self): 11 | return f'Code: {self.code}, Subcode: {self.subcode}, Message: "{self.message}"' 12 | 13 | def __repr__(self): 14 | return f'HeifError({self.code}, {self.subcode}, "{self.message}"' 15 | 16 | 17 | class HeifNoImageError(Exception): 18 | def __init__(self): 19 | self.message = "Heif file contains no images" 20 | 21 | def __str__(self): 22 | return self.message 23 | 24 | 25 | def _assert_success(error): 26 | if error.code != 0: 27 | raise HeifError( 28 | code=error.code, 29 | subcode=error.subcode, 30 | message=ffi.string(error.message).decode(), 31 | ) 32 | -------------------------------------------------------------------------------- /pyheif/reader.py: -------------------------------------------------------------------------------- 1 | import builtins 2 | import functools 3 | import pathlib 4 | import warnings 5 | 6 | from _libheif_cffi import ffi, lib as libheif 7 | from . import constants as _constants 8 | from .transformations import Transformations 9 | from .error import _assert_success, HeifNoImageError 10 | 11 | 12 | class HeifImage: 13 | def __init__( 14 | self, *, size, has_alpha, bit_depth, transformations, metadata, color_profile, data, stride 15 | ): 16 | self.size = size 17 | self.has_alpha = has_alpha 18 | self.mode = "RGBA" if has_alpha else "RGB" 19 | self.bit_depth = bit_depth 20 | self.transformations = transformations 21 | self.metadata = metadata 22 | self.color_profile = color_profile 23 | self.data = data 24 | self.stride = stride 25 | 26 | def __repr__(self): 27 | return ( 28 | f"<{self.__class__.__name__} {self.size[0]}x{self.size[1]} {self.mode} " 29 | f"with {str(len(self.data)) + ' bytes' if self.data else 'no'} data>" 30 | ) 31 | 32 | def load(self): 33 | return self # already loaded 34 | 35 | def close(self): 36 | pass # TODO: release self.data here? 37 | 38 | 39 | class UndecodedHeifImage(HeifImage): 40 | def __init__( 41 | self, ctx, heif_handle, *, apply_transformations, convert_hdr_to_8bit, **kwargs 42 | ): 43 | self._ctx = ctx 44 | self._heif_handle = heif_handle 45 | self.apply_transformations = apply_transformations 46 | self.convert_hdr_to_8bit = convert_hdr_to_8bit 47 | super().__init__(data=None, stride=None, **kwargs) 48 | 49 | def load(self): 50 | self.data, self.stride = _read_heif_image(self._heif_handle, self) 51 | self.close() 52 | self.__class__ = HeifImage 53 | return self 54 | 55 | def close(self): 56 | # Don't call super().close() here, we don't need to free bytes. 57 | if hasattr(self, "_heif_handle"): 58 | del self._heif_handle 59 | if hasattr(self, "_ctx"): 60 | del self._ctx 61 | 62 | 63 | # This names are deprecated an will be removed in 1.0 64 | HeifFile = HeifImage 65 | UndecodedHeifFile = UndecodedHeifImage 66 | 67 | 68 | class HeifContainer: 69 | def __init__(self, primary_image, top_level_images): 70 | self.primary_image = primary_image 71 | self.top_level_images = top_level_images 72 | 73 | 74 | class HeifTopLevelImage: 75 | def __init__(self, id, image, is_primary, depth_image, auxiliary_images): 76 | self.id = id 77 | self.image = image 78 | self.is_primary = is_primary 79 | self.depth_image = depth_image 80 | self.auxiliary_images = auxiliary_images 81 | 82 | 83 | class HeifDepthImage: 84 | def __init__(self, id, image): 85 | self.id = id 86 | self.image = image 87 | 88 | 89 | class HeifAuxiliaryImage: 90 | def __init__(self, id, type, image): 91 | self.id = id 92 | self.type = type 93 | self.image = image 94 | 95 | 96 | def check(fp): 97 | magic = _get_bytes(fp, 12) 98 | filetype_check = libheif.heif_check_filetype(magic, len(magic)) 99 | return filetype_check 100 | 101 | 102 | def read_heif(fp, apply_transformations=True): 103 | warnings.warn("read_heif is deprecated, use read() instead", DeprecationWarning) 104 | return read(fp, apply_transformations=apply_transformations) 105 | 106 | 107 | def read(fp, *, apply_transformations=True, convert_hdr_to_8bit=True): 108 | heif_file = open( 109 | fp, 110 | apply_transformations=apply_transformations, 111 | convert_hdr_to_8bit=convert_hdr_to_8bit, 112 | ) 113 | return heif_file.load() 114 | 115 | 116 | def open(fp, *, apply_transformations=True, convert_hdr_to_8bit=True): 117 | heif_container = open_container( 118 | fp, 119 | apply_transformations=apply_transformations, 120 | convert_hdr_to_8bit=convert_hdr_to_8bit, 121 | ) 122 | return heif_container.primary_image.image 123 | 124 | 125 | def open_container(fp, *, apply_transformations=True, convert_hdr_to_8bit=True): 126 | d = _get_bytes(fp) 127 | ctx = _get_heif_context(d) 128 | return _read_heif_container(ctx, apply_transformations, convert_hdr_to_8bit) 129 | 130 | 131 | def _get_bytes(fp, length=None): 132 | if isinstance(fp, (str, pathlib.Path)): 133 | with builtins.open(fp, "rb") as f: 134 | d = f.read(length or -1) 135 | elif hasattr(fp, "read"): 136 | d = fp.read(length or -1) 137 | else: 138 | d = bytes(fp)[:length] 139 | 140 | return d 141 | 142 | 143 | def _keep_refs(destructor, **refs): 144 | """ 145 | Keep refs to passed arguments until `inner` callback exist. 146 | This prevents collecting parent objects until all children collected. 147 | """ 148 | 149 | def inner(cdata): 150 | return destructor(cdata) 151 | 152 | inner._refs = refs 153 | return inner 154 | 155 | 156 | def _get_heif_context(d): 157 | magic = d[:12] 158 | filetype_check = libheif.heif_check_filetype(magic, len(magic)) 159 | if filetype_check == _constants.heif_filetype_no: 160 | raise ValueError("Input is not a HEIF/AVIF file") 161 | elif filetype_check == _constants.heif_filetype_yes_unsupported: 162 | warnings.warn("Input is an unsupported HEIF/AVIF file type - trying anyway!") 163 | 164 | ctx = libheif.heif_context_alloc() 165 | collect = _keep_refs(libheif.heif_context_free, data=d) 166 | ctx = ffi.gc(ctx, collect, size=len(d)) 167 | 168 | error = libheif.heif_context_read_from_memory_without_copy(ctx, d, len(d), ffi.NULL) 169 | _assert_success(error) 170 | return ctx 171 | 172 | 173 | def _read_heif_container(ctx, apply_transformations, convert_hdr_to_8bit): 174 | image_count = libheif.heif_context_get_number_of_top_level_images(ctx) 175 | if image_count == 0: 176 | raise HeifNoImageError() 177 | 178 | ids = ffi.new("heif_item_id[]", image_count) 179 | image_count = libheif.heif_context_get_list_of_top_level_image_IDs( 180 | ctx, ids, image_count 181 | ) 182 | 183 | p_primary_image_id = ffi.new("heif_item_id *") 184 | error = libheif.heif_context_get_primary_image_ID(ctx, p_primary_image_id) 185 | _assert_success(error) 186 | primary_image_id = p_primary_image_id[0] 187 | primary_image = None 188 | top_level_images = [] 189 | 190 | for handle_id in ids: 191 | p_handle = ffi.new("struct heif_image_handle **") 192 | error = libheif.heif_context_get_image_handle(ctx, handle_id, p_handle) 193 | _assert_success(error) 194 | 195 | collect = _keep_refs(libheif.heif_image_handle_release, ctx=ctx) 196 | handle = ffi.gc(p_handle[0], collect) 197 | 198 | image = _read_heif_handle( 199 | ctx, handle, apply_transformations, convert_hdr_to_8bit 200 | ) 201 | 202 | is_primary = handle_id == primary_image_id 203 | 204 | depth_image = _read_depth_image( 205 | ctx, handle, apply_transformations, convert_hdr_to_8bit 206 | ) 207 | auxiliary_images = _read_all_auxiliary_images( 208 | ctx, handle, apply_transformations, convert_hdr_to_8bit 209 | ) 210 | 211 | top_level_image = HeifTopLevelImage( 212 | handle_id, image, is_primary, depth_image, auxiliary_images 213 | ) 214 | 215 | top_level_images.append(top_level_image) 216 | if is_primary: 217 | primary_image = top_level_image 218 | 219 | return HeifContainer(primary_image, top_level_images) 220 | 221 | 222 | def _read_heif_handle(ctx, handle, apply_transformations, convert_hdr_to_8bit): 223 | if apply_transformations: 224 | width = libheif.heif_image_handle_get_width(handle) 225 | height = libheif.heif_image_handle_get_height(handle) 226 | else: 227 | width = libheif.heif_image_handle_get_ispe_width(handle) 228 | height = libheif.heif_image_handle_get_ispe_height(handle) 229 | has_alpha = bool(libheif.heif_image_handle_has_alpha_channel(handle)) 230 | bit_depth = libheif.heif_image_handle_get_luma_bits_per_pixel(handle) 231 | 232 | transformations = _read_transformations(ctx, handle) 233 | metadata = _read_metadata(handle) 234 | color_profile = _read_color_profile(handle) 235 | 236 | heif_file = UndecodedHeifImage( 237 | ctx, 238 | handle, 239 | size=(width, height), 240 | has_alpha=has_alpha, 241 | bit_depth=bit_depth, 242 | transformations=transformations, 243 | metadata=metadata, 244 | color_profile=color_profile, 245 | apply_transformations=apply_transformations, 246 | convert_hdr_to_8bit=convert_hdr_to_8bit, 247 | ) 248 | return heif_file 249 | 250 | 251 | def _read_depth_image(ctx, handle, apply_transformations, convert_hdr_to_8bit): 252 | has_depth_image = libheif.heif_image_handle_has_depth_image(handle) 253 | if has_depth_image: 254 | p_depth_image_id = ffi.new("heif_item_id *") 255 | n_depth_images = libheif.heif_image_handle_get_list_of_depth_image_IDs( 256 | handle, p_depth_image_id, 1 257 | ) 258 | if n_depth_images == 1: 259 | depth_id = p_depth_image_id[0] 260 | p_depth_handle = ffi.new("struct heif_image_handle **") 261 | error = libheif.heif_image_handle_get_depth_image_handle( 262 | handle, depth_id, p_depth_handle 263 | ) 264 | _assert_success(error) 265 | collect = _keep_refs(libheif.heif_image_handle_release, handle=handle) 266 | depth_handle = ffi.gc(p_depth_handle[0], collect) 267 | return HeifDepthImage( 268 | depth_id, 269 | _read_heif_handle( 270 | ctx, depth_handle, apply_transformations, convert_hdr_to_8bit 271 | ), 272 | ) 273 | return None 274 | 275 | 276 | def _read_all_auxiliary_images(ctx, handle, apply_transformations, convert_hdr_to_8bit): 277 | aux_count = libheif.heif_image_handle_get_number_of_auxiliary_images( 278 | handle, 279 | _constants.LIBHEIF_AUX_IMAGE_FILTER_OMIT_ALPHA 280 | | _constants.LIBHEIF_AUX_IMAGE_FILTER_OMIT_DEPTH, 281 | ) 282 | if aux_count == 0: 283 | return [] 284 | aux_ids = ffi.new("heif_item_id[]", aux_count) 285 | aux_count = libheif.heif_image_handle_get_list_of_auxiliary_image_IDs( 286 | handle, 287 | _constants.LIBHEIF_AUX_IMAGE_FILTER_OMIT_ALPHA 288 | | _constants.LIBHEIF_AUX_IMAGE_FILTER_OMIT_DEPTH, 289 | aux_ids, 290 | aux_count, 291 | ) 292 | auxiliaries = [] 293 | for aux_id in aux_ids: 294 | aux_image = _read_auxiliary_image( 295 | ctx, handle, aux_id, apply_transformations, convert_hdr_to_8bit 296 | ) 297 | auxiliaries.append(aux_image) 298 | return auxiliaries 299 | 300 | 301 | def _read_auxiliary_image( 302 | ctx, handle, auxiliary_image_id, apply_transformations, convert_hdr_to_8bit 303 | ): 304 | p_aux_handle = ffi.new("struct heif_image_handle **") 305 | error = libheif.heif_image_handle_get_auxiliary_image_handle( 306 | handle, auxiliary_image_id, p_aux_handle 307 | ) 308 | _assert_success(error) 309 | 310 | collect = _keep_refs(libheif.heif_image_handle_release, handle=handle) 311 | aux_handle = ffi.gc(p_aux_handle[0], collect) 312 | 313 | p_aux_type = ffi.new("char **") 314 | error = libheif.heif_image_handle_get_auxiliary_type(aux_handle, p_aux_type) 315 | _assert_success(error) 316 | aux_type = ffi.string(p_aux_type[0]).decode() 317 | libheif.heif_image_handle_release_auxiliary_type(aux_handle, p_aux_type) 318 | 319 | return HeifAuxiliaryImage( 320 | auxiliary_image_id, 321 | aux_type, 322 | _read_heif_handle(ctx, aux_handle, apply_transformations, convert_hdr_to_8bit), 323 | ) 324 | 325 | 326 | def _read_transformations(ctx, handle): 327 | transformations = Transformations( 328 | libheif.heif_image_handle_get_ispe_width(handle), 329 | libheif.heif_image_handle_get_ispe_height(handle) 330 | ) 331 | item_id = libheif.heif_image_handle_get_item_id(handle) 332 | properties_count = libheif.heif_item_get_transformation_properties( 333 | ctx, item_id, ffi.NULL, 0 334 | ) 335 | if properties_count: 336 | properties = ffi.new("heif_property_id[]", properties_count) 337 | libheif.heif_item_get_transformation_properties( 338 | ctx, item_id, properties, properties_count 339 | ) 340 | for prop in properties: 341 | prop_type = libheif.heif_item_get_property_type(ctx, item_id, prop) 342 | if prop_type == _constants.heif_item_property_type_transform_mirror: 343 | mirror = libheif.heif_item_get_property_transform_mirror(ctx, item_id, prop) 344 | horizontal = mirror == _constants.heif_transform_mirror_direction_horizontal 345 | transformations.apply_orientation( 346 | flip_horizontal=horizontal, flip_vertical=not horizontal 347 | ) 348 | elif prop_type == _constants.heif_item_property_type_transform_rotation: 349 | rotate = libheif.heif_item_get_property_transform_rotation_ccw(ctx, item_id, prop) 350 | transformations.apply_orientation(turn_ccw=rotate // 90) 351 | elif prop_type == _constants.heif_item_property_type_transform_crop: 352 | crop = ffi.new("int[4]") 353 | libheif.heif_item_get_property_transform_crop_borders( 354 | ctx, item_id, prop, transformations.ispe_width, transformations.ispe_height, 355 | crop + 0, crop + 1, crop + 2, crop + 3 356 | ) 357 | crop[2] = transformations.ispe_width - crop[2] 358 | crop[3] = transformations.ispe_height - crop[3] 359 | transformations.apply_crop(*crop) 360 | return transformations 361 | 362 | 363 | def _read_metadata(handle): 364 | block_count = libheif.heif_image_handle_get_number_of_metadata_blocks( 365 | handle, ffi.NULL 366 | ) 367 | if block_count == 0: 368 | return 369 | 370 | metadata = [] 371 | ids = ffi.new("heif_item_id[]", block_count) 372 | libheif.heif_image_handle_get_list_of_metadata_block_IDs( 373 | handle, ffi.NULL, ids, block_count 374 | ) 375 | for i in range(len(ids)): 376 | metadata_type = libheif.heif_image_handle_get_metadata_type(handle, ids[i]) 377 | metadata_type = ffi.string(metadata_type).decode() 378 | data_length = libheif.heif_image_handle_get_metadata_size(handle, ids[i]) 379 | p_data = ffi.new("char[]", data_length) 380 | error = libheif.heif_image_handle_get_metadata(handle, ids[i], p_data) 381 | _assert_success(error) 382 | 383 | data_buffer = ffi.buffer(p_data, data_length) 384 | data = bytes(data_buffer) 385 | if metadata_type == "Exif": 386 | # skip TIFF header, first 4 bytes 387 | data = data[4:] 388 | metadata.append({"type": metadata_type, "data": data}) 389 | 390 | return metadata 391 | 392 | 393 | def _read_color_profile(handle): 394 | profile_type = libheif.heif_image_handle_get_color_profile_type(handle) 395 | if profile_type == _constants.heif_color_profile_type_not_present: 396 | return 397 | 398 | color_profile = {"type": "unknown", "data": None} 399 | if profile_type == _constants.heif_color_profile_type_nclx: 400 | color_profile["type"] = "nclx" 401 | data_length = ffi.sizeof("struct heif_color_profile_nclx") 402 | pp_data = ffi.new("struct heif_color_profile_nclx * *") 403 | error = libheif.heif_image_handle_get_nclx_color_profile(handle, pp_data) 404 | p_data = ffi.gc(pp_data[0], libheif.heif_nclx_color_profile_free) 405 | 406 | else: 407 | if profile_type == _constants.heif_color_profile_type_rICC: 408 | color_profile["type"] = "rICC" 409 | elif profile_type == _constants.heif_color_profile_type_prof: 410 | color_profile["type"] = "prof" 411 | data_length = libheif.heif_image_handle_get_raw_color_profile_size(handle) 412 | p_data = ffi.new("char[]", data_length) 413 | error = libheif.heif_image_handle_get_raw_color_profile(handle, p_data) 414 | 415 | _assert_success(error) 416 | data_buffer = ffi.buffer(p_data, data_length) 417 | data = bytes(data_buffer) 418 | color_profile["data"] = data 419 | 420 | return color_profile 421 | 422 | 423 | def _read_heif_image(handle, heif_file): 424 | colorspace = _constants.heif_colorspace_RGB 425 | if heif_file.convert_hdr_to_8bit or heif_file.bit_depth <= 8: 426 | if heif_file.has_alpha: 427 | chroma = _constants.heif_chroma_interleaved_RGBA 428 | else: 429 | chroma = _constants.heif_chroma_interleaved_RGB 430 | else: 431 | if heif_file.has_alpha: 432 | chroma = _constants.heif_chroma_interleaved_RRGGBBAA_BE 433 | else: 434 | chroma = _constants.heif_chroma_interleaved_RRGGBB_BE 435 | 436 | p_options = libheif.heif_decoding_options_alloc() 437 | p_options = ffi.gc(p_options, libheif.heif_decoding_options_free) 438 | p_options.ignore_transformations = int(not heif_file.apply_transformations) 439 | p_options.convert_hdr_to_8bit = int(heif_file.convert_hdr_to_8bit) 440 | 441 | p_img = ffi.new("struct heif_image **") 442 | error = libheif.heif_decode_image( 443 | handle, p_img, colorspace, chroma, p_options, 444 | ) 445 | _assert_success(error) 446 | 447 | img = p_img[0] 448 | 449 | p_stride = ffi.new("int *") 450 | p_data = libheif.heif_image_get_plane_readonly( 451 | img, _constants.heif_channel_interleaved, p_stride 452 | ) 453 | stride = p_stride[0] 454 | 455 | data_length = heif_file.size[1] * stride 456 | 457 | # Release image as soon as no references to p_data left 458 | collect = functools.partial(_release_heif_image, img) 459 | p_data = ffi.gc(p_data, collect, size=data_length) 460 | 461 | # ffi.buffer obligatory keeps a reference to p_data 462 | data_buffer = ffi.buffer(p_data, data_length) 463 | 464 | return data_buffer, stride 465 | 466 | 467 | def _release_heif_image(img, p_data=None): 468 | libheif.heif_image_release(img) 469 | -------------------------------------------------------------------------------- /pyheif/transformations.py: -------------------------------------------------------------------------------- 1 | class Transformations: 2 | """ 3 | Represents image transformation stored in irot, imir and clap boxes. 4 | Unlike boxes in the file, these operations have only one proper order: 5 | you always should crop the image first, then rotate according to orientation_tag. 6 | imir and irot boxes stored in single orientation_tag. orientation_tag have 7 | has the same meaning as orientation tag in EXIF (values from 1 to 8) 8 | or could be 0 is there is no irot or imir boxes. 9 | In general, you may transform the image according to this tag, 10 | and if orientation_tag is 0, apply the value from EXIF metadata. 11 | """ 12 | # EXIF orientation tag values decomposed by operations 13 | # 1: 0b000: NONE 14 | # 2: 0b001: FLIP_LEFT_RIGHT 15 | # 3: 0b011: ROTATE_180 16 | # 4: 0b010: FLIP_TOP_BOTTOM 17 | # 5: 0b100: TRANSPOSE 18 | # 6: 0b110: ROTATE_270_CCW 19 | # 7: 0b111: TRANSVERSE 20 | # 8: 0b101: ROTATE_90_CCW 21 | orientation_tag = 0 22 | crop = (0, 0, 1, 1) 23 | 24 | _tag_to_bitmask = [0b000, 0b000, 0b001, 0b011, 0b010, 0b100, 0b110, 0b111, 0b101] 25 | _bitmask_to_tag = [1, 2, 4, 3, 5, 8, 6, 7] 26 | _rotation_to_bitmask = [0b000, 0b101, 0b011, 0b110] 27 | 28 | def __init__(self, ispe_width, ispe_height): 29 | self.crop = (0, 0, ispe_width, ispe_height) 30 | self.ispe_width = ispe_width 31 | self.ispe_height = ispe_height 32 | 33 | def apply_orientation(self, *, turn_ccw=0, flip_horizontal=False, flip_vertical=False): 34 | """ 35 | :param turn_ccw: number of counterclockwise turns by 90 degrees. 36 | 0 is still image, 1 is 90 CCW, 2 it 180. 37 | :param flip_horizontal: flip horizontally after the turn. 38 | :param flip_vertical: flip vertically after the turn. 39 | """ 40 | operation = self._rotation_to_bitmask[turn_ccw & 0b011] 41 | if flip_horizontal: 42 | operation ^= 0b001 43 | if flip_vertical: 44 | operation ^= 0b010 45 | 46 | bitmask = self._tag_to_bitmask[self.orientation_tag] 47 | # If bitmask contatins transposition, we swap first two bits of operation 48 | if bitmask & 0b100: 49 | bit0 = operation & 0b001 50 | bit1 = operation & 0b010 51 | operation = (operation & 0b100) | (bit0 << 1) | (bit1 >> 1) 52 | 53 | # Apply this operation 54 | bitmask ^= operation 55 | 56 | self.orientation_tag = self._bitmask_to_tag[bitmask] 57 | 58 | def apply_crop(self, left, top, width, height): 59 | bitmask = self._tag_to_bitmask[self.orientation_tag] 60 | 61 | if bitmask & 0b100: 62 | left, top = top, left 63 | width, height = height, width 64 | if bitmask & 0b001: 65 | left = self.ispe_width - (left + width) 66 | if bitmask & 0b010: 67 | top = self.ispe_height - (top + height) 68 | 69 | left = max(0, min(self.ispe_width - 1, left)) 70 | top = max(0, min(self.ispe_height - 1, top)) 71 | width = max(0, min(self.ispe_width - left, width)) 72 | height = max(0, min(self.ispe_height - top, height)) 73 | 74 | self.crop = (left, top, width, height) 75 | 76 | def __eq__(self, other): 77 | return ( 78 | self.crop == other.crop and 79 | self.orientation_tag == other.orientation_tag 80 | ) 81 | -------------------------------------------------------------------------------- /pyheif/writer.py: -------------------------------------------------------------------------------- 1 | def write(): 2 | raise Exception("not implemented") 3 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | -r requirements-test.txt 2 | 3 | black==24.3.0 4 | pipdeptree==0.13.2 5 | setuptools==70.0.0 6 | -------------------------------------------------------------------------------- /requirements-publish.txt: -------------------------------------------------------------------------------- 1 | -r requirements-dev.txt 2 | 3 | cffi==1.15.0 4 | twine==3.7.1 5 | -------------------------------------------------------------------------------- /requirements-test.txt: -------------------------------------------------------------------------------- 1 | pytest==6.2.5 2 | piexif==1.1.3 3 | Pillow>=9.5.0; implementation_name != "pypy" or python_version != "3.7" 4 | Pillow==10.3.0; implementation_name == "pypy" and python_version == "3.7" 5 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | with open("README.md", "r") as fh: 4 | long_description = fh.read() 5 | 6 | with open("pyheif/data/version.txt") as f: 7 | version = f.read().strip() 8 | 9 | setup( 10 | name="pyheif", 11 | version=version, 12 | packages=["pyheif"], 13 | package_data={"pyheif": ["data/*"]}, 14 | install_requires=["cffi>=1.0.0"], 15 | setup_requires=["cffi>=1.0.0"], 16 | cffi_modules=["libheif/libheif_build.py:ffibuilder"], 17 | author="Anthony Paes", 18 | author_email="ant32bit-carsales@users.noreply.github.com", 19 | description="Python 3.6+ interface to libheif library", 20 | long_description=long_description, 21 | long_description_content_type="text/markdown", 22 | python_requires=">= 3.6", 23 | classifiers=[ 24 | "Programming Language :: Python :: 3", 25 | "License :: OSI Approved :: Apache Software License", 26 | "Operating System :: MacOS :: MacOS X", 27 | "Operating System :: POSIX :: Linux", 28 | ], 29 | keywords="heif heic", 30 | url="https://github.com/carsales/pyheif", 31 | ) 32 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/__init__.py -------------------------------------------------------------------------------- /tests/images/arrow.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/arrow.heic -------------------------------------------------------------------------------- /tests/images/avif-sample-images/LICENSE.txt: -------------------------------------------------------------------------------- 1 | Attribution-ShareAlike 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More_considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-ShareAlike 4.0 International Public 58 | License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-ShareAlike 4.0 International Public License ("Public 63 | License"). To the extent this Public License may be interpreted as a 64 | contract, You are granted the Licensed Rights in consideration of Your 65 | acceptance of these terms and conditions, and the Licensor grants You 66 | such rights in consideration of benefits the Licensor receives from 67 | making the Licensed Material available under these terms and 68 | conditions. 69 | 70 | 71 | Section 1 -- Definitions. 72 | 73 | a. Adapted Material means material subject to Copyright and Similar 74 | Rights that is derived from or based upon the Licensed Material 75 | and in which the Licensed Material is translated, altered, 76 | arranged, transformed, or otherwise modified in a manner requiring 77 | permission under the Copyright and Similar Rights held by the 78 | Licensor. For purposes of this Public License, where the Licensed 79 | Material is a musical work, performance, or sound recording, 80 | Adapted Material is always produced where the Licensed Material is 81 | synched in timed relation with a moving image. 82 | 83 | b. Adapter's License means the license You apply to Your Copyright 84 | and Similar Rights in Your contributions to Adapted Material in 85 | accordance with the terms and conditions of this Public License. 86 | 87 | c. BY-SA Compatible License means a license listed at 88 | creativecommons.org/compatiblelicenses, approved by Creative 89 | Commons as essentially the equivalent of this Public License. 90 | 91 | d. Copyright and Similar Rights means copyright and/or similar rights 92 | closely related to copyright including, without limitation, 93 | performance, broadcast, sound recording, and Sui Generis Database 94 | Rights, without regard to how the rights are labeled or 95 | categorized. For purposes of this Public License, the rights 96 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 97 | Rights. 98 | 99 | e. Effective Technological Measures means those measures that, in the 100 | absence of proper authority, may not be circumvented under laws 101 | fulfilling obligations under Article 11 of the WIPO Copyright 102 | Treaty adopted on December 20, 1996, and/or similar international 103 | agreements. 104 | 105 | f. Exceptions and Limitations means fair use, fair dealing, and/or 106 | any other exception or limitation to Copyright and Similar Rights 107 | that applies to Your use of the Licensed Material. 108 | 109 | g. License Elements means the license attributes listed in the name 110 | of a Creative Commons Public License. The License Elements of this 111 | Public License are Attribution and ShareAlike. 112 | 113 | h. Licensed Material means the artistic or literary work, database, 114 | or other material to which the Licensor applied this Public 115 | License. 116 | 117 | i. Licensed Rights means the rights granted to You subject to the 118 | terms and conditions of this Public License, which are limited to 119 | all Copyright and Similar Rights that apply to Your use of the 120 | Licensed Material and that the Licensor has authority to license. 121 | 122 | j. Licensor means the individual(s) or entity(ies) granting rights 123 | under this Public License. 124 | 125 | k. Share means to provide material to the public by any means or 126 | process that requires permission under the Licensed Rights, such 127 | as reproduction, public display, public performance, distribution, 128 | dissemination, communication, or importation, and to make material 129 | available to the public including in ways that members of the 130 | public may access the material from a place and at a time 131 | individually chosen by them. 132 | 133 | l. Sui Generis Database Rights means rights other than copyright 134 | resulting from Directive 96/9/EC of the European Parliament and of 135 | the Council of 11 March 1996 on the legal protection of databases, 136 | as amended and/or succeeded, as well as other essentially 137 | equivalent rights anywhere in the world. 138 | 139 | m. You means the individual or entity exercising the Licensed Rights 140 | under this Public License. Your has a corresponding meaning. 141 | 142 | 143 | Section 2 -- Scope. 144 | 145 | a. License grant. 146 | 147 | 1. Subject to the terms and conditions of this Public License, 148 | the Licensor hereby grants You a worldwide, royalty-free, 149 | non-sublicensable, non-exclusive, irrevocable license to 150 | exercise the Licensed Rights in the Licensed Material to: 151 | 152 | a. reproduce and Share the Licensed Material, in whole or 153 | in part; and 154 | 155 | b. produce, reproduce, and Share Adapted Material. 156 | 157 | 2. Exceptions and Limitations. For the avoidance of doubt, where 158 | Exceptions and Limitations apply to Your use, this Public 159 | License does not apply, and You do not need to comply with 160 | its terms and conditions. 161 | 162 | 3. Term. The term of this Public License is specified in Section 163 | 6(a). 164 | 165 | 4. Media and formats; technical modifications allowed. The 166 | Licensor authorizes You to exercise the Licensed Rights in 167 | all media and formats whether now known or hereafter created, 168 | and to make technical modifications necessary to do so. The 169 | Licensor waives and/or agrees not to assert any right or 170 | authority to forbid You from making technical modifications 171 | necessary to exercise the Licensed Rights, including 172 | technical modifications necessary to circumvent Effective 173 | Technological Measures. For purposes of this Public License, 174 | simply making modifications authorized by this Section 2(a) 175 | (4) never produces Adapted Material. 176 | 177 | 5. Downstream recipients. 178 | 179 | a. Offer from the Licensor -- Licensed Material. Every 180 | recipient of the Licensed Material automatically 181 | receives an offer from the Licensor to exercise the 182 | Licensed Rights under the terms and conditions of this 183 | Public License. 184 | 185 | b. Additional offer from the Licensor -- Adapted Material. 186 | Every recipient of Adapted Material from You 187 | automatically receives an offer from the Licensor to 188 | exercise the Licensed Rights in the Adapted Material 189 | under the conditions of the Adapter's License You apply. 190 | 191 | c. No downstream restrictions. You may not offer or impose 192 | any additional or different terms or conditions on, or 193 | apply any Effective Technological Measures to, the 194 | Licensed Material if doing so restricts exercise of the 195 | Licensed Rights by any recipient of the Licensed 196 | Material. 197 | 198 | 6. No endorsement. Nothing in this Public License constitutes or 199 | may be construed as permission to assert or imply that You 200 | are, or that Your use of the Licensed Material is, connected 201 | with, or sponsored, endorsed, or granted official status by, 202 | the Licensor or others designated to receive attribution as 203 | provided in Section 3(a)(1)(A)(i). 204 | 205 | b. Other rights. 206 | 207 | 1. Moral rights, such as the right of integrity, are not 208 | licensed under this Public License, nor are publicity, 209 | privacy, and/or other similar personality rights; however, to 210 | the extent possible, the Licensor waives and/or agrees not to 211 | assert any such rights held by the Licensor to the limited 212 | extent necessary to allow You to exercise the Licensed 213 | Rights, but not otherwise. 214 | 215 | 2. Patent and trademark rights are not licensed under this 216 | Public License. 217 | 218 | 3. To the extent possible, the Licensor waives any right to 219 | collect royalties from You for the exercise of the Licensed 220 | Rights, whether directly or through a collecting society 221 | under any voluntary or waivable statutory or compulsory 222 | licensing scheme. In all other cases the Licensor expressly 223 | reserves any right to collect such royalties. 224 | 225 | 226 | Section 3 -- License Conditions. 227 | 228 | Your exercise of the Licensed Rights is expressly made subject to the 229 | following conditions. 230 | 231 | a. Attribution. 232 | 233 | 1. If You Share the Licensed Material (including in modified 234 | form), You must: 235 | 236 | a. retain the following if it is supplied by the Licensor 237 | with the Licensed Material: 238 | 239 | i. identification of the creator(s) of the Licensed 240 | Material and any others designated to receive 241 | attribution, in any reasonable manner requested by 242 | the Licensor (including by pseudonym if 243 | designated); 244 | 245 | ii. a copyright notice; 246 | 247 | iii. a notice that refers to this Public License; 248 | 249 | iv. a notice that refers to the disclaimer of 250 | warranties; 251 | 252 | v. a URI or hyperlink to the Licensed Material to the 253 | extent reasonably practicable; 254 | 255 | b. indicate if You modified the Licensed Material and 256 | retain an indication of any previous modifications; and 257 | 258 | c. indicate the Licensed Material is licensed under this 259 | Public License, and include the text of, or the URI or 260 | hyperlink to, this Public License. 261 | 262 | 2. You may satisfy the conditions in Section 3(a)(1) in any 263 | reasonable manner based on the medium, means, and context in 264 | which You Share the Licensed Material. For example, it may be 265 | reasonable to satisfy the conditions by providing a URI or 266 | hyperlink to a resource that includes the required 267 | information. 268 | 269 | 3. If requested by the Licensor, You must remove any of the 270 | information required by Section 3(a)(1)(A) to the extent 271 | reasonably practicable. 272 | 273 | b. ShareAlike. 274 | 275 | In addition to the conditions in Section 3(a), if You Share 276 | Adapted Material You produce, the following conditions also apply. 277 | 278 | 1. The Adapter's License You apply must be a Creative Commons 279 | license with the same License Elements, this version or 280 | later, or a BY-SA Compatible License. 281 | 282 | 2. You must include the text of, or the URI or hyperlink to, the 283 | Adapter's License You apply. You may satisfy this condition 284 | in any reasonable manner based on the medium, means, and 285 | context in which You Share Adapted Material. 286 | 287 | 3. You may not offer or impose any additional or different terms 288 | or conditions on, or apply any Effective Technological 289 | Measures to, Adapted Material that restrict exercise of the 290 | rights granted under the Adapter's License You apply. 291 | 292 | 293 | Section 4 -- Sui Generis Database Rights. 294 | 295 | Where the Licensed Rights include Sui Generis Database Rights that 296 | apply to Your use of the Licensed Material: 297 | 298 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 299 | to extract, reuse, reproduce, and Share all or a substantial 300 | portion of the contents of the database; 301 | 302 | b. if You include all or a substantial portion of the database 303 | contents in a database in which You have Sui Generis Database 304 | Rights, then the database in which You have Sui Generis Database 305 | Rights (but not its individual contents) is Adapted Material, 306 | 307 | including for purposes of Section 3(b); and 308 | c. You must comply with the conditions in Section 3(a) if You Share 309 | all or a substantial portion of the contents of the database. 310 | 311 | For the avoidance of doubt, this Section 4 supplements and does not 312 | replace Your obligations under this Public License where the Licensed 313 | Rights include other Copyright and Similar Rights. 314 | 315 | 316 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 317 | 318 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 319 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 320 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 321 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 322 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 323 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 324 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 325 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 326 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 327 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 328 | 329 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 330 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 331 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 332 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 333 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 334 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 335 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 336 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 337 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 338 | 339 | c. The disclaimer of warranties and limitation of liability provided 340 | above shall be interpreted in a manner that, to the extent 341 | possible, most closely approximates an absolute disclaimer and 342 | waiver of all liability. 343 | 344 | 345 | Section 6 -- Term and Termination. 346 | 347 | a. This Public License applies for the term of the Copyright and 348 | Similar Rights licensed here. However, if You fail to comply with 349 | this Public License, then Your rights under this Public License 350 | terminate automatically. 351 | 352 | b. Where Your right to use the Licensed Material has terminated under 353 | Section 6(a), it reinstates: 354 | 355 | 1. automatically as of the date the violation is cured, provided 356 | it is cured within 30 days of Your discovery of the 357 | violation; or 358 | 359 | 2. upon express reinstatement by the Licensor. 360 | 361 | For the avoidance of doubt, this Section 6(b) does not affect any 362 | right the Licensor may have to seek remedies for Your violations 363 | of this Public License. 364 | 365 | c. For the avoidance of doubt, the Licensor may also offer the 366 | Licensed Material under separate terms or conditions or stop 367 | distributing the Licensed Material at any time; however, doing so 368 | will not terminate this Public License. 369 | 370 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 371 | License. 372 | 373 | 374 | Section 7 -- Other Terms and Conditions. 375 | 376 | a. The Licensor shall not be bound by any additional or different 377 | terms or conditions communicated by You unless expressly agreed. 378 | 379 | b. Any arrangements, understandings, or agreements regarding the 380 | Licensed Material not stated herein are separate from and 381 | independent of the terms and conditions of this Public License. 382 | 383 | 384 | Section 8 -- Interpretation. 385 | 386 | a. For the avoidance of doubt, this Public License does not, and 387 | shall not be interpreted to, reduce, limit, restrict, or impose 388 | conditions on any use of the Licensed Material that could lawfully 389 | be made without permission under this Public License. 390 | 391 | b. To the extent possible, if any provision of this Public License is 392 | deemed unenforceable, it shall be automatically reformed to the 393 | minimum extent necessary to make it enforceable. If the provision 394 | cannot be reformed, it shall be severed from this Public License 395 | without affecting the enforceability of the remaining terms and 396 | conditions. 397 | 398 | c. No term or condition of this Public License will be waived and no 399 | failure to comply consented to unless expressly agreed to by the 400 | Licensor. 401 | 402 | d. Nothing in this Public License constitutes or may be interpreted 403 | as a limitation upon, or waiver of, any privileges and immunities 404 | that apply to the Licensor or You, including from the legal 405 | processes of any jurisdiction or authority. 406 | 407 | 408 | ======================================================================= 409 | 410 | Creative Commons is not a party to its public 411 | licenses. Notwithstanding, Creative Commons may elect to apply one of 412 | its public licenses to material it publishes and in those instances 413 | will be considered the “Licensor.” The text of the Creative Commons 414 | public licenses is dedicated to the public domain under the CC0 Public 415 | Domain Dedication. Except for the limited purpose of indicating that 416 | material is shared under a Creative Commons public license or as 417 | otherwise permitted by the Creative Commons policies published at 418 | creativecommons.org/policies, Creative Commons does not authorize the 419 | use of the trademark "Creative Commons" or any other trademark or logo 420 | of Creative Commons without its prior written consent including, 421 | without limitation, in connection with any unauthorized modifications 422 | to any of its public licenses or any other arrangements, 423 | understandings, or agreements concerning use of licensed material. For 424 | the avoidance of doubt, this paragraph does not form part of the 425 | public licenses. 426 | 427 | Creative Commons may be contacted at creativecommons.org. -------------------------------------------------------------------------------- /tests/images/avif-sample-images/README.txt: -------------------------------------------------------------------------------- 1 | AVIF files samples from https://github.com/link-u/avif-sample-images 2 | 3 | Author: Kaede Fujisaki (https://github.com/ledyba) 4 | Retrieved from https://hexe.net/2017/12/02/16:33:53/ 5 | -------------------------------------------------------------------------------- /tests/images/avif-sample-images/fox.profile0.10bpc.yuv420.avif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/avif-sample-images/fox.profile0.10bpc.yuv420.avif -------------------------------------------------------------------------------- /tests/images/avif-sample-images/fox.profile0.10bpc.yuv420.monochrome.avif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/avif-sample-images/fox.profile0.10bpc.yuv420.monochrome.avif -------------------------------------------------------------------------------- /tests/images/avif-sample-images/fox.profile0.8bpc.yuv420.avif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/avif-sample-images/fox.profile0.8bpc.yuv420.avif -------------------------------------------------------------------------------- /tests/images/avif-sample-images/fox.profile0.8bpc.yuv420.monochrome.avif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/avif-sample-images/fox.profile0.8bpc.yuv420.monochrome.avif -------------------------------------------------------------------------------- /tests/images/avif-sample-images/fox.profile1.10bpc.yuv444.avif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/avif-sample-images/fox.profile1.10bpc.yuv444.avif -------------------------------------------------------------------------------- /tests/images/avif-sample-images/fox.profile1.8bpc.yuv444.avif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/avif-sample-images/fox.profile1.8bpc.yuv444.avif -------------------------------------------------------------------------------- /tests/images/avif-sample-images/fox.profile2.10bpc.yuv422.avif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/avif-sample-images/fox.profile2.10bpc.yuv422.avif -------------------------------------------------------------------------------- /tests/images/avif-sample-images/fox.profile2.10bpc.yuv422.monochrome.avif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/avif-sample-images/fox.profile2.10bpc.yuv422.monochrome.avif -------------------------------------------------------------------------------- /tests/images/avif-sample-images/fox.profile2.12bpc.yuv420.avif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/avif-sample-images/fox.profile2.12bpc.yuv420.avif -------------------------------------------------------------------------------- /tests/images/avif-sample-images/fox.profile2.12bpc.yuv420.monochrome.avif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/avif-sample-images/fox.profile2.12bpc.yuv420.monochrome.avif -------------------------------------------------------------------------------- /tests/images/avif-sample-images/fox.profile2.12bpc.yuv422.avif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/avif-sample-images/fox.profile2.12bpc.yuv422.avif -------------------------------------------------------------------------------- /tests/images/avif-sample-images/fox.profile2.12bpc.yuv422.monochrome.avif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/avif-sample-images/fox.profile2.12bpc.yuv422.monochrome.avif -------------------------------------------------------------------------------- /tests/images/avif-sample-images/fox.profile2.12bpc.yuv444.avif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/avif-sample-images/fox.profile2.12bpc.yuv444.avif -------------------------------------------------------------------------------- /tests/images/avif-sample-images/fox.profile2.12bpc.yuv444.monochrome.avif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/avif-sample-images/fox.profile2.12bpc.yuv444.monochrome.avif -------------------------------------------------------------------------------- /tests/images/avif-sample-images/fox.profile2.8bpc.yuv422.avif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/avif-sample-images/fox.profile2.8bpc.yuv422.avif -------------------------------------------------------------------------------- /tests/images/avif-sample-images/fox.profile2.8bpc.yuv422.monochrome.avif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/avif-sample-images/fox.profile2.8bpc.yuv422.monochrome.avif -------------------------------------------------------------------------------- /tests/images/hif/93FG5559.HIF: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/hif/93FG5559.HIF -------------------------------------------------------------------------------- /tests/images/hif/93FG5564.HIF: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/hif/93FG5564.HIF -------------------------------------------------------------------------------- /tests/images/hif/COPYRIGHT: -------------------------------------------------------------------------------- 1 | The images in this directory are the copyright of Fred Greaves 2 | 3 | -------------------------------------------------------------------------------- /tests/images/hif/README: -------------------------------------------------------------------------------- 1 | Sample 10-bit HEIC images from a Canon 1D X Mark III 2 | 3 | -------------------------------------------------------------------------------- /tests/images/iPhoneXR.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/iPhoneXR.heic -------------------------------------------------------------------------------- /tests/images/lego.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/lego.heic -------------------------------------------------------------------------------- /tests/images/live-image.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/live-image.heic -------------------------------------------------------------------------------- /tests/images/multiimage.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/multiimage.heic -------------------------------------------------------------------------------- /tests/images/nokia/COPYRIGHT: -------------------------------------------------------------------------------- 1 | All the example files in this directory are under copyright © 2017-2020 Nokia Corporation and/or its subsidiary(-ies) 2 | 3 | -------------------------------------------------------------------------------- /tests/images/nokia/README: -------------------------------------------------------------------------------- 1 | Example HEIC files from https://nokiatech.github.io/heif/examples.html 2 | 3 | -------------------------------------------------------------------------------- /tests/images/nokia/alpha/alpha_1440x960.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/alpha/alpha_1440x960.heic -------------------------------------------------------------------------------- /tests/images/nokia/bothie/bothie_1440x960.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/bothie/bothie_1440x960.heic -------------------------------------------------------------------------------- /tests/images/nokia/burst/bird_burst.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/burst/bird_burst.heic -------------------------------------------------------------------------------- /tests/images/nokia/burst/rally_burst.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/burst/rally_burst.heic -------------------------------------------------------------------------------- /tests/images/nokia/collection/random_collection_1440x960.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/collection/random_collection_1440x960.heic -------------------------------------------------------------------------------- /tests/images/nokia/collection/season_collection_1440x960.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/collection/season_collection_1440x960.heic -------------------------------------------------------------------------------- /tests/images/nokia/grid/grid_960x640.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/grid/grid_960x640.heic -------------------------------------------------------------------------------- /tests/images/nokia/overlay/overlay_1000x680.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/overlay/overlay_1000x680.heic -------------------------------------------------------------------------------- /tests/images/nokia/sequence/sea1_animation.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/sequence/sea1_animation.heic -------------------------------------------------------------------------------- /tests/images/nokia/sequence/starfield_animation.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/sequence/starfield_animation.heic -------------------------------------------------------------------------------- /tests/images/nokia/stereo/stereo_1200x800.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/stereo/stereo_1200x800.heic -------------------------------------------------------------------------------- /tests/images/nokia/still/autumn_1440x960.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/still/autumn_1440x960.heic -------------------------------------------------------------------------------- /tests/images/nokia/still/cheers_1440x960.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/still/cheers_1440x960.heic -------------------------------------------------------------------------------- /tests/images/nokia/still/crowd_1440x960.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/still/crowd_1440x960.heic -------------------------------------------------------------------------------- /tests/images/nokia/still/old_bridge_1440x960.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/still/old_bridge_1440x960.heic -------------------------------------------------------------------------------- /tests/images/nokia/still/ski_jump_1440x960.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/still/ski_jump_1440x960.heic -------------------------------------------------------------------------------- /tests/images/nokia/still/spring_1440x960.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/still/spring_1440x960.heic -------------------------------------------------------------------------------- /tests/images/nokia/still/summer_1440x960.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/still/summer_1440x960.heic -------------------------------------------------------------------------------- /tests/images/nokia/still/surfer_1440x960.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/still/surfer_1440x960.heic -------------------------------------------------------------------------------- /tests/images/nokia/still/winter_1440x960.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/still/winter_1440x960.heic -------------------------------------------------------------------------------- /tests/images/nokia/udes/lights_1440x960.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/nokia/udes/lights_1440x960.heic -------------------------------------------------------------------------------- /tests/images/parfait.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/parfait.heic -------------------------------------------------------------------------------- /tests/images/tree-with-transforms.avif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/tree-with-transforms.avif -------------------------------------------------------------------------------- /tests/images/tree-with-transparency.heic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carsales/pyheif/4cf1fdef621b8afe3a4065e4883ab23d021f4cc6/tests/images/tree-with-transparency.heic -------------------------------------------------------------------------------- /tests/test_read.py: -------------------------------------------------------------------------------- 1 | import gc 2 | import glob 3 | import io 4 | from pathlib import Path 5 | 6 | import piexif 7 | from PIL import Image, ImageCms 8 | import pyheif.reader 9 | import pytest 10 | 11 | 12 | heic_files = list(Path().glob("tests/images/**/*.heic")) 13 | hif_files = list(Path().glob("tests/images/**/*.HIF")) 14 | avif_files = list(Path().glob("tests/images/**/*.avif")) 15 | heif_files = heic_files + hif_files + avif_files 16 | 17 | 18 | def create_pillow_image(heif_file): 19 | heif_file = heif_file.load() 20 | return Image.frombytes( 21 | heif_file.mode, 22 | heif_file.size, 23 | heif_file.data, 24 | "raw", 25 | heif_file.mode, 26 | heif_file.stride, 27 | ) 28 | 29 | 30 | @pytest.mark.parametrize("path", heif_files) 31 | def test_check(path): 32 | filetype = pyheif.check(path) 33 | assert pyheif.heif_filetype_no != filetype 34 | 35 | 36 | @pytest.mark.parametrize("path", heif_files[:2]) 37 | def test_get_bytes_from_path(path): 38 | d = pyheif.reader._get_bytes(path) 39 | assert d == path.read_bytes() 40 | 41 | 42 | @pytest.mark.parametrize("path", heif_files[:2]) 43 | def test_get_bytes_from_file_name(path): 44 | d = pyheif.reader._get_bytes(str(path)) 45 | assert d == path.read_bytes() 46 | 47 | 48 | @pytest.mark.parametrize("path", heif_files[:2]) 49 | def test_get_bytes_from_file_object(path): 50 | with open(path, "rb") as f: 51 | d = pyheif.reader._get_bytes(f) 52 | assert d == path.read_bytes() 53 | 54 | 55 | @pytest.mark.parametrize("path", heif_files[:2]) 56 | def test_get_bytes_from_bytes(path): 57 | with open(path, "rb") as f: 58 | d = pyheif.reader._get_bytes(f.read()) 59 | assert d == path.read_bytes() 60 | 61 | 62 | @pytest.mark.parametrize("path", heif_files[:2]) 63 | def test_get_bytes_from_bytes(path): 64 | with open(path, "rb") as f: 65 | d = pyheif.reader._get_bytes(bytearray(f.read())) 66 | assert d == path.read_bytes() 67 | 68 | 69 | @pytest.fixture(scope="session", params=heif_files) 70 | def heif_file(request): 71 | return pyheif.read(request.param) 72 | 73 | 74 | def test_check_heif_properties(heif_file): 75 | assert heif_file is not None 76 | width, height = heif_file.size 77 | assert width > 0 78 | assert height > 0 79 | assert len(heif_file.data) > 0 80 | 81 | 82 | def test_read_exif_metadata(heif_file): 83 | for m in heif_file.metadata or []: 84 | if m["type"] == "Exif": 85 | exif_dict = piexif.load(m["data"]) 86 | assert "0th" in exif_dict 87 | assert len(exif_dict["0th"]) > 0 88 | assert "Exif" in exif_dict 89 | assert len(exif_dict["Exif"]) > 0 90 | 91 | 92 | def test_read_icc_color_profile(heif_file): 93 | if heif_file.color_profile and heif_file.color_profile["type"] in ["prof", "rICC"]: 94 | profile = io.BytesIO(heif_file.color_profile["data"]) 95 | cms = ImageCms.getOpenProfile(profile) 96 | 97 | 98 | def test_read_pillow_frombytes(heif_file): 99 | create_pillow_image(heif_file) 100 | 101 | 102 | def apply_transformations(im, transformations): 103 | im = im.crop(transformations.crop) 104 | method = { 105 | 2: Image.Transpose.FLIP_LEFT_RIGHT, 106 | 3: Image.Transpose.ROTATE_180, 107 | 4: Image.Transpose.FLIP_TOP_BOTTOM, 108 | 5: Image.Transpose.TRANSPOSE, 109 | 6: Image.Transpose.ROTATE_270, 110 | 7: Image.Transpose.TRANSVERSE, 111 | 8: Image.Transpose.ROTATE_90, 112 | }.get(transformations.orientation_tag) 113 | if method: 114 | im = im.transpose(method) 115 | return im 116 | 117 | 118 | @pytest.mark.parametrize("path", [ 119 | "tests/images/parfait.heic", # orientation 120 | "tests/images/tree-with-transforms.avif", # orientation + crop 121 | "tests/images/tree-with-transparency.heic", # to transformations 122 | ]) 123 | def test_read_transformations(path): 124 | heif_native = pyheif.open(path, apply_transformations=False) 125 | width, height = heif_native.size 126 | 127 | orientation_tag = heif_native.transformations.orientation_tag 128 | assert 0 <= orientation_tag <= 8 129 | 130 | crop = heif_native.transformations.crop 131 | assert 0 <= crop[0] < width 132 | assert 0 <= crop[1] < height 133 | assert 1 <= crop[2] <= width - crop[0] 134 | assert 1 <= crop[3] <= height - crop[1] 135 | 136 | heif_transformed = pyheif.open(path) 137 | assert heif_native.transformations == heif_transformed.transformations 138 | 139 | native = apply_transformations( 140 | create_pillow_image(heif_native), 141 | heif_native.transformations 142 | ) 143 | transformed = create_pillow_image(heif_transformed) 144 | assert native == transformed 145 | 146 | 147 | @pytest.mark.parametrize("path", heif_files) 148 | def test_open_and_load(path): 149 | heif_file = pyheif.open(path) 150 | assert heif_file.size[0] > 0 151 | assert heif_file.size[1] > 0 152 | assert heif_file.has_alpha is not None 153 | assert heif_file.mode is not None 154 | assert heif_file.bit_depth is not None 155 | 156 | assert heif_file.data is None 157 | assert heif_file.stride is None 158 | 159 | if path.name == "arrow.heic": 160 | assert heif_file.metadata 161 | assert heif_file.color_profile 162 | 163 | res = heif_file.load() 164 | assert heif_file is res 165 | assert heif_file.data is not None 166 | assert heif_file.stride is not None 167 | assert len(heif_file.data) >= heif_file.stride * heif_file.size[1] 168 | assert type(heif_file.data[:100]) == bytes 169 | 170 | # Subsequent calls don't change anything 171 | res = heif_file.load() 172 | assert heif_file is res 173 | assert heif_file.data is not None 174 | assert heif_file.stride is not None 175 | 176 | 177 | @pytest.mark.parametrize("path", heif_files) 178 | def test_open_and_load_data_not_collected(path): 179 | data = path.read_bytes() 180 | heif_file = pyheif.open(data) 181 | 182 | # heif_file.load() should work even if there is no other refs 183 | # to the source data. 184 | data = None 185 | gc.collect() 186 | 187 | heif_file.load() 188 | 189 | 190 | @pytest.mark.parametrize("path", heif_files) 191 | def test_open_container(path): 192 | container = pyheif.open_container(path) 193 | assert container is not None 194 | assert container.primary_image is not None 195 | assert len(container.top_level_images) > 0 196 | 197 | if path.name == "multiimage.heic": 198 | assert len(container.top_level_images) == 5 199 | 200 | n_primary_images = 0 201 | for top_level_image in container.top_level_images: 202 | if top_level_image.is_primary: 203 | n_primary_images += 1 204 | assert container.primary_image == top_level_image 205 | top_level_image.image.load() 206 | test_check_heif_properties(top_level_image.image) 207 | test_read_pillow_frombytes(top_level_image.image) 208 | assert n_primary_images == 1 209 | 210 | if path.name == "live-image.heic": 211 | top_level_image = container.top_level_images[0] 212 | assert len(top_level_image.auxiliary_images) == 1 213 | 214 | auxiliary_image = top_level_image.auxiliary_images[0] 215 | assert auxiliary_image.type == "urn:com:apple:photo:2020:aux:hdrgainmap" 216 | 217 | auxiliary_image.image.load() 218 | test_check_heif_properties(auxiliary_image.image) 219 | test_read_pillow_frombytes(auxiliary_image.image) 220 | 221 | 222 | def test_no_transformations(): 223 | transformed = pyheif.read("tests/images/arrow.heic") 224 | native = pyheif.read("tests/images/arrow.heic", apply_transformations=False) 225 | assert transformed.size[0] != transformed.size[1] 226 | assert transformed.size == native.size[::-1] 227 | 228 | transformed = create_pillow_image(transformed) 229 | native = create_pillow_image(native) 230 | 231 | assert transformed == native.transpose(Image.ROTATE_270) 232 | -------------------------------------------------------------------------------- /tests/test_versions.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | sys.path.insert(0, os.path.abspath(".")) 5 | 6 | import pyheif 7 | 8 | 9 | def test_libheif_version(): 10 | version = pyheif.libheif_version() 11 | assert version != "" 12 | 13 | 14 | def test_pyheif_version(): 15 | with open("pyheif/data/version.txt") as f: 16 | expected_version = f.read().strip() 17 | 18 | version = pyheif.__version__ 19 | assert expected_version == version 20 | -------------------------------------------------------------------------------- /tools/freeze-deps.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | pipdeptree -f --warn silence | ggrep -P '^[\w0-9\-=.]+' > requirements-dev.txt 4 | 5 | -------------------------------------------------------------------------------- /tools/git-push.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | git add -A . 4 | git commit -a -m "$1" 5 | git push 6 | -------------------------------------------------------------------------------- /tools/pypi-publish.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | rm dist/* 4 | python setup.py sdist 5 | twine upload dist/* 6 | --------------------------------------------------------------------------------