pax_global_header 0000666 0000000 0000000 00000000064 15226316512 0014515 g ustar 00root root 0000000 0000000 52 comment=9d817d185f7f77ebcc0356ed4f36bbed9ccd484f
pillow-jpegxl-plugin-1.3.8/ 0000775 0000000 0000000 00000000000 15226316512 0015617 5 ustar 00root root 0000000 0000000 pillow-jpegxl-plugin-1.3.8/.github/ 0000775 0000000 0000000 00000000000 15226316512 0017157 5 ustar 00root root 0000000 0000000 pillow-jpegxl-plugin-1.3.8/.github/dependabot.yml 0000664 0000000 0000000 00000000704 15226316512 0022010 0 ustar 00root root 0000000 0000000 # Basic set up for Cargo projects
---
version: 2
updates:
# Maintain dependencies for GitHub Actions
- package-ecosystem: "github-actions"
directory: /
schedule:
interval: "weekly"
commit-message:
prefix: "�👷 "
include: scope
# Maintain dependencies for Cargo
- package-ecosystem: cargo
directory: /
schedule:
interval: weekly
commit-message:
prefix: "⬆� "
include: scope
pillow-jpegxl-plugin-1.3.8/.github/workflows/ 0000775 0000000 0000000 00000000000 15226316512 0021214 5 ustar 00root root 0000000 0000000 pillow-jpegxl-plugin-1.3.8/.github/workflows/benchmarks.yml 0000664 0000000 0000000 00000007147 15226316512 0024065 0 ustar 00root root 0000000 0000000 name: Benchmarks
on:
# Trigger the workflow on push or pull request,
# but only for the main branch
push:
branches:
- main
pull_request:
branches:
- main
env:
RUSTFLAGS: -C debuginfo=0 # Do not produce debug symbols to keep memory usage down
RUST_BACKTRACE: 1
jobs:
windows:
runs-on: windows-latest
strategy:
fail-fast: false
matrix:
# we only use macos for fast testing
features: ["vendored", "dynamic"]
python-version: ['3.13']
steps:
- uses: actions/checkout@v7
with:
submodules: recursive
- name: Install libjxl
uses: msys2/setup-msys2@v2
with:
update: true
install: >-
mingw-w64-x86_64-toolchain
mingw-w64-x86_64-libjxl
- name: Put MSYS2_MinGW64 on PATH
# there is not yet an environment variable for this path from msys2/setup-msys2
run: echo "${{ runner.temp }}/msys64/mingw64/bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
- name: Set up Python
uses: actions/setup-python@v6
with:
python-version: ${{ matrix.python-version }}
- name: Create virtual environment
run: python -m venv .venv
- name: Build dynamic linking wheel
if: ${{ matrix.features == 'dynamic' }}
uses: PyO3/maturin-action@v1
env:
RUST_BACKTRACE: 1
with:
rust-toolchain: stable-x86_64-pc-windows-gnu
target: x86_64-pc-windows-gnu
args: --release --out ./ -i 3.13 --features dynamic
sccache: 'true'
- name: Run benchmarks scripts (dynamic)
if: ${{ matrix.features == 'dynamic' }}
run: |
.venv/Scripts/activate
python -m pip install delvewheel
delvewheel repair pillow_jxl_plugin-1.3.8-cp313-cp313-win_amd64.whl
python -m pip install ./wheelhouse/pillow_jxl_plugin-1.3.8-cp313-cp313-win_amd64.whl
python benchmarks/benchmarks_encode.py -i test/images/bench.png -o benchmarks-results-${{ matrix.os }}-${{ matrix.features }}-py${{ matrix.python-version }}.json
- name: Run benchmarks scripts (vendored)
if: ${{ matrix.features == 'vendored' }}
run: |
.venv/Scripts/activate
python -m pip install -e . -v
python benchmarks/benchmarks_encode.py -i test/images/bench.png -o benchmarks-results-${{ matrix.os }}-${{ matrix.features }}-py${{ matrix.python-version }}.json
- name: Upload pytest test results
uses: actions/upload-artifact@v7
with:
name: benchmarks-results-${{ matrix.os }}-${{ matrix.features }}-py${{ matrix.python-version }}
path: benchmarks-results-${{ matrix.os }}-${{ matrix.features }}-py${{ matrix.python-version }}.json
# Use always() to always run this step to publish test results when there are test failures
if: ${{ always() }}
macos:
runs-on: macos-latest
strategy:
fail-fast: false
matrix:
python-version: ['3.13']
steps:
- uses: actions/checkout@v7
with:
submodules: recursive
- name: Set up libjxl
run: brew install jpeg-xl
- name: Set up Python
uses: actions/setup-python@v6
with:
python-version: ${{ matrix.python-version }}
- name: Run benchmarks scripts (MacOS)
run: |
python -m venv .venv
source .venv/bin/activate
python -m pip install -e . -v
python benchmarks/benchmarks_encode.py -i test/images/bench.png -o benchmarks-results-${{ matrix.os }}-py${{ matrix.python-version }}.json
pillow-jpegxl-plugin-1.3.8/.github/workflows/pre-commit.yml 0000664 0000000 0000000 00000001027 15226316512 0024013 0 ustar 00root root 0000000 0000000 name: pre-commit
on:
pull_request:
push:
branches: [main]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
permissions:
contents: read
jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v6
with:
python-version: "3.12"
cache: 'pip'
- uses: pre-commit/action@v3.0.1
with:
extra_args: --all-files --hook-stage manual
pillow-jpegxl-plugin-1.3.8/.github/workflows/release.yml 0000664 0000000 0000000 00000020637 15226316512 0023367 0 ustar 00root root 0000000 0000000 # This file is autogenerated by maturin v1.7.4
# To update, run
#
# maturin generate-ci github
#
name: Release
on:
push:
branches:
- main
tags:
- '*'
pull_request:
branches:
- main
workflow_dispatch:
permissions:
contents: read
jobs:
linux:
runs-on: ${{ matrix.platform.runner }}
env:
MATURIN_INTERPRETERS: "3.10 3.11 3.12 3.13 3.14 pypy3.11"
strategy:
matrix:
platform:
- runner: ubuntu-latest
target: x86_64
- runner: ubuntu-latest
target: x86
- runner: ubuntu-24.04-arm
target: aarch64
# - runner: ubuntu-latest
# target: armv7
# - runner: ubuntu-latest
# target: s390x
# - runner: ubuntu-latest
# target: ppc64le
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v6
with:
python-version: 3.x
# - name: Setup QEMU
# if: ${{ matrix.platform.target != 'x86_64' && matrix.platform.target != 'x86' }}
# uses: docker/setup-qemu-action@v4
- name: Build wheels
uses: PyO3/maturin-action@v1
with:
target: ${{ matrix.platform.target }}
args: --release --out dist --interpreter ${{ env.MATURIN_INTERPRETERS }} --features vendored
sccache: 'true'
manylinux: auto
- name: Upload wheels
uses: actions/upload-artifact@v7
with:
name: wheels-linux-${{ matrix.platform.target }}
path: dist
musllinux:
runs-on: ${{ matrix.platform.runner }}
env:
MATURIN_INTERPRETERS: "3.10 3.11 3.12 3.13 3.14 pypy3.11"
strategy:
matrix:
platform:
- runner: ubuntu-latest
target: x86_64
- runner: ubuntu-latest
target: x86
- runner: ubuntu-latest
target: aarch64
- runner: ubuntu-latest
target: armv7
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v6
with:
python-version: 3.x
- name: Setup QEMU
if: ${{ matrix.platform.target != 'x86_64' && matrix.platform.target != 'x86' }}
uses: docker/setup-qemu-action@v4
- name: Build wheels
uses: PyO3/maturin-action@v1
with:
target: ${{ matrix.platform.target }}
args: --release --out dist --interpreter ${{ env.MATURIN_INTERPRETERS }} --features vendored
sccache: 'true'
manylinux: musllinux_1_2
- name: Upload wheels
uses: actions/upload-artifact@v7
with:
name: wheels-musllinux-${{ matrix.platform.target }}
path: dist
windows:
runs-on: ${{ matrix.platform.runner }}
strategy:
matrix:
platform:
- runner: windows-latest
target: x64
toolchain: x86_64-pc-windows-gnu
features: dynamic
python-versions: |
3.10
3.11
3.12
3.13
3.14
- runner: windows-latest
target: x86
toolchain: i686-pc-windows-gnu
features: dynamic
python-versions: |
3.10
3.11
3.12
3.13
3.14
- runner: windows-11-arm
target: aarch64
toolchain: aarch64-pc-windows-msvc
features: vendored
python-versions: |
3.11
3.12
3.13
3.14
steps:
- uses: actions/checkout@v7
- name: Install msys2 dependencys for x64
uses: msys2/setup-msys2@v2
if: ${{ matrix.platform.target == 'x64' }}
with:
update: true
install: >-
mingw-w64-x86_64-toolchain
mingw-w64-x86_64-libjxl
- name: Install msys2 dependencys for x86
uses: msys2/setup-msys2@v2
if: ${{ matrix.platform.target == 'x86' }}
with:
update: true
install: >-
mingw-w64-i686-toolchain
mingw-w64-i686-libjxl
- name: Put MSYS2_MinGW64 on PATH
# there is not yet an environment variable for this path from msys2/setup-msys2
if: ${{ matrix.platform.target == 'x64' }}
run: echo "${{ runner.temp }}/msys64/mingw64/bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
- name: Put MSYS2_MinGW32 on PATH
# there is not yet an environment variable for this path from msys2/setup-msys2
if: ${{ matrix.platform.target == 'x86' }}
run: echo "${{ runner.temp }}/msys64/mingw32/bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
- name: Setup Python
uses: actions/setup-python@v6
with:
python-version: ${{ matrix.platform.python-versions }}
architecture: ${{ matrix.platform.target == 'aarch64' && 'arm64' || matrix.platform.target }}
- name: Build wheels
uses: PyO3/maturin-action@v1
with:
rust-toolchain: stable-${{ matrix.platform.toolchain }}
target: ${{ matrix.platform.toolchain }}
args: --release --out dist --find-interpreter --features ${{ matrix.platform.features }}
sccache: 'true'
- name: Fix wheels with delvewheel
if: ${{ matrix.platform.features == 'dynamic' }}
run: |
pip install delvewheel
Get-ChildItem ${{ github.workspace }}/dist/*.whl | ForEach-Object -Process {delvewheel repair $PSItem -w dist}
- name: Upload wheels
uses: actions/upload-artifact@v7
with:
name: wheels-windows-${{ matrix.platform.target }}
path: dist
macos:
runs-on: ${{ matrix.platform.runner }}
env:
MATURIN_INTERPRETERS: "3.10 3.11 3.12 3.13 3.14 pypy3.11"
strategy:
matrix:
platform:
- runner: macos-latest
target: aarch64
- runner: macos-15-intel
target: x86_64
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v6
with:
python-version: 3.x
- name: Build wheels
uses: PyO3/maturin-action@v1
with:
target: ${{ matrix.platform.target }}
args: --release --out dist --interpreter ${{ env.MATURIN_INTERPRETERS }} --features vendored
sccache: 'true'
- name: Upload wheels
uses: actions/upload-artifact@v7
with:
name: wheels-macos-${{ matrix.platform.target }}
path: dist
sdist:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- name: Build sdist
uses: PyO3/maturin-action@v1
with:
command: sdist
args: --out dist
- name: Upload sdist
uses: actions/upload-artifact@v7
with:
name: wheels-sdist
path: dist
release:
name: Release
runs-on: ubuntu-latest
if: ${{ startsWith(github.ref, 'refs/tags/') || github.event_name == 'workflow_dispatch' }}
needs: [linux, musllinux, windows, macos, sdist]
permissions:
# Use to sign the release artifacts
id-token: write
# Used to upload release artifacts
contents: write
# Used to generate artifact attestation
attestations: write
steps:
- uses: actions/download-artifact@v8
- name: Generate artifact attestation
uses: actions/attest-build-provenance@v4
with:
subject-path: 'wheels-*/*'
- name: upload to github release
uses: softprops/action-gh-release@v3
with:
files: |
wheels-*/*.whl
prerelease: ${{ contains(github.ref, 'alpha') || contains(github.ref, 'beta') || contains(github.ref, 'dev') }}
- name: Publish to TestPyPI
if: ${{ contains(github.ref, 'alpha') || contains(github.ref, 'beta') || contains(github.ref, 'dev') }}
uses: PyO3/maturin-action@v1
env:
MATURIN_PYPI_TOKEN: ${{ secrets.TESTPYPI_API_TOKEN }}
MATURIN_REPOSITORY_URL: https://test.pypi.org/legacy/
with:
command: upload
args: --non-interactive --skip-existing wheels-*/*
- name: Publish to PyPI
if: ${{ !contains(github.ref, 'alpha') && !contains(github.ref, 'beta') && !contains(github.ref, 'dev') }}
uses: PyO3/maturin-action@v1
env:
MATURIN_PYPI_TOKEN: ${{ secrets.PYPI_API_TOKEN }}
with:
command: upload
args: --non-interactive --skip-existing wheels-*/*
pillow-jpegxl-plugin-1.3.8/.github/workflows/test.yml 0000664 0000000 0000000 00000003745 15226316512 0022727 0 ustar 00root root 0000000 0000000 name: Test Python
on:
# Trigger the workflow on push or pull request,
# but only for the main branch
push:
branches:
- main
pull_request:
branches:
- main
env:
RUSTFLAGS: -C debuginfo=0 # Do not produce debug symbols to keep memory usage down
RUST_BACKTRACE: 1
jobs:
test-python:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
# we only use macos for fast testing
os: [macos-latest]
python-version: ['3.12', '3.13']
steps:
- uses: actions/checkout@v7
with:
submodules: recursive
- name: Set up Python
uses: actions/setup-python@v6
with:
python-version: ${{ matrix.python-version }}
- name: Create virtual environment
env:
BIN: ${{ matrix.os == 'macos-latest' && 'Scripts' || 'bin' }}
run: |
python -m venv venv
- name: Set up Rust
run: rustup show
- name: Cache Rust
uses: Swatinem/rust-cache@v2
- name: Install Plugin
run: |
brew install jpeg-xl
export DEP_JXL_LIB=$(brew --prefix jpeg-xl)'/lib'
export DEP_BROTLI_LIB=$(brew --prefix brotli)'/lib'
export DEP_HWY_LIB=$(brew --prefix highway)'/lib'
source venv/bin/activate
pip install -e .[dev] --config-settings=build-args="--features=dynamic"
- name: Test with pytest
run: |
brew install inih
source venv/bin/activate
pytest test/ --junitxml=junit/test-results-${{ matrix.python-version }}.xml
- name: Upload pytest test results
uses: actions/upload-artifact@v7
with:
name: pytest-results-${{ matrix.python-version }}
path: junit/test-results-${{ matrix.python-version }}.xml
# Use always() to always run this step to publish test results when there are test failures
if: ${{ always() }}
pillow-jpegxl-plugin-1.3.8/.gitignore 0000664 0000000 0000000 00000001357 15226316512 0017615 0 ustar 00root root 0000000 0000000 /target
Cargo.lock
# Generated files
*.json
# Byte-compiled / optimized / DLL files
__pycache__/
.pytest_cache/
*.py[cod]
# C extensions
*.so
*.dll
# Distribution / packaging
.Python
.venv/
env/
bin/
build/
develop-eggs/
dist/
eggs/
lib/
lib64/
parts/
sdist/
var/
include/
man/
venv/
wsl_venv/
*.egg-info/
.installed.cfg
*.egg
wheelhouse/
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
pip-selfcheck.json
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.cache
nosetests.xml
coverage.xml
# Translations
*.mo
# Mr Developer
.mr.developer.cfg
.project
.pydevproject
# Rope
.ropeproject
# Django stuff:
*.log
*.pot
.DS_Store
# Sphinx documentation
docs/_build/
# PyCharm
.idea/
# VSCode
.vscode/
# Pyenv
.python-version
pillow-jpegxl-plugin-1.3.8/.pre-commit-config.yaml 0000664 0000000 0000000 00000001330 15226316512 0022075 0 ustar 00root root 0000000 0000000 repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.6.4
hooks:
- id: ruff
args: ["--fix"]
- id: ruff-format
- repo: local
hooks:
- id: cargo-fmt
name: cargo fmt
entry: cargo fmt --all --
language: system
types: [rust]
pass_filenames: false
- id: cargo-clippy
name: cargo clippy
entry: cargo clippy --all-targets --all-features --features vendored -- -D warnings
language: system
types: [rust]
pass_filenames: false
pillow-jpegxl-plugin-1.3.8/Cargo.toml 0000664 0000000 0000000 00000001054 15226316512 0017547 0 ustar 00root root 0000000 0000000 [package]
name = "pillow-jxl-plugin"
version = "1.3.8"
edition = "2021"
build = "build.rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
name = "pillow_jxl"
crate-type = ["cdylib"]
[dependencies]
pyo3 = { version="0.29.0", features = ["extension-module"] }
jpegxl-rs = { version="0.15.0", default-features = false }
half = "2.7.1"
bytemuck = "1.24.0"
[features]
# Enables parallel processing support by enabling the "rayon" feature of jpeg-decoder.
vendored = ["jpegxl-rs/vendored"]
dynamic = []
pillow-jpegxl-plugin-1.3.8/LICENSE 0000664 0000000 0000000 00000104515 15226316512 0016632 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
pillow-jpegxl-plugin-1.3.8/README.md 0000664 0000000 0000000 00000005675 15226316512 0017113 0 ustar 00root root 0000000 0000000 # pillow-jpegxl-plugin

[](https://github.com/Isotr0py/pillow-jpegxl-plugin/actions/workflows/test.yml)
Pillow plugin for JPEG-XL, using Rust for bindings.
## Features
- JPEG-XL Plugin for Pillow
- Encoder/Decoder to work with JPEG-XL using safe wrapper
- Support EXIF metadata encoding
## Install via PIP
```
pip install pillow-jxl-plugin
```
## Build from source
Make sure [`Rust`](https://www.rust-lang.org/tools/install) installed, then run:
```
git clone https://github.com/Isotr0py/pillow-jpegxl-plugin
cd pillow-jpegxl-plugin
pip install -e .[dev] -v
```
If you have [`libjxl`](https://github.com/libjxl/libjxl) installed and want to use dynamic link, run:
```
pip install -e .[dev] -v --config-settings=build-args="--features=dynamic"
```
## Development
- Python code is formatted and linted with `ruff`, while Rust code is checked with `cargo fmt` and `cargo clippy` via [pre-commit](https://pre-commit.com/).
- Install the tooling once with `pip install -e .[dev]` and then `pre-commit install`.
- Run the suite manually with `pre-commit run --all-files` before opening a pull request.
## Plugin Usage
Use `import pillow_jxl` to register the plugin in your code.
### Example:
```python
from io import BytesIO
import pillow_jxl
from PIL import Image
# Lossless encode a png image
with Image.open("example.png") as img:
img.save("example.jxl",lossless=True)
# Encode image with JPEG-Style quality
with Image.open("example.png") as img:
img.save("example.jxl", quality=98)
# Lossless construct from a jpeg image
with Image.open("example.jpg") as img:
img.save("example.jxl",lossless=True)
# Decode jxl image
with Image.open("example.jxl") as img:
display(img)
# Encode/decode jxl image to buffer
buffer = BytesIO()
with Image.open("example.png") as img:
img.save(buffer, format="JXL")
jxl_bytes = buffer.getvalue()
img = Image.open(BytesIO(jxl_bytes))
display(img)
```
## Wheels status
| Wheels | Windows (x86/x64) | Windows (ARM) | MacOS (x64/aarch64) | manylinux (x86/x64/aarch64) | musllinux |
|:-----------:|:-----------------:|:-------------:|:-------------------:|:---------------------------:|:---------:|
| CP3.10 | ✔ | � | ✔ | ✔ | ✔ |
| CP3.11 | ✔ | ✔ | ✔ | ✔ | ✔ |
| CP3.12 | ✔ | ✔ | ✔ | ✔ | ✔ |
| CP3.13 | ✔ | ✔ | ✔ | ✔ | ✔ |
| PyPy3.11 | ✔ | � | ✔ | ✔ | ✔ |
## Credits
- [inflation/jpegxl-rs](https://github.com/inflation/jpegxl-rs)
pillow-jpegxl-plugin-1.3.8/benchmarks/ 0000775 0000000 0000000 00000000000 15226316512 0017734 5 ustar 00root root 0000000 0000000 pillow-jpegxl-plugin-1.3.8/benchmarks/benchmarks_encode.py 0000664 0000000 0000000 00000004007 15226316512 0023741 0 ustar 00root root 0000000 0000000 import json
import shlex
import subprocess
from argparse import ArgumentParser
from io import BytesIO
from time import time
from PIL import Image
import pillow_jxl # noqa: F401
def encode_plugin(filename, quality, effort):
bio = BytesIO()
t = time()
Image.open(filename).save(bio, format="jxl", quality=quality, effort=effort)
d = time() - t
return len(bio.getvalue()), d
def encode_cli(filename, quality, effort):
cmd = f'cjxl -q {quality} -e {effort} "{filename}" -'
t = time()
p = subprocess.run(shlex.split(cmd), check=True, capture_output=True)
d = time() - t
return len(p.stdout), d
def main(args):
filename = args.image
quality = args.quality
result = {
"image": filename,
"quality": quality,
"effort": [],
"plugin_size": [],
"plugin_time": [],
"refenc_size": [],
"refenc_time": [],
}
print("Quality:", quality)
for effort in range(1, 10):
size_plugin, time_plugin = encode_plugin(filename, quality, effort)
size_refenc, time_refenc = encode_cli(filename, quality, effort)
print(f"\nEffort {effort}")
print(f" plugin [size: {size_plugin}, duration: {time_plugin:.3f}]")
print(f" reference [size: {size_refenc}, duration: {time_refenc:.3f}]")
result["effort"].append(effort)
result["plugin_size"].append(size_plugin)
result["plugin_time"].append(time_plugin)
result["refenc_size"].append(size_refenc)
result["refenc_time"].append(time_refenc)
if args.output_json:
with open(args.output_json, "w") as f:
json.dump(result, f, indent=4)
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument(
"-i", "--image", help="Image file for encode benchmark", required=True
)
parser.add_argument("-q", "--quality", type=int, default=98, help="Quality level")
parser.add_argument("-o", "--output-json", help="Output JSON file")
args = parser.parse_args()
main(args)
pillow-jpegxl-plugin-1.3.8/build.rs 0000664 0000000 0000000 00000003206 15226316512 0017265 0 ustar 00root root 0000000 0000000 use std::env;
#[allow(dead_code)]
fn dynamic_link() {
println!("cargo:rustc-link-lib=jxl");
println!("cargo:rustc-link-lib=jxl_threads");
println!("cargo:rustc-link-lib=hwy");
if let Ok(path) = env::var("DEP_HWY_LIB") {
println!("cargo:rustc-link-search=native={path}");
}
println!("cargo:rustc-link-lib:+whole-archive=brotlidec");
println!("cargo:rustc-link-lib=brotlienc");
println!("cargo:rustc-link-lib=brotlicommon");
if let Ok(path) = env::var("DEP_BROTLI_LIB") {
println!("cargo:rustc-link-search=native={path}");
}
}
#[allow(dead_code)]
fn static_link() {
println!("cargo:rustc-link-lib=static=jxl");
println!("cargo:rustc-link-lib=static=jxl_cms");
println!("cargo:rustc-link-lib=static=jxl_threads");
println!("cargo:rustc-link-lib=static=hwy");
if let Ok(path) = env::var("DEP_HWY_LIB") {
println!("cargo:rustc-link-search=native={path}");
}
println!("cargo:rustc-link-lib=static:+whole-archive=brotlidec");
println!("cargo:rustc-link-lib=static=brotlienc");
println!("cargo:rustc-link-lib=static=brotlicommon");
if let Ok(path) = env::var("DEP_BROTLI_LIB") {
println!("cargo:rustc-link-search=native={path}");
}
}
fn main() {
// Static link libjxl
#[cfg(all(not(feature = "vendored"), not(feature = "dynamic")))]
static_link();
#[cfg(all(not(feature = "vendored"), feature = "dynamic"))]
dynamic_link();
// Dynamic link c++
#[cfg(target_os = "linux")]
{
println!("cargo:rustc-link-lib=stdc++");
}
#[cfg(target_os = "macos")]
{
println!("cargo:rustc-link-lib=c++");
}
}
pillow-jpegxl-plugin-1.3.8/pillow_jxl/ 0000775 0000000 0000000 00000000000 15226316512 0020002 5 ustar 00root root 0000000 0000000 pillow-jpegxl-plugin-1.3.8/pillow_jxl/JpegXLImagePlugin.py 0000664 0000000 0000000 00000013433 15226316512 0023633 0 ustar 00root root 0000000 0000000 import warnings
from io import BytesIO
import PIL
from packaging.version import parse
from PIL import Image, ImageFile
from pillow_jxl import Decoder, Encoder
_VALID_JXL_MODES = {"RGB", "RGBA", "L", "LA", "I;16", "F"}
DECODE_THREADS = -1 # -1 detect available cpu cores, 0 disables parallelism
def _accept(data):
return (
data[:2] == b"\xff\x0a"
or data[:12] == b"\x00\x00\x00\x0c\x4a\x58\x4c\x20\x0d\x0a\x87\x0a"
or data[4:7] == b"JXL"
)
class JXLImageFile(ImageFile.ImageFile):
format = "JXL"
format_description = "Jpeg XL image"
__loaded = -1
__frame = 0
def _open(self):
self.fc = self.fp.read()
self._decoder = Decoder(num_threads=DECODE_THREADS)
(self.jpeg, self._jxlinfo, self._data, icc_profile, jxl_boxes) = self._decoder(
self.fc
)
if self._jxlinfo.mode == "F;16":
warnings.warn(
"Pillow doesn't support 16 bit floats, upcasting to 32 bits.",
stacklevel=2,
)
self._jxlinfo.mode = "F"
# FIXME (Isotr0py): Maybe slow down jpeg reconstruction
if self.jpeg:
with Image.open(BytesIO(self._data)) as im:
self._data = im.tobytes()
self._size = im.size
self.rawmode = im.mode
self.info = im.info
icc_profile = im.info.get("icc_profile", icc_profile)
else:
self._size = (self._jxlinfo.width, self._jxlinfo.height)
self.rawmode = self._jxlinfo.mode
# Read the exif data from the file
for box in jxl_boxes:
if box.box_type == b"Exif":
exif_data = box.data
if len(exif_data) > 8 and exif_data[4:8] in (
b"II\x2a\x00",
b"MM\x00\x2a",
):
exif_data = exif_data[4:]
self.info["exif"] = exif_data
break
if icc_profile:
self.info["icc_profile"] = icc_profile
# NOTE (Isotr0py): PIL 10.1.0 changed the mode to property, use _mode instead
if parse(PIL.__version__) >= parse("10.1.0"):
self._mode = self.rawmode
else:
self.mode = self.rawmode
# FIXME (Isotr0py): animation JXL hasn't supported yet
self.is_animated = False
self.n_frames = 1
self.tile = []
# TODO(Isotr0py): Support animation seeking
# def seek(self, frame):
# self.load()
# if self.__frame + 1 != frame:
# # I believe JPEG XL doesn't support seeking in animations
# raise NotImplementedError(
# "Seeking more than one frame forward is currently not supported."
# )
# self.__frame = frame
def load(self):
if self.__loaded != self.__frame:
if self._data is None:
EOFError("no more frames")
self.__loaded = self.__frame
if self.fp and self._exclusive_fp:
self.fp.close()
self.fp = BytesIO(self._data)
self.tile = [("raw", (0, 0) + self.size, 0, self.rawmode)]
return super().load()
# may be defined for contained formats
def load_seek(self, pos):
pass
# may be defined for blocked formats (e.g. PNG)
# def load_read(self, bytes):
# pass
def tell(self):
return self.__frame
def _save(im, fp, filename, save_all=False):
if im.mode not in _VALID_JXL_MODES:
raise NotImplementedError("Only RGB, RGBA, L, LA, I;16, F are supported.")
info = im.encoderinfo.copy()
# default quality is 90
lossless = info.get("lossless", False)
quality = 100 if lossless else info.get("quality", 90)
decoding_speed = info.get("decoding_speed", 0)
effort = info.get("effort", 7)
use_container = info.get("use_container", False)
use_original_profile = info.get("use_original_profile", False)
jpeg_encode = info.get("lossless_jpeg", None)
num_threads = info.get("num_threads", -1)
compress_metadata = info.get("compress_metadata", False)
enc = Encoder(
mode=im.mode,
lossless=lossless,
quality=quality,
decoding_speed=decoding_speed,
effort=effort,
use_container=use_container,
use_original_profile=use_original_profile,
num_threads=num_threads,
)
# FIXME (Isotr0py): im.filename maybe None if parse stream
# TODO (Isotr0py): This part should be refactored in the near future
if im.format == "JPEG" and im.filename and (jpeg_encode or jpeg_encode is None):
if jpeg_encode is None:
warnings.warn(
"Using JPEG reconstruction to create lossless JXL image from JPEG. "
"This is the default behavior for JPEG encode, if you want to "
"disable this, please set 'lossless_jpeg'.",
stacklevel=2,
)
with open(im.filename, "rb") as f:
data = enc(f.read(), im.width, im.height, jpeg_encode=True)
else:
exif = info.get("exif")
if exif is None:
exif = im.getexif()
exif = exif.tobytes() if exif else None
if exif and exif.startswith(b"Exif\x00\x00"):
exif = exif[6:]
metadata = {
"exif": exif or None,
"jumb": info.get("jumb") or None,
"xmp": info.get("xmp") or None,
"compress": compress_metadata,
}
data = enc(im.tobytes(), im.width, im.height, jpeg_encode=False, **metadata)
fp.write(data)
Image.register_open(JXLImageFile.format, JXLImageFile, _accept)
Image.register_save(JXLImageFile.format, _save)
Image.register_extension(JXLImageFile.format, ".jxl")
Image.register_mime(JXLImageFile.format, "image/jxl")
pillow-jpegxl-plugin-1.3.8/pillow_jxl/__init__.py 0000664 0000000 0000000 00000000303 15226316512 0022107 0 ustar 00root root 0000000 0000000 # ruff: noqa
from .pillow_jxl import Decoder, Encoder
from pillow_jxl import JpegXLImagePlugin
__doc__ = pillow_jxl.__doc__
if hasattr(pillow_jxl, "__all__"):
__all__ = pillow_jxl.__all__
pillow-jpegxl-plugin-1.3.8/pillow_jxl/__init__.pyi 0000664 0000000 0000000 00000002242 15226316512 0022264 0 ustar 00root root 0000000 0000000 class ImageInfo:
"""
A class contains metadata of ddecoded image.
"""
mode: str
width: int
height: int
num_channels: int
has_alpha_channel: bool
class Encoder:
def __init__(
self,
parallel: bool = True,
has_alpha: bool = False,
lossless: bool = True,
quality: float = 0.0,
num_threads: int = -1,
): ...
def __call__(
self, data: bytes, width: int, height: int, jpeg_encode: bool
) -> bytes: ...
"""
Encode a jpeg-xl image.
Args:
data(`bytes`): raw image bytes
Return:
`bytes`: The encoded jpeg-xl image.
"""
class Decoder:
"""
Initialize a jpeg-xl decoder.
Args:
parallel(`bool`): enable parallel decoding
"""
def __init__(self, num_threads: int = -1): ...
def __call__(self, data: bytes) -> (bool, ImageInfo, bytes): ...
"""
Decode a jpeg-xl image.
Args:
data(`bytes`): jpeg-xl image
Return:
`bool`: If the jpeg is reconstructed
`ImageInfo`: The metadata of decoded image
`bytes`: The decoded image.
"""
pillow-jpegxl-plugin-1.3.8/pillow_jxl/py.typed 0000664 0000000 0000000 00000000000 15226316512 0021467 0 ustar 00root root 0000000 0000000 pillow-jpegxl-plugin-1.3.8/pyproject.toml 0000664 0000000 0000000 00000002216 15226316512 0020534 0 ustar 00root root 0000000 0000000 [build-system]
requires = ["maturin>=1.2,<2.0"]
build-backend = "maturin"
[project]
name = "pillow-jxl-plugin"
requires-python = ">=3.9"
authors = [
{ name = "Isotr0py" },
]
description = "Pillow plugin for JPEG-XL, using Rust for bindings."
readme = "README.md"
license = "GPL-3.0-or-later"
license-files = ["LICENSE"]
classifiers = [
"Programming Language :: Rust",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
]
dependencies = [
"packaging",
"Pillow",
]
dynamic = ["version", "dependencies", "optional-dependencies"]
[project.optional-dependencies]
dev = [
"cmake",
"numpy",
"OpenEXR",
"pre-commit",
"pytest",
"pyexiv2",
"ruff",
]
[project.urls]
"Homepage" = "https://github.com/Isotr0py/pillow-jpegxl-plugin"
"Bug Tracker" = "https://github.com/Isotr0py/pillow-jpegxl-plugin/issues"
"Releases" = "https://github.com/Isotr0py/pillow-jpegxl-plugin/releases"
[tool.maturin]
features = ["pyo3/extension-module", "vendored"]
[tool.ruff]
target-version = "py39"
line-length = 88
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
pillow-jpegxl-plugin-1.3.8/src/ 0000775 0000000 0000000 00000000000 15226316512 0016406 5 ustar 00root root 0000000 0000000 pillow-jpegxl-plugin-1.3.8/src/decode.rs 0000664 0000000 0000000 00000022754 15226316512 0020211 0 ustar 00root root 0000000 0000000 use std::borrow::Cow;
use pyo3::exceptions::{PyNotImplementedError, PyRuntimeError, PyValueError};
use pyo3::prelude::*;
use jpegxl_rs::decode::{Data, Metadata, Pixels};
use jpegxl_rs::parallel::threads_runner::ThreadsRunner;
use jpegxl_rs::{decoder_builder, DecodeError};
// it works even if the item is not documented:
#[pyclass(module = "pillow_jxl")]
struct ImageInfo {
#[pyo3(get, set)]
mode: String, // Mode of the image
#[pyo3(get, set)]
width: u32, // Width of the image
#[pyo3(get, set)]
height: u32, // Height of the image
#[pyo3(get, set)]
num_channels: u32, // Number of color channels per pixel
#[pyo3(get, set)]
has_alpha_channel: bool,
}
impl ImageInfo {
fn from(item: Metadata, pixel: &Data) -> ImageInfo {
let pixel_type = match &pixel {
Data::Pixels(pixels) => Some(pixels),
Data::Jpeg(_) => None,
};
ImageInfo {
mode: Self::mode(item.num_color_channels, item.has_alpha_channel, pixel_type).unwrap(),
width: item.width,
height: item.height,
num_channels: item.num_color_channels,
has_alpha_channel: item.has_alpha_channel,
}
}
fn mode(
num_channels: u32,
has_alpha_channel: bool,
pixel_type: Option<&Pixels>,
) -> PyResult {
let mode = match (num_channels, has_alpha_channel) {
(1, false) => "L".to_string(),
(1, true) => "LA".to_string(),
(3, false) => "RGB".to_string(),
(3, true) => "RGBA".to_string(),
_ => return Err(PyNotImplementedError::new_err("Unsupported color mode")),
};
if let Some(Pixels::Uint16(_)) = pixel_type {
if mode == "L" {
return Ok("I;16".to_string());
}
}
if let Some(Pixels::Float(_)) = pixel_type {
if mode == "L" {
return Ok("F".to_string());
}
}
// HACK: Pillow doesn't natively support float16 mode.
// Therefore, you have to upcast
if let Some(Pixels::Float16(_)) = pixel_type {
if mode == "L" {
return Ok("F;16".to_string());
}
}
Ok(mode)
}
}
#[pyclass(module = "pillow_jxl")]
pub struct JxlBox {
#[pyo3(get, set)]
box_type: [u8; 4],
#[pyo3(get, set)]
data: Vec,
}
#[pymethods]
impl JxlBox {
fn __repr__(&self) -> PyResult {
Ok(format!(
"JxlBox(type={:?}, size={})",
String::from_utf8_lossy(&self.box_type),
self.data.len()
))
}
}
// refer to https://github.com/Fraetor/jxl_decode/blob/902cd5d479f89f93df6105a22dc92f297ab77541/src/jxl_decode/jxl.py#L88-L110
fn extract_boxes(data: &[u8]) -> PyResult> {
const JXL_CONTAINER_SIGNATURE: &[u8] = b"\x00\x00\x00\x0c\x4a\x58\x4c\x20\x0d\x0a\x87\x0a";
if !data.starts_with(JXL_CONTAINER_SIGNATURE) {
return Ok(Vec::new());
}
const JXL_CONTAINER_HEADER_SIZE: usize = 32;
let mut boxes = Vec::new();
let mut pos = JXL_CONTAINER_HEADER_SIZE;
while pos + 8 <= data.len() {
// A box has at least a 4-byte size and 4-byte type.
let box_size = u32::from_be_bytes(data[pos..pos + 4].try_into().unwrap()) as usize;
let (header_length, box_length) = if box_size == 1 {
// 64-bit box size
if pos + 16 > data.len() {
// Not enough data for a large box header
break;
}
let large_box_size = u64::from_be_bytes(data[pos + 8..pos + 16].try_into().unwrap());
let large_box_size = usize::try_from(large_box_size).map_err(|_| {
PyValueError::new_err(format!(
"Box size at position {pos} is too large for this platform"
))
})?;
if large_box_size < 16 {
// The box is smaller than its own header, which is invalid.
return Err(PyValueError::new_err(format!(
"Invalid large box size at position {pos}",
)));
}
(16, large_box_size)
} else {
// 32-bit box size
if (2..=7).contains(&box_size) {
return Err(PyValueError::new_err(format!(
"Invalid box size at position {pos}",
)));
}
(
8,
if box_size == 0 {
data.len() - pos
} else {
box_size
},
)
};
if pos
.checked_add(box_length)
.is_none_or(|end| end > data.len())
{
// Box extends beyond the end of the data, which indicates a corrupt file.
break;
}
let box_type = data[pos + 4..pos + 8].try_into().unwrap();
let box_data = data[pos + header_length..pos + box_length].to_vec();
boxes.push(JxlBox {
box_type,
data: box_data,
});
pos += box_length;
}
Ok(boxes)
}
#[pyclass(module = "pillow_jxl")]
pub struct Decoder {
num_threads: isize,
}
type DecodeResult<'a> = (bool, ImageInfo, Cow<'a, [u8]>, Cow<'a, [u8]>, Vec);
#[pymethods]
impl Decoder {
#[new]
#[pyo3(signature = (num_threads = -1))]
fn new(num_threads: isize) -> Self {
Self { num_threads }
}
#[pyo3(signature = (data))]
fn __call__(&self, _py: Python, data: &[u8]) -> PyResult> {
_py.detach(|| self.call_inner(data))
}
fn __repr__(&self) -> PyResult {
Ok("Decoder".to_string())
}
}
impl Decoder {
fn pixels_to_bytes_8bit(&self, pixels: Pixels) -> PyResult> {
// Convert pixels to bytes with 8-bit casting
let mut result = Vec::new();
match pixels {
Pixels::Uint8(pixels) => {
return Ok(pixels);
}
Pixels::Uint16(pixels) => {
for pixel in pixels {
result.push((pixel >> 8) as u8);
}
}
Pixels::Float(pixels) => {
for pixel in pixels {
result.push((pixel * 255.0) as u8);
}
}
Pixels::Float16(pixels) => {
for pixel in pixels {
// PERF: use native f16 ops
result.push((pixel.to_f32() * 255.0) as u8);
}
}
}
Ok(result)
}
fn pixels_to_bytes(&self, pixels: Pixels) -> PyResult> {
// Convert pixels to bytes without casting
let mut result = Vec::new();
match pixels {
Pixels::Uint8(pixels) => {
return Ok(pixels);
}
Pixels::Uint16(pixels) => {
for pixel in pixels {
let pix_bytes = pixel.to_ne_bytes();
for byte in pix_bytes.iter() {
result.push(*byte);
}
}
}
Pixels::Float(pixels) => {
for pixel in pixels {
let pix_bytes = pixel.to_ne_bytes();
for byte in pix_bytes.iter() {
result.push(*byte);
}
}
}
Pixels::Float16(pixels) => {
// HACK: Pillow doesn't natively support float16 mode.
// Therefore, you have to upcast
for pixel in pixels {
let pix_bytes = pixel.to_f32().to_ne_bytes();
result.extend_from_slice(&pix_bytes);
}
}
}
Ok(result)
}
fn convert_pil_pixels(&self, pixels: Pixels, num_channels: u32) -> PyResult> {
let result = match num_channels {
1 => self.pixels_to_bytes(pixels)?,
3 => self.pixels_to_bytes_8bit(pixels)?,
_ => return Err(PyValueError::new_err("image color channels must be 1 or 3")),
};
Ok(result)
}
}
impl Decoder {
fn call_inner(&self, data: &[u8]) -> PyResult> {
let parallel_runner = ThreadsRunner::new(
None,
if self.num_threads < 0 {
None
} else {
Some(self.num_threads as usize)
},
)
.ok_or_else(|| PyRuntimeError::new_err("Could not create JxlThreadsRunner"))?;
let decoder = decoder_builder()
.icc_profile(true)
.parallel_runner(¶llel_runner)
.build()
.map_err(to_pyjxlerror)?;
let (info, img) = decoder.reconstruct(data).map_err(to_pyjxlerror)?;
let boxes = match extract_boxes(data) {
Ok(b) => b,
Err(e) => {
eprintln!("Warning: Failed to extract JXL boxes: {e}");
Vec::new()
}
};
let icc_profile: Vec = match &info.icc_profile {
Some(x) => x.to_vec(),
None => Vec::new(),
};
let img_info = ImageInfo::from(info, &img);
let (jpeg, img) = match img {
Data::Jpeg(x) => (true, x),
Data::Pixels(x) => (false, self.convert_pil_pixels(x, img_info.num_channels)?),
};
Ok((
jpeg,
img_info,
Cow::Owned(img),
Cow::Owned(icc_profile),
boxes,
))
}
}
fn to_pyjxlerror(e: DecodeError) -> PyErr {
PyRuntimeError::new_err(e.to_string())
}
pillow-jpegxl-plugin-1.3.8/src/encode.rs 0000664 0000000 0000000 00000020224 15226316512 0020211 0 ustar 00root root 0000000 0000000 use std::borrow::Cow;
use pyo3::exceptions::{PyRuntimeError, PyValueError};
use pyo3::prelude::*;
use jpegxl_rs::encode::{ColorEncoding, EncoderFrame, EncoderSpeed, Metadata};
use jpegxl_rs::parallel::threads_runner::ThreadsRunner;
use jpegxl_rs::{encoder_builder, EncodeError};
/// Represents different pixel types for encoding
#[derive(Clone, Copy)]
enum PixelType {
/// 8-bit unsigned integer (RGB, RGBA, L, LA modes)
Uint8 { num_channels: u32, has_alpha: bool },
/// 16-bit unsigned integer (I;16 mode, grayscale only)
Uint16,
/// 32-bit float (F mode, grayscale only)
Float32,
}
impl PixelType {
fn color_encoding(&self) -> ColorEncoding {
match self {
PixelType::Uint8 { num_channels, .. } => match num_channels {
1 | 2 => ColorEncoding::SrgbLuma,
3 | 4 => ColorEncoding::Srgb,
_ => unreachable!("Invalid number of channels for Uint8 pixel type"),
},
PixelType::Uint16 | PixelType::Float32 => ColorEncoding::LinearSrgbLuma,
}
}
fn has_alpha(&self) -> bool {
match self {
PixelType::Uint8 { has_alpha, .. } => *has_alpha,
PixelType::Uint16 | PixelType::Float32 => false,
}
}
}
#[pyclass(module = "pillow_jxl")]
pub struct Encoder {
pixel_type: PixelType,
lossless: bool,
quality: f32,
decoding_speed: i64,
effort: u32,
use_container: bool,
use_original_profile: bool,
num_threads: isize,
}
#[allow(clippy::too_many_arguments)]
#[pymethods]
impl Encoder {
#[new]
#[pyo3(signature = (mode, lossless=false, quality=1.0, decoding_speed=0, effort=7, use_container=false, use_original_profile=false, num_threads=-1))]
fn new(
mode: &str,
lossless: bool,
quality: f32,
decoding_speed: i64,
effort: u32,
use_container: bool,
use_original_profile: bool,
num_threads: isize,
) -> PyResult {
let pixel_type = match mode {
"RGBA" => PixelType::Uint8 {
num_channels: 4,
has_alpha: true,
},
"RGB" => PixelType::Uint8 {
num_channels: 3,
has_alpha: false,
},
"LA" => PixelType::Uint8 {
num_channels: 2,
has_alpha: true,
},
"L" => PixelType::Uint8 {
num_channels: 1,
has_alpha: false,
},
"I;16" => PixelType::Uint16,
"F" => PixelType::Float32,
_ => {
return Err(PyValueError::new_err(
"Only RGB, RGBA, L, LA, I;16, F are supported.",
))
}
};
let decoding_speed = match decoding_speed {
0..=4 => decoding_speed,
_ => {
return Err(PyValueError::new_err(
"Decoding speed must be between 0 and 4",
))
}
};
let use_original_profile = match lossless {
true => true,
false => use_original_profile,
};
Ok(Self {
pixel_type,
lossless,
quality,
decoding_speed,
effort,
use_container,
use_original_profile,
num_threads,
})
}
#[allow(clippy::too_many_arguments)]
#[pyo3(signature = (data, width, height, jpeg_encode, exif=None, jumb=None, xmp=None, compress=false))]
fn __call__(
&self,
py: Python,
data: &[u8],
width: u32,
height: u32,
jpeg_encode: bool,
exif: Option<&[u8]>,
jumb: Option<&[u8]>,
xmp: Option<&[u8]>,
compress: bool,
) -> PyResult> {
py.detach(|| self.call_inner(data, width, height, jpeg_encode, exif, jumb, xmp, compress))
}
fn __repr__(&self) -> PyResult {
Ok(format!(
"Encoder(has_alpha={}, lossless={}, quality={}, decoding_speed={}, effort={}, num_threads={})",
self.pixel_type.has_alpha(), self.lossless, self.quality, self.decoding_speed, self.effort, self.num_threads
))
}
}
impl Encoder {
#[allow(clippy::too_many_arguments)]
fn call_inner(
&self,
data: &[u8],
width: u32,
height: u32,
jpeg_encode: bool,
exif: Option<&[u8]>,
jumb: Option<&[u8]>,
xmp: Option<&[u8]>,
compress: bool,
) -> PyResult> {
let parallel_runner = ThreadsRunner::new(
None,
if self.num_threads < 0 {
None
} else {
Some(self.num_threads as usize)
},
)
.ok_or_else(|| PyRuntimeError::new_err("Could not create JxlThreadsRunner"))?;
let mut encoder = encoder_builder()
.parallel_runner(¶llel_runner)
.jpeg_quality(self.quality)
.has_alpha(self.pixel_type.has_alpha())
.lossless(self.lossless)
.use_container(self.use_container)
.decoding_speed(self.decoding_speed)
.build()
.map_err(to_pyjxlerror)?;
encoder.uses_original_profile = self.use_original_profile;
encoder.color_encoding = Some(self.pixel_type.color_encoding());
encoder.speed = match self.effort {
1 => EncoderSpeed::Lightning,
2 => EncoderSpeed::Thunder,
3 => EncoderSpeed::Falcon,
4 => EncoderSpeed::Cheetah,
5 => EncoderSpeed::Hare,
6 => EncoderSpeed::Wombat,
7 => EncoderSpeed::Squirrel,
8 => EncoderSpeed::Kitten,
9 => EncoderSpeed::Tortoise,
10 => EncoderSpeed::Glacier,
_ => return Err(PyValueError::new_err("Invalid effort")),
};
// Add metadata if provided (for non-JPEG encode)
if !jpeg_encode {
if let Some(exif_data) = exif {
encoder
.add_metadata(&Metadata::Exif(exif_data), compress)
.map_err(to_pyjxlerror)?
}
if let Some(xmp_data) = xmp {
encoder
.add_metadata(&Metadata::Xmp(xmp_data), compress)
.map_err(to_pyjxlerror)?
}
if let Some(jumb_data) = jumb {
encoder
.add_metadata(&Metadata::Jumb(jumb_data), compress)
.map_err(to_pyjxlerror)?
}
}
let buffer: Vec = if jpeg_encode {
encoder.encode_jpeg(data).map_err(to_pyjxlerror)?.data
} else {
match self.pixel_type {
PixelType::Uint8 { num_channels, .. } => {
let frame = EncoderFrame::new(data).num_channels(num_channels);
encoder
.encode_frame::(&frame, width, height)
.map_err(to_pyjxlerror)?
.data
}
PixelType::Uint16 => {
let data_u16: &[u16] = bytemuck::try_cast_slice(data).map_err(|e| {
PyValueError::new_err(format!("Failed to cast I;16 data to u16 slice: {e}"))
})?;
let frame = EncoderFrame::new(data_u16).num_channels(1);
encoder
.encode_frame::(&frame, width, height)
.map_err(to_pyjxlerror)?
.data
}
PixelType::Float32 => {
let data_f32: &[f32] = bytemuck::try_cast_slice(data).map_err(|e| {
PyValueError::new_err(format!("Failed to cast F data to f32 slice: {e}"))
})?;
let frame = EncoderFrame::new(data_f32).num_channels(1);
encoder
.encode_frame::(&frame, width, height)
.map_err(to_pyjxlerror)?
.data
}
}
};
Ok(Cow::Owned(buffer))
}
}
fn to_pyjxlerror(e: EncodeError) -> PyErr {
PyRuntimeError::new_err(e.to_string())
}
pillow-jpegxl-plugin-1.3.8/src/lib.rs 0000664 0000000 0000000 00000000743 15226316512 0017526 0 ustar 00root root 0000000 0000000 use pyo3::{create_exception, exceptions::PyRuntimeError, prelude::*};
// it works even if the item is not documented:
mod decode;
mod encode;
create_exception!(my_module, JxlException, PyRuntimeError, "Jxl Error");
#[pymodule]
#[pyo3(name = "pillow_jxl")]
fn pillow_jxl(_py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::()?;
m.add_class::()?;
m.add("JxlException", m.py().get_type::())?;
Ok(())
}
pillow-jpegxl-plugin-1.3.8/test/ 0000775 0000000 0000000 00000000000 15226316512 0016576 5 ustar 00root root 0000000 0000000 pillow-jpegxl-plugin-1.3.8/test/images/ 0000775 0000000 0000000 00000000000 15226316512 0020043 5 ustar 00root root 0000000 0000000 pillow-jpegxl-plugin-1.3.8/test/images/README.md 0000664 0000000 0000000 00000000701 15226316512 0021320 0 ustar 00root root 0000000 0000000 ## License about test sample images
- Most of sample images are copied from [`libjxl/testdata`](https://github.com/libjxl/testdata/tree/main) with **CC-BY-4.0 license**
- `bench.png` is a photo taken by myself, with **CC-BY-SA-4.0 license**
- `62AHB.jpg` is copied from [Stackoverflow](https://stackoverflow.com/questions/31865743/pil-pillow-decode-icc-profile-information), with [**CC-BY-SA-4.0 license**](https://stackoverflow.com/help/licensing)
pillow-jpegxl-plugin-1.3.8/test/images/bench.png 0000664 0000000 0000000 00005170332 15226316512 0021643 0 ustar 00root root 0000000 0000000 ‰PNG
IHDR f €Âï2 sRGB ®Îé gAMA ±�üa pHYs à ÃÇo¨d ÿ¥IDATx^”ýÉ’%I–¦‰‰™ªÍæîá•Y•™‘YÕ
¡‰@Ø`êe#‡¢®*"¼K¼€' VX¢�êFUWá>Úl¦³Î÷Ÿó3á{Õ<ó¿Ê‡ÏÌ,,,ƒ^½óý¿ýß?lw>lÛFIÜÙN¶¢}÷N´>ý~»sçÎv÷î]ñß¿ŸŠxw>„MÙY[µµÝ¶÷áË<€oµ‰}çnÐbJïnø<‰Xïߣ#m6©mìÏyÞ¹s¢¶úRÈ<2·™;òŒ�®ôÑCD_"&p®©çúýö[ó£þú䊟餽d¢Ê9‰ê!H`âQ¾cQ.‚NBù‡aŒ’Æ'“�tÙ4_"ÿÙ/üæø±Ÿî¡±bÜ‚gpýº{7ç®U°+_À45�}Ô�â1Š™rò¤ƒ(jFnÚ–~µ�“°ÇÆû4~F÷Ð|›”GÍ�½}zìOìG.QºMúb˜1®©÷>ÆåÃЧf|K¯æIÊSÇ>°µÏt�crðáÃMæ%Ý�kNºÌÛ°u:æÑdxǬÄy@¯ÌÀ�ùeÉñƒO›cAšÌ¨™_‚¼ßn`jßÞoäQ}ª8Á2:šؓ“ÿ˜ ‘QGÎ
ì€s£íü$( ³³¬Q'¿nKM^ädd;e9™W –*Ǧœ<®ì?õ£�9•N¸MõTÈœKŸèÌŒ%g©£5‘Où•IM�wÉ9âØ3òºwǪÜE²ÞŠÔ>”µSO‚ØÜ½{ñê|Û.Ï·—ϾÙÎÏ^n7—7:>ÀÙåÅv}}~óú*æoå®üñRóQyÄçüü\sôääDyS®®®¤ƒÍÕå•|üâ_†Þõöþ&rˆúnècÿ$Öý“û1»Ø—ô'øWWבÃûíÝÛËí“O¶ýëÿÕÿn»÷É'ô$Ç ;&¯†2Qûø;.#µK?*ò¤
'LË_ÖW|@²p.–´j†P56ìÈgYö$cUKU´Zû±Ôªà5·å7᜴ËKiÈeW†å35Yýçq\Ç€D¥ðyŸ}©sW€*öxÔ9f.!ÀE+¡ˆ.‡`©6]ıGã¼HÞ²
ã¼fM‡Ì�µÇvâA—™6¸/S?yôM<
RÐö/{™q ÇT0XŒ5Ÿä«"öc3¬‚[cÃ|êº(jÇ‚gè|à±¶·Î‡bk ÄÑžº4vù€ê7¶ñ�"?i>xîG›5Üë'º>¦�Ü÷¹O»+Ï+œ£ÒÑ\¬¸U£ÙÇÈ:UéEƒ<ºfúɤúXdßsÜ5ÞòÈØaý)�Œ!ÿŽ�Ž)GCéÑö¹?3Ïãµ ´íä¥M^+‚·’
³ôɹ^y8©ò‘÷3’dÜÐÃÑ�èyÀðˆ©}Zû‘¯l²Âˆ-µô…ض°á¢s£AVÆÊ?cD+X9Gf,ÙGÓnsFM¬‚cS¯}³Þm<æ:MxÌ÷ JÆ~
:’‚CŠ‘™ìàØ¦m8*ĉ:�2xò L9
QÃÒûT¼ŠÑý‹¦tžïjnÆ'�©à¦zÔÑV�„ΫÑOÏ]#c Ïš“>Í3�ëZÐñ!RÇÅ
®¹ôê‡Âº·…Ô’³1)$Ÿ2Ã>EG¡ÏÜÓ'¢Ç‹ó ¾†S74-ûs{1ûh1Ö¸éyHÇ~ì÷»1Î̵눯{«ì”ôu¦2mrœ s:,ðùžµ#¯§s”�÷9xä›LkÇí@L¦=mñ#;î1ÈC¾ƒ×]ÚvŒ›Æƒvf’œ¢ƒèϲßéC¹ÇÕÖºH?ËCTŒ§|-sœC¾âYnì—ä›7sÌxйv£Í1Þ$Ï-\6y,I»òöÜ·?¸B¸zÃ>bŸäq•6[ëIÀv)O:‘ºì½ŒX9t„->ï–�´™pܤU)´MСøqc›9&œ›Æ¢b©¥:Ÿ§
�’Ûšyîyϼ¹);iÑdǧ÷5ÜÛ~#˜¢ƒ‡,cá'ã˜Ðãø`×Ü�¹ó>γÖ×pÄù†¶svÍýSÏs:÷Çáù1õÑ»»�üÕ_ÿ»_ј@’JÊŠîU€Œâ”t±Ä…TqSºCVا“2û ò