diff --git a/.appveyor.yml b/.appveyor.yml
index f6ac309c4..ad783f85e 100644
--- a/.appveyor.yml
+++ b/.appveyor.yml
@@ -1,4 +1,5 @@
version: '{build}'
+image: Visual Studio 2017
clone_folder: c:\pillow
init:
- ECHO %PYTHON%
@@ -6,69 +7,37 @@ init:
# Uncomment previous line to get RDP access during the build.
environment:
- X64_EXT: -x64
EXECUTABLE: python.exe
PIP_DIR: Scripts
- VENV: NO
TEST_OPTIONS:
DEPLOY: YES
matrix:
- PYTHON: C:/Python38
- - PYTHON: C:/Python38-x64
- - PYTHON: C:/Python35
+ ARCHITECTURE: x86
- PYTHON: C:/Python35-x64
- - PYTHON: C:/msys64/mingw32
- EXECUTABLE: bin/python3
- PIP_DIR: bin
- TEST_OPTIONS: --processes=0
- DEPLOY: NO
- - PYTHON: C:/vp/pypy3
- EXECUTABLE: bin/pypy.exe
- PIP_DIR: bin
- VENV: YES
+ ARCHITECTURE: x64
install:
- curl -fsSL -o pillow-depends.zip https://github.com/python-pillow/pillow-depends/archive/master.zip
- 7z x pillow-depends.zip -oc:\
- mv c:\pillow-depends-master c:\pillow-depends
-- xcopy c:\pillow-depends\*.zip c:\pillow\winbuild\
-- xcopy c:\pillow-depends\*.tar.gz c:\pillow\winbuild\
- xcopy /s c:\pillow-depends\test_images\* c:\pillow\tests\images
-- cd c:\pillow\winbuild\
-- ps: |
- if ($env:PYTHON -eq "c:/vp/pypy3")
- {
- c:\pillow\winbuild\appveyor_install_pypy3.cmd
- }
-- ps: |
- if ($env:PYTHON -eq "c:/msys64/mingw32")
- {
- c:\msys64\usr\bin\bash -l -c c:\\pillow\\winbuild\\appveyor_install_msys2_deps.sh
- }
- else
- {
- c:\python37\python.exe c:\pillow\winbuild\build_dep.py
- c:\pillow\winbuild\build_deps.cmd
- $host.SetShouldExit(0)
- }
+- 7z x ..\pillow-depends\nasm-2.14.02-win64.zip -oc:\
- curl -fsSL -o gs952.exe https://github.com/ArtifexSoftware/ghostpdl-downloads/releases/download/gs952/gs952w32.exe
- gs952.exe /S
-- path %path%;C:\Program Files (x86)\gs\gs9.52\bin
+- path c:\nasm-2.14.02;C:\Program Files (x86)\gs\gs9.52\bin;%PATH%
+- cd c:\pillow\winbuild\
+- ps: |
+ c:\python37\python.exe c:\pillow\winbuild\build_prepare.py -v --depends=C:\pillow-depends\
+ c:\pillow\winbuild\build\build_dep_all.cmd
+ $host.SetShouldExit(0)
+- path C:\pillow\winbuild\build\bin;%PATH%
build_script:
- ps: |
- if ($env:PYTHON -eq "c:/msys64/mingw32")
- {
- c:\msys64\usr\bin\bash -l -c c:\\pillow\\winbuild\\appveyor_build_msys2.sh
- Write-Host "through install"
+ c:\pillow\winbuild\build\build_pillow.cmd install
$host.SetShouldExit(0)
- }
- else
- {
- & $env:PYTHON/$env:EXECUTABLE c:\pillow\winbuild\build.py
- $host.SetShouldExit(0)
- }
- cd c:\pillow
- '%PYTHON%\%EXECUTABLE% selftest.py --installed'
@@ -99,7 +68,7 @@ before_deploy:
- cd c:\pillow
- '%PYTHON%\%PIP_DIR%\pip.exe install wheel'
- cd c:\pillow\winbuild\
- - '%PYTHON%\%EXECUTABLE% c:\pillow\winbuild\build.py --wheel'
+ - c:\pillow\winbuild\build\build_pillow.cmd bdist_wheel
- cd c:\pillow
- ps: Get-ChildItem .\dist\*.* | % { Push-AppveyorArtifact $_.FullName -FileName $_.Name }
diff --git a/.ci/install.sh b/.ci/install.sh
index 180fa6582..8a3b8fee4 100755
--- a/.ci/install.sh
+++ b/.ci/install.sh
@@ -1,8 +1,22 @@
#!/bin/bash
+aptget_update()
+{
+ if [ ! -z $1 ]; then
+ echo ""
+ echo "Retrying apt-get update..."
+ echo ""
+ fi
+ output=`sudo apt-get update 2>&1`
+ echo "$output"
+ if [[ $output == *[WE]:\ * ]]; then
+ return 1
+ fi
+}
+aptget_update || aptget_update retry || aptget_update retry
+
set -e
-sudo apt-get update
sudo apt-get -qq install libfreetype6-dev liblcms2-dev python3-tk\
ghostscript libffi-dev libjpeg-turbo-progs libopenjp2-7-dev\
cmake imagemagick libharfbuzz-dev libfribidi-dev
@@ -20,7 +34,7 @@ if [[ $TRAVIS_PYTHON_VERSION == 3.* ]]; then
# arm64, ppc64le, s390x CPUs:
# "ERROR: Could not find a version that satisfies the requirement pyqt5"
if [[ $TRAVIS_CPU_ARCH == "amd64" ]]; then
- sudo apt-get -qq install pyqt5-dev-tools
+ sudo apt-get -qq install libxcb-xinerama0 pyqt5-dev-tools
pip install pyqt5
fi
fi
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index 3cad8d417..6c5d81ac4 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -13,7 +13,7 @@ jobs:
name: Python ${{ matrix.python-version }}
steps:
- - uses: actions/checkout@v1
+ - uses: actions/checkout@v2
- name: pip cache
uses: actions/cache@v1
diff --git a/.github/workflows/test-docker.yml b/.github/workflows/test-docker.yml
index c10f9af3e..f168304bc 100644
--- a/.github/workflows/test-docker.yml
+++ b/.github/workflows/test-docker.yml
@@ -14,6 +14,7 @@ jobs:
arch,
ubuntu-16.04-xenial-amd64,
ubuntu-18.04-bionic-amd64,
+ ubuntu-20.04-focal-amd64,
debian-9-stretch-x86,
debian-10-buster-x86,
centos-6-amd64,
@@ -21,15 +22,15 @@ jobs:
centos-8-amd64,
amazon-1-amd64,
amazon-2-amd64,
- fedora-30-amd64,
fedora-31-amd64,
+ fedora-32-amd64,
]
dockerTag: [master]
name: ${{ matrix.docker }}
steps:
- - uses: actions/checkout@v1
+ - uses: actions/checkout@v2
- name: Build system information
run: python .github/workflows/system-info.py
@@ -46,7 +47,6 @@ jobs:
sudo chown -R runner $GITHUB_WORKSPACE
- name: After success
- if: success()
run: |
PATH="$PATH:~/.local/bin"
docker start pillow_container
@@ -59,7 +59,6 @@ jobs:
MATRIX_DOCKER: ${{ matrix.docker }}
- name: Upload coverage
- if: success()
uses: codecov/codecov-action@v1
with:
flags: GHA_Docker
diff --git a/.github/workflows/test-windows.yml b/.github/workflows/test-windows.yml
index 705c61e50..7ae26b883 100644
--- a/.github/workflows/test-windows.yml
+++ b/.github/workflows/test-windows.yml
@@ -4,7 +4,6 @@ on: [push, pull_request]
jobs:
build:
-
runs-on: windows-2019
strategy:
fail-fast: false
@@ -27,14 +26,16 @@ jobs:
name: Python ${{ matrix.python-version }} ${{ matrix.architecture }}
steps:
- - uses: actions/checkout@v1
+ - name: Checkout Pillow
+ uses: actions/checkout@v2
- - uses: actions/checkout@v1
+ - name: Checkout cached dependencies
+ uses: actions/checkout@v2
with:
repository: python-pillow/pillow-depends
- ref: master
+ path: winbuild\depends
- - name: Cache
+ - name: Cache pip
uses: actions/cache@v1
with:
path: ~\AppData\Local\pip\Cache
@@ -51,291 +52,68 @@ jobs:
python-version: ${{ matrix.python-version }}
architecture: ${{ matrix.architecture }}
- - name: Build system information
+ - name: Print build system information
run: python .github/workflows/system-info.py
- name: pip install wheel pytest pytest-cov
- run: |
- "%pythonLocation%\python.exe" -m pip install wheel pytest pytest-cov
- shell: cmd
+ run: python -m pip install wheel pytest pytest-cov
- - name: Fetch dependencies
+ - name: Prepare dependencies
run: |
- 7z x ..\pillow-depends\nasm-2.14.02-win64.zip "-o$env:RUNNER_WORKSPACE\"
- Write-Host "`#`#[add-path]$env:RUNNER_WORKSPACE\nasm-2.14.02"
+ 7z x winbuild\depends\nasm-2.14.02-win64.zip "-o$env:RUNNER_WORKSPACE\"
Write-Host "::add-path::$env:RUNNER_WORKSPACE\nasm-2.14.02"
- ..\pillow-depends\gs950w32.exe /S
- Write-Host "`#`#[add-path]C:\Program Files (x86)\gs\gs9.50\bin"
+ winbuild\depends\gs950w32.exe /S
Write-Host "::add-path::C:\Program Files (x86)\gs\gs9.50\bin"
- $env:PYTHON=$env:pythonLocation
- xcopy ..\pillow-depends\*.zip $env:GITHUB_WORKSPACE\winbuild\
- xcopy ..\pillow-depends\*.tar.gz $env:GITHUB_WORKSPACE\winbuild\
- xcopy /s ..\pillow-depends\test_images\* $env:GITHUB_WORKSPACE\tests\images\
- cd $env:GITHUB_WORKSPACE/winbuild/
- python.exe $env:GITHUB_WORKSPACE\winbuild\build_dep.py
- env:
- EXECUTABLE: bin\python.exe
+ xcopy /s winbuild\depends\test_images\* Tests\images\
+
+ & python.exe winbuild\build_prepare.py -v --python=$env:pythonLocation
shell: pwsh
- - name: Build dependencies / libjpeg
- if: false
- run: |
- REM FIXME uses /MT not /MD, see makefile.vc and win32.mak for more info
-
- set INCLUDE=C:\Program Files (x86)\Microsoft SDKs\Windows\V7.1A\Include
- set INCLIB=%GITHUB_WORKSPACE%\winbuild\depends\msvcr10-x32
- set BUILD=%GITHUB_WORKSPACE%\winbuild\build
- cd /D %BUILD%\jpeg-9d
- call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" ${{ matrix.platform-vcvars }}
- echo on
- nmake -nologo -f makefile.vc setup-vc6
- nmake -nologo -f makefile.vc clean
- nmake -nologo -f makefile.vc nodebug=1 libjpeg.lib cjpeg.exe djpeg.exe
- copy /Y /B j*.h %INCLIB%
- copy /Y /B *.lib %INCLIB%
- copy /Y /B *.exe %INCLIB%
- shell: cmd
-
- name: Build dependencies / libjpeg-turbo
- run: |
- set INCLUDE=C:\Program Files (x86)\Microsoft SDKs\Windows\V7.1A\Include
- set INCLIB=%GITHUB_WORKSPACE%\winbuild\depends\msvcr10-x32
- set BUILD=%GITHUB_WORKSPACE%\winbuild\build
- cd /D %BUILD%\libjpeg-turbo-2.0.3
- call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" ${{ matrix.platform-vcvars }}
- echo on
- set CMAKE=cmake.exe -DCMAKE_VERBOSE_MAKEFILE=ON -DCMAKE_RULE_MESSAGES:BOOL=OFF
- set CMAKE=%CMAKE% -DENABLE_SHARED:BOOL=OFF -DWITH_JPEG8:BOOL=TRUE -DWITH_CRT_DLL:BOOL=TRUE -DCMAKE_BUILD_TYPE=Release
- %CMAKE% -G "NMake Makefiles" .
- nmake -nologo -f Makefile clean
- nmake -nologo -f Makefile jpeg-static cjpeg-static djpeg-static
- copy /Y /B j*.h %INCLIB%
- copy /Y /B jpeg-static.lib %INCLIB%\libjpeg.lib
- copy /Y /B cjpeg-static.exe %INCLIB%\cjpeg.exe
- copy /Y /B djpeg-static.exe %INCLIB%\djpeg.exe
- shell: cmd
-
+ run: "& winbuild\\build\\build_dep_libjpeg.cmd"
- name: Build dependencies / zlib
- run: |
- set INCLUDE=C:\Program Files (x86)\Microsoft SDKs\Windows\V7.1A\Include
- set INCLIB=%GITHUB_WORKSPACE%\winbuild\depends\msvcr10-x32
- set BUILD=%GITHUB_WORKSPACE%\winbuild\build
- cd /D %BUILD%\zlib-1.2.11
- call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" ${{ matrix.platform-vcvars }}
- echo on
- nmake -nologo -f win32\Makefile.msc clean
- nmake -nologo -f win32\Makefile.msc zlib.lib
- copy /Y /B z*.h %INCLIB%
- copy /Y /B *.lib %INCLIB%
- copy /Y /B zlib.lib %INCLIB%\z.lib
- shell: cmd
-
- - name: Build dependencies / LibTIFF
- run: |
- set INCLUDE=C:\Program Files (x86)\Microsoft SDKs\Windows\V7.1A\Include
- set INCLIB=%GITHUB_WORKSPACE%\winbuild\depends\msvcr10-x32
- set BUILD=%GITHUB_WORKSPACE%\winbuild\build
- cd /D %BUILD%\tiff-4.1.0
- call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" ${{ matrix.platform-vcvars }}
- echo on
- copy %GITHUB_WORKSPACE%\winbuild\tiff.opt nmake.opt
- nmake -nologo -f makefile.vc clean
- nmake -nologo -f makefile.vc lib
- copy /Y /B libtiff\tiff*.h %INCLIB%
- copy /Y /B libtiff\*.dll %INCLIB%
- copy /Y /B libtiff\*.lib %INCLIB%
- shell: cmd
-
+ run: "& winbuild\\build\\build_dep_zlib.cmd"
+ - name: Build dependencies / LibTiff
+ run: "& winbuild\\build\\build_dep_libtiff.cmd"
- name: Build dependencies / WebP
- run: |
- set INCLUDE=C:\Program Files (x86)\Microsoft SDKs\Windows\V7.1A\Include
- set INCLIB=%GITHUB_WORKSPACE%\winbuild\depends\msvcr10-x32
- set BUILD=%GITHUB_WORKSPACE%\winbuild\build
- cd /D %BUILD%\libwebp-1.1.0
- call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" ${{ matrix.platform-vcvars }}
- echo on
- rmdir /S /Q output\release-static
- nmake -nologo -f Makefile.vc CFG=release-static OBJDIR=output ARCH=${{ matrix.architecture }} all
- mkdir %INCLIB%\webp
- copy /Y /B src\webp\*.h %INCLIB%\webp
- copy /Y /B output\release-static\${{ matrix.architecture }}\lib\* %INCLIB%
- shell: cmd
-
+ run: "& winbuild\\build\\build_dep_libwebp.cmd"
- name: Build dependencies / FreeType
- run: |
- REM Toolkit v100 not available; missing VCTargetsPath; Clean fails
-
- set INCLUDE=C:\Program Files (x86)\Microsoft SDKs\Windows\V7.1A\Include
- set INCLIB=%GITHUB_WORKSPACE%\winbuild\depends\msvcr10-x32
- set BUILD=%GITHUB_WORKSPACE%\winbuild\build
- cd /D %BUILD%\freetype-2.10.1
- call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" ${{ matrix.platform-vcvars }}
- echo on
- rmdir /S /Q objs
- set DefaultPlatformToolset=v142
- set VCTargetsPath=C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Microsoft\VC\v160\
- set MSBUILD="C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\MSBuild.exe"
- powershell -Command "(gc builds\windows\vc2010\freetype.vcxproj) -replace 'MultiThreaded<', 'MultiThreadedDLL<' | Out-File -encoding ASCII builds\windows\vc2010\freetype.vcxproj"
- %MSBUILD% builds\windows\vc2010\freetype.sln /t:Build /p:Configuration="Release Static" /p:Platform=${{ matrix.platform-msbuild }} /m
- xcopy /Y /E /Q include %INCLIB%
- copy /Y /B "objs\${{ matrix.platform-msbuild }}\Release Static\freetype.lib" %INCLIB%
- shell: cmd
-
+ run: "& winbuild\\build\\build_dep_freetype.cmd"
- name: Build dependencies / LCMS2
- run: |
- set INCLUDE=C:\Program Files (x86)\Microsoft SDKs\Windows\V7.1A\Include
- set INCLIB=%GITHUB_WORKSPACE%\winbuild\depends\msvcr10-x32
- set BUILD=%GITHUB_WORKSPACE%\winbuild\build
- cd /D %BUILD%\lcms2-2.8
- call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" ${{ matrix.platform-vcvars }}
- echo on
- rmdir /S /Q Lib
- rmdir /S /Q Projects\VC2015\Release
- set VCTargetsPath=C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Microsoft\VC\v160\
- set MSBUILD="C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\MSBuild.exe"
- powershell %GITHUB_WORKSPACE%\winbuild\lcms2_patch.ps1
- %MSBUILD% Projects\VC2015\lcms2.sln /t:Clean;lcms2_static /p:Configuration="Release" /p:Platform=${{ matrix.platform-msbuild }} /m
- xcopy /Y /E /Q include %INCLIB%
- copy /Y /B Lib\MS\*.lib %INCLIB%
- shell: cmd
-
+ run: "& winbuild\\build\\build_dep_lcms2.cmd"
- name: Build dependencies / OpenJPEG
- run: |
- set INCLUDE=C:\Program Files (x86)\Microsoft SDKs\Windows\V7.1A\Include
- set INCLIB=%GITHUB_WORKSPACE%\winbuild\depends\msvcr10-x32
- set BUILD=%GITHUB_WORKSPACE%\winbuild\build
- cd /D %BUILD%\openjpeg-2.3.1msvcr10-x32
- call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" ${{ matrix.platform-vcvars }}
- echo on
- set CMAKE=cmake.exe -DCMAKE_VERBOSE_MAKEFILE=ON -DCMAKE_RULE_MESSAGES:BOOL=OFF
- set CMAKE=%CMAKE% -DBUILD_THIRDPARTY:BOOL=OFF -DBUILD_SHARED_LIBS:BOOL=OFF
- set CMAKE=%CMAKE% -DCMAKE_BUILD_TYPE=Release
- %CMAKE% -G "NMake Makefiles" .
- nmake -nologo -f Makefile clean
- nmake -nologo -f Makefile
- mkdir %INCLIB%\openjpeg-2.3.1
- copy /Y /B src\lib\openjp2\*.h %INCLIB%\openjpeg-2.3.1
- copy /Y /B bin\*.lib %INCLIB%
- shell: cmd
+ run: "& winbuild\\build\\build_dep_openjpeg.cmd"
# GPL licensed; skip if building wheels
- name: Build dependencies / libimagequant
- if: "github.event_name != 'push' || contains(matrix.python-version, 'pypy')"
- run: |
- set INCLUDE=C:\Program Files (x86)\Microsoft SDKs\Windows\V7.1A\Include
- set INCLIB=%GITHUB_WORKSPACE%\winbuild\depends\msvcr10-x32
- set BUILD=%GITHUB_WORKSPACE%\winbuild\build
- rem e5d454b: Merge tag '2.12.6' into msvc
- cd /D %BUILD%\libimagequant-e5d454bc7f5eb63ee50c84a83a7fa5ac94f68ec4
- call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" ${{ matrix.platform-vcvars }}
- echo on
- echo (gc CMakeLists.txt) -replace 'add_library', "add_compile_options(-openmp-)`r`nadd_library" ^| Out-File -encoding ASCII CMakeLists.txt > patch.ps1
- echo (gc CMakeLists.txt) -replace ' SHARED', ' STATIC' ^| Out-File -encoding ASCII CMakeLists.txt >> patch.ps1
- powershell .\patch.ps1
- set CMAKE=cmake.exe -DCMAKE_VERBOSE_MAKEFILE=ON -DCMAKE_RULE_MESSAGES:BOOL=OFF
- set CMAKE=%CMAKE% -DCMAKE_BUILD_TYPE=Release
- %CMAKE% -G "NMake Makefiles" .
- nmake -nologo -f Makefile clean
- nmake -nologo -f Makefile
- copy /Y /B *.h %INCLIB%
- copy /Y /B *.lib %INCLIB%
- shell: cmd
+ if: "github.event_name != 'push'"
+ run: "& winbuild\\build\\build_dep_libimagequant.cmd"
- # for Raqm
+ # Raqm dependencies
- name: Build dependencies / HarfBuzz
- run: |
- set INCLUDE=C:\Program Files (x86)\Microsoft SDKs\Windows\V7.1A\Include
- set INCLIB=%GITHUB_WORKSPACE%\winbuild\depends\msvcr10-x32
- set BUILD=%GITHUB_WORKSPACE%\winbuild\build
- set INCLUDE=%INCLUDE%;%INCLIB%
- set LIB=%LIB%;%INCLIB%
- cd /D %BUILD%\harfbuzz-2.6.4
- call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" ${{ matrix.platform-vcvars }}
- echo on
- set CMAKE=cmake.exe -DCMAKE_VERBOSE_MAKEFILE=ON -DCMAKE_RULE_MESSAGES:BOOL=OFF
- set CMAKE=%CMAKE% -DHB_HAVE_FREETYPE:BOOL=ON -DCMAKE_BUILD_TYPE=Release
- %CMAKE% -G "NMake Makefiles" .
- nmake -nologo -f Makefile clean
- nmake -nologo -f Makefile harfbuzz
- copy /Y /B src\*.h %INCLIB%
- copy /Y /B *.lib %INCLIB%
- shell: cmd
-
- # for Raqm
+ run: "& winbuild\\build\\build_dep_harfbuzz.cmd"
- name: Build dependencies / FriBidi
- run: |
- set INCLUDE=C:\Program Files (x86)\Microsoft SDKs\Windows\V7.1A\Include
- set INCLIB=%GITHUB_WORKSPACE%\winbuild\depends\msvcr10-x32
- set BUILD=%GITHUB_WORKSPACE%\winbuild\build
- cd /D %BUILD%\fribidi-1.0.9
- call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" ${{ matrix.platform-vcvars }}
- echo on
- copy /Y /B %GITHUB_WORKSPACE%\winbuild\fribidi.cmake CMakeLists.txt
- set CMAKE=cmake.exe -DCMAKE_VERBOSE_MAKEFILE=ON -DCMAKE_RULE_MESSAGES:BOOL=OFF
- set CMAKE=%CMAKE% -DCMAKE_BUILD_TYPE=Release
- %CMAKE% -G "NMake Makefiles" .
- nmake -nologo -f Makefile clean
- nmake -nologo -f Makefile fribidi
- copy /Y /B lib\*.h %INCLIB%
- copy /Y /B *.lib %INCLIB%
- shell: cmd
-
+ run: "& winbuild\\build\\build_dep_fribidi.cmd"
- name: Build dependencies / Raqm
- run: |
- set INCLUDE=C:\Program Files (x86)\Microsoft SDKs\Windows\V7.1A\Include
- set INCLIB=%GITHUB_WORKSPACE%\winbuild\depends\msvcr10-x32
- set BUILD=%GITHUB_WORKSPACE%\winbuild\build
- set INCLUDE=%INCLUDE%;%INCLIB%
- set LIB=%LIB%;%INCLIB%
- cd /D %BUILD%\libraqm-0.7.0
- call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" ${{ matrix.platform-vcvars }}
- echo on
- copy /Y /B %GITHUB_WORKSPACE%\winbuild\raqm.cmake CMakeLists.txt
- set CMAKE=cmake.exe -DCMAKE_VERBOSE_MAKEFILE=ON -DCMAKE_RULE_MESSAGES:BOOL=OFF
- set CMAKE=%CMAKE% -DCMAKE_BUILD_TYPE=Release
- %CMAKE% -G "NMake Makefiles" .
- nmake -nologo -f Makefile clean
- nmake -nologo -f Makefile libraqm
- copy /Y /B src\*.h %INCLIB%
- copy /Y /B libraqm.dll %INCLIB%
- shell: cmd
+ run: "& winbuild\\build\\build_dep_libraqm.cmd"
- name: Build Pillow
run: |
- set PYTHON=%pythonLocation%
- set INCLUDE=C:\Program Files (x86)\Microsoft SDKs\Windows\V7.1A\Include
- set MPLSRC=%GITHUB_WORKSPACE%
- set INCLIB=%GITHUB_WORKSPACE%\winbuild\depends\msvcr10-x32
- cd /D %GITHUB_WORKSPACE%
- set LIB=%INCLIB%;%PYTHON%\tcl
- set INCLUDE=%INCLIB%;%GITHUB_WORKSPACE%\depends\tcl86\include;%INCLUDE%
- call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" ${{ matrix.platform-vcvars }}
- set MSSdk=1
- set DISTUTILS_USE_SDK=1
- set py_vcruntime_redist=true
- %PYTHON%\python.exe setup.py build_ext install
- rem Add libraqm.dll (copied to INCLIB) to PATH.
- path %INCLIB%;%PATH%
- %PYTHON%\python.exe selftest.py --installed
- shell: cmd
+ & winbuild\build\build_pillow.cmd install
+ & $env:pythonLocation\python.exe selftest.py --installed
+ shell: pwsh
# failing with PyPy3
- name: Enable heap verification
if: "!contains(matrix.python-version, 'pypy')"
- run: |
- c:\"Program Files (x86)"\"Windows Kits"\10\Debuggers\x86\gflags.exe /p /enable %PYTHON%\python.exe
- shell: cmd
+ run: "& 'C:\\Program Files (x86)\\Windows Kits\\10\\Debuggers\\x86\\gflags.exe' /p /enable $env:pythonLocation\\python.exe"
- name: Test Pillow
run: |
- set PYTHON=%pythonLocation%
- set INCLIB=%GITHUB_WORKSPACE%\winbuild\depends\msvcr10-x32
- rem Add libraqm.dll (copied to INCLIB) to PATH.
- path %INCLIB%;%PATH%
- cd /D %GITHUB_WORKSPACE%
- %PYTHON%\python.exe -m pytest -vx -W always --cov PIL --cov Tests --cov-report term --cov-report xml Tests
+ path %GITHUB_WORKSPACE%\\winbuild\\build\\bin;%PATH%
+ python.exe -m pytest -vx -W always --cov PIL --cov Tests --cov-report term --cov-report xml Tests
shell: cmd
- name: Prepare to upload errors
@@ -352,38 +130,100 @@ jobs:
path: Tests/errors
- name: After success
- if: success()
run: |
.ci/after_success.sh
shell: pwsh
- name: Upload coverage
- if: success()
uses: codecov/codecov-action@v1
with:
- file: ./coverage.xml
- flags: GHA_Windows
- name: ${{ runner.os }} Python ${{ matrix.python-version }}
+ file: ./coverage.xml
+ flags: GHA_Windows
+ name: ${{ runner.os }} Python ${{ matrix.python-version }} ${{ matrix.architecture }}
- name: Build wheel
id: wheel
- if: "github.event_name == 'push' && !contains(matrix.python-version, 'pypy')"
+ if: "github.event_name == 'push'"
run: |
- for /f "tokens=3 delims=/" %%a in ("${{ github.ref }}") do echo ##[set-output name=dist;]dist-%%a
for /f "tokens=3 delims=/" %%a in ("${{ github.ref }}") do echo ::set-output name=dist::dist-%%a
- set PYTHON=%pythonLocation%
- set INCLUDE=C:\Program Files (x86)\Microsoft SDKs\Windows\V7.1A\Include
- set MPLSRC=%GITHUB_WORKSPACE%
- set INCLIB=%GITHUB_WORKSPACE%\winbuild\depends\msvcr10-x32
- cd /D %GITHUB_WORKSPACE%
- set LIB=%INCLIB%;%PYTHON%\tcl
- set INCLUDE=%INCLIB%;%GITHUB_WORKSPACE%\depends\tcl86\include;%INCLUDE%
- call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" ${{ matrix.platform-vcvars }}
- %PYTHON%\python.exe setup.py bdist_wheel
+ winbuild\\build\\build_pillow.cmd bdist_wheel"
shell: cmd
- - uses: actions/upload-artifact@v1
- if: "github.event_name == 'push' && !contains(matrix.python-version, 'pypy')"
+ - uses: actions/upload-artifact@v2
+ if: "github.event_name == 'push'"
with:
name: ${{ steps.wheel.outputs.dist }}
- path: dist
+ path: dist\*.whl
+
+ msys:
+ runs-on: windows-2019
+
+ strategy:
+ fail-fast: false
+ matrix:
+ mingw: ["MINGW32", "MINGW64"]
+ include:
+ - mingw: "MINGW32"
+ package: "mingw-w64-i686"
+ - mingw: "MINGW64"
+ package: "mingw-w64-x86_64"
+
+ defaults:
+ run:
+ shell: bash.exe --login -eo pipefail "{0}"
+ env:
+ MSYSTEM: ${{ matrix.mingw }}
+ CHERE_INVOKING: 1
+
+ timeout-minutes: 30
+ name: MSYS2 ${{ matrix.mingw }}
+
+ steps:
+ - uses: actions/checkout@v2
+
+ - name: Set up shell
+ run: echo ::add-path::C:\msys64\usr\bin\
+ shell: pwsh
+
+ - name: Install Dependencies
+ run: |
+ pacman -S --noconfirm \
+ ${{ matrix.package }}-python3-pip \
+ ${{ matrix.package }}-python3-setuptools \
+ ${{ matrix.package }}-python3-pytest \
+ ${{ matrix.package }}-python3-pytest-cov \
+ ${{ matrix.package }}-python3-cffi \
+ ${{ matrix.package }}-python3-olefile \
+ ${{ matrix.package }}-python3-numpy \
+ ${{ matrix.package }}-python3-pyqt5 \
+ ${{ matrix.package }}-python3-numpy \
+ ${{ matrix.package }}-freetype \
+ ${{ matrix.package }}-lcms2 \
+ ${{ matrix.package }}-libwebp \
+ ${{ matrix.package }}-libjpeg-turbo \
+ ${{ matrix.package }}-openjpeg2 \
+ ${{ matrix.package }}-libimagequant \
+ ${{ matrix.package }}-libraqm \
+ ${{ matrix.package }}-ghostscript \
+ subversion
+
+ python3 -m pip install pyroma
+
+ pushd depends && ./install_extra_test_images.sh && popd
+
+ - name: Build Pillow
+ run: |
+ # libtiff is unable to open files
+ CFLAGS="-coverage" python3 setup.py build_ext --disable-tiff install
+
+ - name: Test Pillow
+ run: |
+ python3 selftest.py --installed
+ python3 -m pytest -vx --cov PIL --cov Tests --cov-report term --cov-report xml Tests
+
+ - name: Upload coverage
+ run: |
+ python3 -m pip install codecov
+ bash <(curl -s https://codecov.io/bash) -F GHA_Windows
+ env:
+ CODECOV_NAME: MSYS2 ${{ matrix.mingw }}
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index f1643edd6..b8d2c6374 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -95,13 +95,17 @@ jobs:
name: errors
path: Tests/errors
+ - name: Docs
+ if: startsWith(matrix.os, 'ubuntu') && matrix.python-version == 3.8
+ run: |
+ pip install sphinx-rtd-theme
+ make doccheck
+
- name: After success
- if: success()
run: |
.ci/after_success.sh
- name: Upload coverage
- if: success()
run: bash <(curl -s https://codecov.io/bash) -F ${{ matrix.codecov-flag }}
env:
CODECOV_NAME: ${{ matrix.os }} Python ${{ matrix.python-version }}
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index e30453c3e..a37674036 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -1,6 +1,6 @@
repos:
- repo: https://github.com/psf/black
- rev: 19.10b0
+ rev: 6bedb5c58a7d8c25aa9509f8217bc24e9797e90d # frozen: 19.10b0
hooks:
- id: black
args: ["--target-version", "py35"]
@@ -8,25 +8,36 @@ repos:
files: \.py$
types: []
+ - repo: https://github.com/timothycrosley/isort
+ rev: 7c29dd9d55161704cfc45998c6f5c2c43d39264b # frozen: 4.3.21
+ hooks:
+ - id: isort
+
+ - repo: https://github.com/asottile/yesqa
+ rev: b13a51aa54142c59219c764e9f9362c049b439ed # frozen: v1.2.0
+ hooks:
+ - id: yesqa
+
+ - repo: https://github.com/Lucas-C/pre-commit-hooks
+ rev: ffbd448645bad2e7ca13f96fca5830058d27ccd5 # frozen: v1.1.7
+ hooks:
+ - id: remove-tabs
+ exclude: (Makefile$|\.bat$|\.cmake$|\.eps$|\.fits$|\.opt$)
+
- repo: https://gitlab.com/pycqa/flake8
- rev: 3.7.9
+ rev: 735cfe7e1c57a8e05f660ba75de72313005af54a # frozen: 3.8.2
hooks:
- id: flake8
additional_dependencies: [flake8-2020, flake8-implicit-str-concat]
- - repo: https://github.com/timothycrosley/isort
- rev: 4.3.21
- hooks:
- - id: isort
-
- repo: https://github.com/pre-commit/pygrep-hooks
- rev: v1.5.1
+ rev: 0d7d077d6ed5624854f93ac601739c1804ebeb98 # frozen: v1.5.1
hooks:
- id: python-check-blanket-noqa
- id: rst-backticks
- repo: https://github.com/pre-commit/pre-commit-hooks
- rev: v2.5.0
+ rev: ebc15addedad713c86ef18ae9632c88e187dd0af # frozen: v3.1.0
hooks:
- id: check-merge-conflict
- id: check-yaml
diff --git a/.travis.yml b/.travis.yml
index e77102e44..980506368 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -28,6 +28,9 @@ matrix:
- python: "pypy3"
name: "PyPy3 Xenial"
+ - python: "3.9-dev"
+ name: "3.9-dev Xenial"
+ services: xvfb
- python: "3.8"
name: "3.8 Xenial"
services: xvfb
diff --git a/CHANGES.rst b/CHANGES.rst
index 4ece866f2..566e055a4 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -2,6 +2,54 @@
Changelog (Pillow)
==================
+7.2.0 (unreleased)
+------------------
+
+- Use ImageFileDirectory_v2 in Image.Exif #4637
+ [radarhere]
+
+- Corrected reading EXIF metadata without prefix #4677
+ [radarhere]
+
+- Fixed drawing a jointed line with a sequence of numeric values #4580
+ [radarhere]
+
+- Added support for 1-D NumPy arrays #4608
+ [radarhere]
+
+- Parse orientation from XMP tags #4560
+ [radarhere]
+
+- Speed up text layout by not rendering glyphs #4652
+ [nulano]
+
+- Fixed ZeroDivisionError in Image.thumbnail #4625
+ [radarhere]
+
+- Replaced TiffImagePlugin DEBUG with logging #4550
+ [radarhere]
+
+- Fix repeatedly loading .gbr #4620
+ [ElinksFr, radarhere]
+
+- JPEG: Truncate icclist instead of setting to None #4613
+ [homm]
+
+- Fixes default offset for Exif #4594
+ [rodrigob, radarhere]
+
+- Fixed bug when unpickling TIFF images #4565
+ [radarhere]
+
+- Fix pickling WebP #4561
+ [hugovk, radarhere]
+
+7.1.2 (2020-04-25)
+------------------
+
+- Raise an EOFError when seeking too far in PNG #4528
+ [radarhere]
+
7.1.1 (2020-04-02)
------------------
@@ -5295,23 +5343,23 @@ Pre-fork
+ Added keyword options to the "save" method. The following options
are currently supported:
- format option description
+ Format Option Description
--------------------------------------------------------
- JPEG optimize minimize output file at the
- expense of compression speed.
+ JPEG optimize Minimize output file at the
+ expense of compression speed.
- JPEG progressive enable progressive output. the
- option value is ignored.
+ JPEG progressive Enable progressive output.
+ The option value is ignored.
- JPEG quality set compression quality (1-100).
- the default value is 75.
+ JPEG quality Set compression quality (1-100).
+ The default value is 75.
- JPEG smooth smooth dithered images. value
- is strength (1-100). default is
- off (0).
+ JPEG smooth Smooth dithered images.
+ Value is strength (1-100).
+ Default is off (0).
- PNG optimize minimize output file at the
- expense of compression speed.
+ PNG optimize Minimize output file at the
+ expense of compression speed.
Expect more options in future releases. Also note that
file writers silently ignore unknown options.
@@ -5332,31 +5380,31 @@ Pre-fork
+ Various improvements to the sample scripts:
"pilconvert" Carries out some extra tricks in order to make
- the resulting file as small as possible.
+ the resulting file as small as possible.
- "explode" (NEW) Split an image sequence into individual frames.
+ "explode" (NEW) Split an image sequence into individual frames.
- "gifmaker" (NEW) Convert a sequence file into a GIF animation.
- Note that the GIF encoder create "uncompressed" GIF
- files, so animations created by this script are
- rather large (typically 2-5 times the compressed
- sizes).
+ "gifmaker" (NEW) Convert a sequence file into a GIF animation.
+ Note that the GIF encoder create "uncompressed" GIF
+ files, so animations created by this script are
+ rather large (typically 2-5 times the compressed
+ sizes).
- "image2py" (NEW) Convert a single image to a python module. See
- comments in this script for details.
+ "image2py" (NEW) Convert a single image to a python module. See
+ comments in this script for details.
- "player" If multiple images are given on the command line,
- they are interpreted as frames in a sequence. The
- script assumes that they all have the same size.
- Also note that this script now can play FLI/FLC
- and GIF animations.
+ "player" If multiple images are given on the command line,
+ they are interpreted as frames in a sequence. The
+ script assumes that they all have the same size.
+ Also note that this script now can play FLI/FLC
+ and GIF animations.
This player can also execute embedded Python
animation applets (ARG format only).
- "viewer" Transparent images ("P" with transparency property,
- and "RGBA") are superimposed on the standard Tk back-
- ground.
+ "viewer" Transparent images ("P" with transparency property,
+ and "RGBA") are superimposed on the standard Tk back-
+ ground.
+ Fixed colour argument to "new". For multilayer images, pass a
tuple: (Red, Green, Blue), (Red, Green, Blue, Alpha), or (Cyan,
diff --git a/MANIFEST.in b/MANIFEST.in
index a5f726b04..f5d367fdd 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -21,10 +21,8 @@ exclude .appveyor.yml
exclude .coveragerc
exclude .editorconfig
exclude .readthedocs.yml
-exclude azure-pipelines.yml
exclude codecov.yml
global-exclude .git*
global-exclude *.pyc
global-exclude *.so
-prune .azure-pipelines
prune .ci
diff --git a/Makefile b/Makefile
index 6e55e4c7a..06208ad98 100644
--- a/Makefile
+++ b/Makefile
@@ -67,7 +67,7 @@ debug:
CFLAGS='-g -O0' python3 setup.py build_ext install > /dev/null
install-req:
- pip install -r requirements.txt
+ python3 -m pip install -r requirements.txt
install-venv:
virtualenv .
diff --git a/RELEASING.md b/RELEASING.md
index 3a285662c..a33a1684a 100644
--- a/RELEASING.md
+++ b/RELEASING.md
@@ -6,7 +6,10 @@ Released quarterly on January 2nd, April 1st, July 1st and October 15th.
* [ ] Open a release ticket e.g. https://github.com/python-pillow/Pillow/issues/3154
* [ ] Develop and prepare release in `master` branch.
-* [ ] Check [Travis CI](https://travis-ci.org/python-pillow/Pillow) and [AppVeyor CI](https://ci.appveyor.com/project/python-pillow/Pillow) to confirm passing tests in `master` branch.
+* [ ] Check [GitHub Actions](https://github.com/python-pillow/Pillow/actions),
+ [Travis CI](https://travis-ci.org/github/python-pillow/Pillow) and
+ [AppVeyor](https://ci.appveyor.com/project/python-pillow/Pillow) to confirm
+ passing tests in `master` branch.
* [ ] Check that all of the wheel builds [Pillow Wheel Builder](https://github.com/python-pillow/pillow-wheels) pass the tests in Travis CI.
* [ ] In compliance with [PEP 440](https://www.python.org/dev/peps/pep-0440/), update version identifier in `src/PIL/_version.py`
* [ ] Update `CHANGES.rst`.
@@ -38,12 +41,19 @@ Released as needed for security, installation or critical bug fixes.
git checkout -t remotes/origin/5.2.x
```
* [ ] Cherry pick individual commits from `master` branch to release branch e.g. `5.2.x`.
-* [ ] Check [Travis CI](https://travis-ci.org/python-pillow/Pillow) to confirm passing tests in release branch e.g. `5.2.x`.
+
+
+
+* [ ] Check [GitHub Actions](https://github.com/python-pillow/Pillow/actions),
+ [Travis CI](https://travis-ci.org/github/python-pillow/Pillow) and
+ [AppVeyor](https://ci.appveyor.com/project/python-pillow/Pillow) to confirm
+ passing tests in release branch e.g. `5.2.x`.
* [ ] In compliance with [PEP 440](https://www.python.org/dev/peps/pep-0440/), update version identifier in `src/PIL/_version.py`
* [ ] Run pre-release check via `make release-test`.
* [ ] Create tag for release e.g.:
```bash
git tag 5.2.1
+ git push
git push --tags
```
* [ ] Create source distributions e.g.:
diff --git a/Tests/check_j2k_overflow.py b/Tests/check_j2k_overflow.py
index f20ad6748..7a0a5f948 100644
--- a/Tests/check_j2k_overflow.py
+++ b/Tests/check_j2k_overflow.py
@@ -5,5 +5,5 @@ from PIL import Image
def test_j2k_overflow(tmp_path):
im = Image.new("RGBA", (1024, 131584))
target = str(tmp_path / "temp.jpc")
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.save(target)
diff --git a/Tests/check_libtiff_segfault.py b/Tests/check_libtiff_segfault.py
index 5187385d6..6663ac097 100644
--- a/Tests/check_libtiff_segfault.py
+++ b/Tests/check_libtiff_segfault.py
@@ -9,6 +9,6 @@ def test_libtiff_segfault():
libtiff >= 4.0.0
"""
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
with Image.open(TEST_FILE) as im:
im.load()
diff --git a/Tests/helper.py b/Tests/helper.py
index 15a51ccd1..7e8abc9c9 100644
--- a/Tests/helper.py
+++ b/Tests/helper.py
@@ -6,6 +6,7 @@ import logging
import os
import shutil
import sys
+import sysconfig
import tempfile
from io import BytesIO
@@ -272,12 +273,8 @@ def on_github_actions():
def on_ci():
- # Travis and AppVeyor have "CI"
- # Azure Pipelines has "TF_BUILD"
- # GitHub Actions has "GITHUB_ACTIONS"
- return (
- "CI" in os.environ or "TF_BUILD" in os.environ or "GITHUB_ACTIONS" in os.environ
- )
+ # GitHub Actions, Travis and AppVeyor have "CI"
+ return "CI" in os.environ
def is_big_endian():
@@ -292,6 +289,10 @@ def is_pypy():
return hasattr(sys, "pypy_translation_info")
+def is_mingw():
+ return sysconfig.get_platform() == "mingw"
+
+
if sys.platform == "win32":
IMCONVERT = os.environ.get("MAGICK_HOME", "")
if IMCONVERT:
diff --git a/Tests/images/icc-after-SOF.jpg b/Tests/images/icc-after-SOF.jpg
new file mode 100644
index 000000000..a284a2298
Binary files /dev/null and b/Tests/images/icc-after-SOF.jpg differ
diff --git a/Tests/images/imagedraw_polygon_1px_high.png b/Tests/images/imagedraw_polygon_1px_high.png
new file mode 100644
index 000000000..e06508a0a
Binary files /dev/null and b/Tests/images/imagedraw_polygon_1px_high.png differ
diff --git a/Tests/images/variation_adobe.png b/Tests/images/variation_adobe.png
index 71b879bc5..3ac326f51 100644
Binary files a/Tests/images/variation_adobe.png and b/Tests/images/variation_adobe.png differ
diff --git a/Tests/images/variation_adobe_axes.png b/Tests/images/variation_adobe_axes.png
index 9376c1d7b..93cad98ff 100644
Binary files a/Tests/images/variation_adobe_axes.png and b/Tests/images/variation_adobe_axes.png differ
diff --git a/Tests/images/variation_adobe_name.png b/Tests/images/variation_adobe_name.png
index 9e5fe70e5..acb0df63c 100644
Binary files a/Tests/images/variation_adobe_name.png and b/Tests/images/variation_adobe_name.png differ
diff --git a/Tests/images/variation_adobe_older_harfbuzz.png b/Tests/images/variation_adobe_older_harfbuzz.png
new file mode 100644
index 000000000..71b879bc5
Binary files /dev/null and b/Tests/images/variation_adobe_older_harfbuzz.png differ
diff --git a/Tests/images/variation_adobe_older_harfbuzz_axes.png b/Tests/images/variation_adobe_older_harfbuzz_axes.png
new file mode 100644
index 000000000..9376c1d7b
Binary files /dev/null and b/Tests/images/variation_adobe_older_harfbuzz_axes.png differ
diff --git a/Tests/images/variation_adobe_older_harfbuzz_name.png b/Tests/images/variation_adobe_older_harfbuzz_name.png
new file mode 100644
index 000000000..9e5fe70e5
Binary files /dev/null and b/Tests/images/variation_adobe_older_harfbuzz_name.png differ
diff --git a/Tests/images/xmp_tags_orientation.png b/Tests/images/xmp_tags_orientation.png
new file mode 100644
index 000000000..c1be1665f
Binary files /dev/null and b/Tests/images/xmp_tags_orientation.png differ
diff --git a/Tests/test_file_bufrstub.py b/Tests/test_file_bufrstub.py
index ee6f3f2a4..6803a1230 100644
--- a/Tests/test_file_bufrstub.py
+++ b/Tests/test_file_bufrstub.py
@@ -32,7 +32,7 @@ def test_load():
with Image.open(TEST_FILE) as im:
# Act / Assert: stub cannot load without an implemented handler
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.load()
@@ -42,5 +42,5 @@ def test_save(tmp_path):
tmpfile = str(tmp_path / "temp.bufr")
# Act / Assert: stub cannot save without an implemented handler
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.save(tmpfile)
diff --git a/Tests/test_file_dds.py b/Tests/test_file_dds.py
index d157e15fd..8960edea3 100644
--- a/Tests/test_file_dds.py
+++ b/Tests/test_file_dds.py
@@ -138,7 +138,7 @@ def test_short_header():
def short_header():
Image.open(BytesIO(img_file[:119]))
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
short_header()
@@ -152,7 +152,7 @@ def test_short_file():
with Image.open(BytesIO(img_file[:-100])) as im:
im.load()
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
short_file()
diff --git a/Tests/test_file_fitsstub.py b/Tests/test_file_fitsstub.py
index f9f6c4ba9..01bc2deee 100644
--- a/Tests/test_file_fitsstub.py
+++ b/Tests/test_file_fitsstub.py
@@ -30,7 +30,7 @@ def test_load():
with Image.open(TEST_FILE) as im:
# Act / Assert: stub cannot load without an implemented handler
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.load()
@@ -41,7 +41,7 @@ def test_save():
dummy_filename = "dummy.filename"
# Act / Assert: stub cannot save without an implemented handler
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.save(dummy_filename)
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
FitsStubImagePlugin._save(im, dummy_fp, dummy_filename)
diff --git a/Tests/test_file_fpx.py b/Tests/test_file_fpx.py
index ef8cdb577..a247de79c 100644
--- a/Tests/test_file_fpx.py
+++ b/Tests/test_file_fpx.py
@@ -19,5 +19,5 @@ def test_invalid_file():
def test_fpx_invalid_number_of_bands():
- with pytest.raises(IOError, match="Invalid number of bands"):
+ with pytest.raises(OSError, match="Invalid number of bands"):
Image.open("Tests/images/input_bw_five_bands.fpx")
diff --git a/Tests/test_file_gbr.py b/Tests/test_file_gbr.py
index f183390bc..b95970889 100644
--- a/Tests/test_file_gbr.py
+++ b/Tests/test_file_gbr.py
@@ -15,3 +15,11 @@ def test_gbr_file():
with Image.open("Tests/images/gbr.gbr") as im:
with Image.open("Tests/images/gbr.png") as target:
assert_image_equal(target, im)
+
+
+def test_multiple_load_operations():
+ with Image.open("Tests/images/gbr.gbr") as im:
+ im.load()
+ im.load()
+ with Image.open("Tests/images/gbr.png") as target:
+ assert_image_equal(target, im)
diff --git a/Tests/test_file_gribstub.py b/Tests/test_file_gribstub.py
index 1cc1f47ac..9d9def96b 100644
--- a/Tests/test_file_gribstub.py
+++ b/Tests/test_file_gribstub.py
@@ -32,7 +32,7 @@ def test_load():
with Image.open(TEST_FILE) as im:
# Act / Assert: stub cannot load without an implemented handler
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.load()
@@ -42,5 +42,5 @@ def test_save(tmp_path):
tmpfile = str(tmp_path / "temp.grib")
# Act / Assert: stub cannot save without an implemented handler
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.save(tmpfile)
diff --git a/Tests/test_file_hdf5stub.py b/Tests/test_file_hdf5stub.py
index 526fd7c99..862cafa91 100644
--- a/Tests/test_file_hdf5stub.py
+++ b/Tests/test_file_hdf5stub.py
@@ -30,7 +30,7 @@ def test_load():
with Image.open(TEST_FILE) as im:
# Act / Assert: stub cannot load without an implemented handler
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.load()
@@ -41,7 +41,7 @@ def test_save():
dummy_filename = "dummy.filename"
# Act / Assert: stub cannot save without an implemented handler
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.save(dummy_filename)
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
Hdf5StubImagePlugin._save(im, dummy_fp, dummy_filename)
diff --git a/Tests/test_file_jpeg.py b/Tests/test_file_jpeg.py
index 330451228..afca875de 100644
--- a/Tests/test_file_jpeg.py
+++ b/Tests/test_file_jpeg.py
@@ -147,7 +147,7 @@ class TestFileJpeg:
with Image.open("Tests/images/icc_profile_big.jpg") as im:
f = str(tmp_path / "temp.jpg")
icc_profile = im.info["icc_profile"]
- # Should not raise IOError for image with icc larger than image size.
+ # Should not raise OSError for image with icc larger than image size.
im.save(
f,
format="JPEG",
@@ -219,7 +219,7 @@ class TestFileJpeg:
gps_index = 34853
expected_exif_gps = {
0: b"\x00\x00\x00\x01",
- 2: (4294967295, 1),
+ 2: 4294967295,
5: b"\x01",
30: 65535,
29: "1999:99:99 99:99:99",
@@ -241,7 +241,7 @@ class TestFileJpeg:
36867: "2099:09:29 10:10:10",
34853: {
0: b"\x00\x00\x00\x01",
- 2: (4294967295, 1),
+ 2: 4294967295,
5: b"\x01",
30: 65535,
29: "1999:99:99 99:99:99",
@@ -253,11 +253,11 @@ class TestFileJpeg:
271: "Make",
272: "XXX-XXX",
305: "PIL",
- 42034: ((1, 1), (1, 1), (1, 1), (1, 1)),
+ 42034: (1, 1, 1, 1),
42035: "LensMake",
34856: b"\xaa\xaa\xaa\xaa\xaa\xaa",
- 282: (4294967295, 1),
- 33434: (4294967295, 1),
+ 282: 4294967295,
+ 33434: 4294967295,
}
with Image.open("Tests/images/exif_gps.jpg") as im:
@@ -379,14 +379,14 @@ class TestFileJpeg:
ImageFile.LOAD_TRUNCATED_IMAGES = False
assert im.getbbox() is not None
- def test_truncated_jpeg_throws_IOError(self):
+ def test_truncated_jpeg_throws_oserror(self):
filename = "Tests/images/truncated_jpeg.jpg"
with Image.open(filename) as im:
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.load()
# Test that the error is raised if loaded a second time
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.load()
def test_qtables(self, tmp_path):
@@ -500,7 +500,7 @@ class TestFileJpeg:
def test_load_djpeg(self):
with Image.open(TEST_FILE) as img:
img.load_djpeg()
- assert_image_similar(img, Image.open(TEST_FILE), 0)
+ assert_image_similar(img, Image.open(TEST_FILE), 5)
@pytest.mark.skipif(not cjpeg_available(), reason="cjpeg not available")
def test_save_cjpeg(self, tmp_path):
@@ -552,7 +552,7 @@ class TestFileJpeg:
out = BytesIO()
for mode in ["LA", "La", "RGBA", "RGBa", "P"]:
img = Image.new(mode, (20, 20))
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
img.save(out, "JPEG")
def test_save_tiff_with_dpi(self, tmp_path):
@@ -647,6 +647,19 @@ class TestFileJpeg:
# OSError for unidentified image.
assert im.info.get("dpi") == (72, 72)
+ def test_exif_x_resolution(self, tmp_path):
+ with Image.open("Tests/images/flower.jpg") as im:
+ exif = im.getexif()
+ assert exif[282] == 180
+
+ out = str(tmp_path / "out.jpg")
+ with pytest.warns(None) as record:
+ im.save(out, exif=exif)
+ assert len(record) == 0
+
+ with Image.open(out) as reloaded:
+ assert reloaded.getexif()[282] == 180
+
def test_invalid_exif_x_resolution(self):
# When no x or y resolution is defined in EXIF
with Image.open("Tests/images/invalid-exif-without-x-resolution.jpg") as im:
@@ -689,6 +702,10 @@ class TestFileJpeg:
apps_13_lengths = [len(v) for k, v in im.applist if k == "APP13"]
assert [65504, 24] == apps_13_lengths
+ def test_icc_after_SOF(self):
+ with Image.open("Tests/images/icc-after-SOF.jpg") as im:
+ assert im.info["icc_profile"] == b"profile"
+
@pytest.mark.skipif(not is_win32(), reason="Windows only")
@skip_unless_feature("jpg")
@@ -702,7 +719,7 @@ class TestFileCloseW32:
im = Image.open(tmpfile)
fp = im.fp
assert not fp.closed
- with pytest.raises(WindowsError):
+ with pytest.raises(OSError):
os.remove(tmpfile)
im.load()
assert fp.closed
diff --git a/Tests/test_file_jpeg2k.py b/Tests/test_file_jpeg2k.py
index 72bc7df67..7b8b7a04a 100644
--- a/Tests/test_file_jpeg2k.py
+++ b/Tests/test_file_jpeg2k.py
@@ -218,7 +218,7 @@ def test_16bit_jp2_roundtrips():
def test_unbound_local():
# prepatch, a malformed jp2 file could cause an UnboundLocalError exception.
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
Image.open("Tests/images/unbound_variable.jp2")
diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py
index 923bd6107..9523e5901 100644
--- a/Tests/test_file_libtiff.py
+++ b/Tests/test_file_libtiff.py
@@ -479,11 +479,11 @@ class TestFileLibTiff(LibTiffTestCase):
im = hopper("RGB")
out = str(tmp_path / "temp.tif")
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.save(out, compression="tiff_ccitt")
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.save(out, compression="group3")
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.save(out, compression="group4")
def test_fp_leak(self):
@@ -831,7 +831,7 @@ class TestFileLibTiff(LibTiffTestCase):
def test_realloc_overflow(self):
TiffImagePlugin.READ_LIBTIFF = True
with Image.open("Tests/images/tiff_overflow_rows_per_strip.tif") as im:
- with pytest.raises(IOError) as e:
+ with pytest.raises(OSError) as e:
im.load()
# Assert that the error code is IMAGING_CODEC_MEMORY
diff --git a/Tests/test_file_msp.py b/Tests/test_file_msp.py
index 8f261388e..9b508a4e4 100644
--- a/Tests/test_file_msp.py
+++ b/Tests/test_file_msp.py
@@ -86,5 +86,5 @@ def test_cannot_save_wrong_mode(tmp_path):
filename = str(tmp_path / "temp.msp")
# Act/Assert
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.save(filename)
diff --git a/Tests/test_file_palm.py b/Tests/test_file_palm.py
index 886332dea..38f6dccd9 100644
--- a/Tests/test_file_palm.py
+++ b/Tests/test_file_palm.py
@@ -72,19 +72,19 @@ def test_p_mode(tmp_path):
roundtrip(tmp_path, mode)
-def test_l_ioerror(tmp_path):
+def test_l_oserror(tmp_path):
# Arrange
mode = "L"
# Act / Assert
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
helper_save_as_palm(tmp_path, mode)
-def test_rgb_ioerror(tmp_path):
+def test_rgb_oserror(tmp_path):
# Arrange
mode = "RGB"
# Act / Assert
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
helper_save_as_palm(tmp_path, mode)
diff --git a/Tests/test_file_pdf.py b/Tests/test_file_pdf.py
index ea3b6c1d9..14a7a654f 100644
--- a/Tests/test_file_pdf.py
+++ b/Tests/test_file_pdf.py
@@ -172,7 +172,7 @@ def test_pdf_open(tmp_path):
def test_pdf_append_fails_on_nonexistent_file():
im = hopper("RGB")
with tempfile.TemporaryDirectory() as temp_dir:
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.save(os.path.join(temp_dir, "nonexistent.pdf"), append=True)
diff --git a/Tests/test_file_png.py b/Tests/test_file_png.py
index 476995dd7..a44bdecf8 100644
--- a/Tests/test_file_png.py
+++ b/Tests/test_file_png.py
@@ -105,7 +105,7 @@ class TestFilePng:
# file was checked into Subversion as a text file.
test_file = "Tests/images/broken.png"
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
Image.open(test_file)
def test_bad_text(self):
@@ -334,7 +334,7 @@ class TestFilePng:
def test_verify_struct_error(self):
# Check open/load/verify exception (#1755)
- # offsets to test, -10: breaks in i32() in read. (IOError)
+ # offsets to test, -10: breaks in i32() in read. (OSError)
# -13: breaks in crc, txt chunk.
# -14: malformed chunk
@@ -344,7 +344,7 @@ class TestFilePng:
with Image.open(BytesIO(test_file)) as im:
assert im.fp is not None
- with pytest.raises((IOError, SyntaxError)):
+ with pytest.raises((OSError, SyntaxError)):
im.verify()
def test_verify_ignores_crc_error(self):
@@ -463,7 +463,7 @@ class TestFilePng:
data = b"\x89" + fd.read()
pngfile = BytesIO(data)
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
Image.open(pngfile)
def test_trns_rgb(self):
@@ -575,13 +575,13 @@ class TestFilePng:
# Raises a SyntaxError in load_end
with Image.open("Tests/images/broken_data_stream.png") as im:
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
assert isinstance(im.text, dict)
# Raises a UnicodeDecodeError in load_end
with Image.open("Tests/images/truncated_image.png") as im:
# The file is truncated
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.text()
ImageFile.LOAD_TRUNCATED_IMAGES = True
assert isinstance(im.text, dict)
@@ -591,18 +591,27 @@ class TestFilePng:
with Image.open("Tests/images/hopper_idat_after_image_end.png") as im:
assert im.text == {"TXT": "VALUE", "ZIP": "VALUE"}
- @pytest.mark.parametrize(
- "test_file",
- [
- "Tests/images/exif.png", # With an EXIF chunk
- "Tests/images/exif_imagemagick.png", # With an ImageMagick zTXt chunk
- ],
- )
- def test_exif(self, test_file):
- with Image.open(test_file) as im:
+ def test_exif(self):
+ # With an EXIF chunk
+ with Image.open("Tests/images/exif.png") as im:
exif = im._getexif()
assert exif[274] == 1
+ # With an ImageMagick zTXt chunk
+ with Image.open("Tests/images/exif_imagemagick.png") as im:
+ exif = im._getexif()
+ assert exif[274] == 1
+
+ # Assert that info still can be extracted
+ # when the image is no longer a PngImageFile instance
+ exif = im.copy().getexif()
+ assert exif[274] == 1
+
+ # With XMP tags
+ with Image.open("Tests/images/xmp_tags_orientation.png") as im:
+ exif = im.getexif()
+ assert exif[274] == 3
+
def test_exif_save(self, tmp_path):
with Image.open("Tests/images/exif.png") as im:
test_file = str(tmp_path / "temp.png")
diff --git a/Tests/test_file_ppm.py b/Tests/test_file_ppm.py
index 6b91ba28a..15c08e438 100644
--- a/Tests/test_file_ppm.py
+++ b/Tests/test_file_ppm.py
@@ -64,7 +64,7 @@ def test_neg_ppm():
# has been removed. The default opener doesn't accept negative
# sizes.
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
Image.open("Tests/images/negative_size.ppm")
diff --git a/Tests/test_file_psd.py b/Tests/test_file_psd.py
index 4d8c6eba4..011efc977 100644
--- a/Tests/test_file_psd.py
+++ b/Tests/test_file_psd.py
@@ -125,5 +125,5 @@ def test_combined_larger_than_size():
# If we instead take the 'size' of the extra data field as the source of truth,
# then the seek can't be negative
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
Image.open("Tests/images/combined_larger_than_size.psd")
diff --git a/Tests/test_file_spider.py b/Tests/test_file_spider.py
index c7446e161..8c69491e6 100644
--- a/Tests/test_file_spider.py
+++ b/Tests/test_file_spider.py
@@ -134,7 +134,7 @@ def test_is_int_not_a_number():
def test_invalid_file():
invalid_file = "Tests/images/invalid.spider"
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
Image.open(invalid_file)
diff --git a/Tests/test_file_tiff.py b/Tests/test_file_tiff.py
index a996f0b0e..7aa55dad0 100644
--- a/Tests/test_file_tiff.py
+++ b/Tests/test_file_tiff.py
@@ -196,7 +196,7 @@ class TestFileTiff:
def test_save_unsupported_mode(self, tmp_path):
im = hopper("HSV")
outfile = str(tmp_path / "temp.tif")
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.save(outfile)
def test_little_endian(self):
@@ -249,7 +249,7 @@ class TestFileTiff:
assert im.getextrema() == (-3.140936851501465, 3.140684127807617)
def test_unknown_pixel_mode(self):
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
Image.open("Tests/images/hopper_unknown_pixel_mode.tif")
def test_n_frames(self):
@@ -614,7 +614,7 @@ class TestFileTiffW32:
im = Image.open(tmpfile)
fp = im.fp
assert not fp.closed
- with pytest.raises(WindowsError):
+ with pytest.raises(OSError):
os.remove(tmpfile)
im.load()
assert fp.closed
diff --git a/Tests/test_file_webp.py b/Tests/test_file_webp.py
index 22957f06d..1b8aa9f8a 100644
--- a/Tests/test_file_webp.py
+++ b/Tests/test_file_webp.py
@@ -22,7 +22,7 @@ class TestUnsupportedWebp:
WebPImagePlugin.SUPPORTED = False
file_path = "Tests/images/hopper.webp"
- pytest.warns(UserWarning, lambda: pytest.raises(IOError, Image.open, file_path))
+ pytest.warns(UserWarning, lambda: pytest.raises(OSError, Image.open, file_path))
if HAVE_WEBP:
WebPImagePlugin.SUPPORTED = True
diff --git a/Tests/test_file_webp_metadata.py b/Tests/test_file_webp_metadata.py
index 9fa20e403..a2a05f96b 100644
--- a/Tests/test_file_webp_metadata.py
+++ b/Tests/test_file_webp_metadata.py
@@ -30,6 +30,15 @@ def test_read_exif_metadata():
assert exif_data == expected_exif
+def test_read_exif_metadata_without_prefix():
+ with Image.open("Tests/images/flower2.webp") as im:
+ # Assert prefix is not present
+ assert im.info["exif"][:6] != b"Exif\x00\x00"
+
+ exif = im.getexif()
+ assert exif[305] == "Adobe Photoshop CS6 (Macintosh)"
+
+
def test_write_exif_metadata():
file_path = "Tests/images/flower.jpg"
test_buffer = BytesIO()
diff --git a/Tests/test_file_wmf.py b/Tests/test_file_wmf.py
index 03444eb9d..3339cbfd3 100644
--- a/Tests/test_file_wmf.py
+++ b/Tests/test_file_wmf.py
@@ -66,7 +66,7 @@ def test_load_set_dpi():
assert im.size == (164, 164)
with Image.open("Tests/images/drawing_wmf_ref_144.png") as expected:
- assert_image_similar(im, expected, 2.0)
+ assert_image_similar(im, expected, 2.1)
def test_save(tmp_path):
@@ -74,5 +74,5 @@ def test_save(tmp_path):
for ext in [".wmf", ".emf"]:
tmpfile = str(tmp_path / ("temp" + ext))
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.save(tmpfile)
diff --git a/Tests/test_font_pcf.py b/Tests/test_font_pcf.py
index afd0c38b2..a60163713 100644
--- a/Tests/test_font_pcf.py
+++ b/Tests/test_font_pcf.py
@@ -68,8 +68,8 @@ def test_textsize(request, tmp_path):
(dx, dy) = font.getsize(chr(i))
assert dy == 20
assert dx in (0, 10)
- for l in range(len(message)):
- msg = message[: l + 1]
+ for i in range(len(message)):
+ msg = message[: i + 1]
assert font.getsize(msg) == (len(msg) * 10, 20)
diff --git a/Tests/test_font_pcf_charsets.py b/Tests/test_font_pcf_charsets.py
index 8621f18ae..4a39803be 100644
--- a/Tests/test_font_pcf_charsets.py
+++ b/Tests/test_font_pcf_charsets.py
@@ -103,8 +103,8 @@ def _test_textsize(request, tmp_path, encoding):
assert dy == 20
assert dx in (0, 10)
message = charsets[encoding]["message"].encode(encoding)
- for l in range(len(message)):
- msg = message[: l + 1]
+ for i in range(len(message)):
+ msg = message[: i + 1]
assert font.getsize(msg) == (len(msg) * 10, 20)
diff --git a/Tests/test_image.py b/Tests/test_image.py
index 3a0b7bd62..4d1b66dff 100644
--- a/Tests/test_image.py
+++ b/Tests/test_image.py
@@ -57,7 +57,7 @@ class TestImage:
assert str(e.value) == "unrecognized image mode"
def test_exception_inheritance(self):
- assert issubclass(UnidentifiedImageError, IOError)
+ assert issubclass(UnidentifiedImageError, OSError)
def test_sanity(self):
@@ -687,5 +687,5 @@ class TestRegistry:
assert enc.args == ("RGB", "args", "extra")
def test_encode_registry_fail(self):
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
Image._getencoder("RGB", "DoesNotExist", ("args",), extra=("extra",))
diff --git a/Tests/test_image_filter.py b/Tests/test_image_filter.py
index 42f4f448d..ed71ea968 100644
--- a/Tests/test_image_filter.py
+++ b/Tests/test_image_filter.py
@@ -112,12 +112,12 @@ def test_kernel_not_enough_coefficients():
def test_consistency_3x3():
with Image.open("Tests/images/hopper.bmp") as source:
with Image.open("Tests/images/hopper_emboss.bmp") as reference:
- kernel = ImageFilter.Kernel( # noqa: E127
+ kernel = ImageFilter.Kernel(
(3, 3),
# fmt: off
(-1, -1, 0,
-1, 0, 1,
- 0, 1, 1),
+ 0, 1, 1),
# fmt: on
0.3,
)
@@ -134,14 +134,14 @@ def test_consistency_3x3():
def test_consistency_5x5():
with Image.open("Tests/images/hopper.bmp") as source:
with Image.open("Tests/images/hopper_emboss_more.bmp") as reference:
- kernel = ImageFilter.Kernel( # noqa: E127
+ kernel = ImageFilter.Kernel(
(5, 5),
# fmt: off
(-1, -1, -1, -1, 0,
-1, -1, -1, 0, 1,
-1, -1, 0, 1, 1,
-1, 0, 1, 1, 1,
- 0, 1, 1, 1, 1),
+ 0, 1, 1, 1, 1),
# fmt: on
0.3,
)
diff --git a/Tests/test_image_reduce.py b/Tests/test_image_reduce.py
index 729645a0b..353d0def0 100644
--- a/Tests/test_image_reduce.py
+++ b/Tests/test_image_reduce.py
@@ -174,8 +174,10 @@ def assert_compare_images(a, b, max_average_diff, max_diff=255):
average_diff = sum(i * num for i, num in enumerate(ch_hist)) / (
a.size[0] * a.size[1]
)
- msg = "average pixel value difference {:.4f} > expected {:.4f} "
- "for '{}' band".format(average_diff, max_average_diff, band)
+ msg = (
+ "average pixel value difference {:.4f} > expected {:.4f} "
+ "for '{}' band".format(average_diff, max_average_diff, band)
+ )
assert max_average_diff >= average_diff, msg
last_diff = [i for i, num in enumerate(ch_hist) if num > 0][-1]
diff --git a/Tests/test_image_thumbnail.py b/Tests/test_image_thumbnail.py
index f4ed8e746..da63efe55 100644
--- a/Tests/test_image_thumbnail.py
+++ b/Tests/test_image_thumbnail.py
@@ -63,6 +63,12 @@ def test_aspect():
assert im.size == (75, 23) # ratio is 3.260869565217
+def test_division_by_zero():
+ im = Image.new("L", (200, 2))
+ im.thumbnail((75, 75))
+ assert im.size == (75, 1)
+
+
def test_float():
im = Image.new("L", (128, 128))
im.thumbnail((99.9, 99.9))
diff --git a/Tests/test_imagecms.py b/Tests/test_imagecms.py
index ac34a8106..921fdc369 100644
--- a/Tests/test_imagecms.py
+++ b/Tests/test_imagecms.py
@@ -484,10 +484,10 @@ def assert_aux_channel_preserved(mode, transform_in_place, preserved_channel):
def create_test_image():
# set up test image with something interesting in the tested aux channel.
# fmt: off
- nine_grid_deltas = [ # noqa: E131
+ nine_grid_deltas = [
(-1, -1), (-1, 0), (-1, 1),
- (0, -1), (0, 0), (0, 1),
- (1, -1), (1, 0), (1, 1),
+ (0, -1), (0, 0), (0, 1),
+ (1, -1), (1, 0), (1, 1),
]
# fmt: on
chans = []
diff --git a/Tests/test_imagedraw.py b/Tests/test_imagedraw.py
index 2f1e947a6..bb1254a63 100644
--- a/Tests/test_imagedraw.py
+++ b/Tests/test_imagedraw.py
@@ -569,6 +569,20 @@ def test_polygon_kite():
assert_image_equal(im, Image.open(expected))
+def test_polygon_1px_high():
+ # Test drawing a 1px high polygon
+ # Arrange
+ im = Image.new("RGB", (3, 3))
+ draw = ImageDraw.Draw(im)
+ expected = "Tests/images/imagedraw_polygon_1px_high.png"
+
+ # Act
+ draw.polygon([(0, 1), (0, 1), (2, 1), (2, 1)], "#f00")
+
+ # Assert
+ assert_image_equal(im, Image.open(expected))
+
+
def helper_rectangle(bbox):
# Arrange
im = Image.new("RGB", (W, H))
@@ -911,28 +925,93 @@ def test_wide_line_dot():
assert_image_similar(im, Image.open(expected), 1)
-def test_line_joint():
+@pytest.mark.parametrize(
+ "xy",
+ [
+ [
+ (400, 280),
+ (380, 280),
+ (450, 280),
+ (440, 120),
+ (350, 200),
+ (310, 280),
+ (300, 280),
+ (250, 280),
+ (250, 200),
+ (150, 200),
+ (150, 260),
+ (50, 200),
+ (150, 50),
+ (250, 100),
+ ],
+ (
+ 400,
+ 280,
+ 380,
+ 280,
+ 450,
+ 280,
+ 440,
+ 120,
+ 350,
+ 200,
+ 310,
+ 280,
+ 300,
+ 280,
+ 250,
+ 280,
+ 250,
+ 200,
+ 150,
+ 200,
+ 150,
+ 260,
+ 50,
+ 200,
+ 150,
+ 50,
+ 250,
+ 100,
+ ),
+ [
+ 400,
+ 280,
+ 380,
+ 280,
+ 450,
+ 280,
+ 440,
+ 120,
+ 350,
+ 200,
+ 310,
+ 280,
+ 300,
+ 280,
+ 250,
+ 280,
+ 250,
+ 200,
+ 150,
+ 200,
+ 150,
+ 260,
+ 50,
+ 200,
+ 150,
+ 50,
+ 250,
+ 100,
+ ],
+ ],
+)
+def test_line_joint(xy):
im = Image.new("RGB", (500, 325))
draw = ImageDraw.Draw(im)
expected = "Tests/images/imagedraw_line_joint_curve.png"
# Act
- xy = [
- (400, 280),
- (380, 280),
- (450, 280),
- (440, 120),
- (350, 200),
- (310, 280),
- (300, 280),
- (250, 280),
- (250, 200),
- (150, 200),
- (150, 260),
- (50, 200),
- (150, 50),
- (250, 100),
- ]
draw.line(xy, GRAY, 50, "curve")
# Assert
diff --git a/Tests/test_imagefile.py b/Tests/test_imagefile.py
index 883e3f566..805625a24 100644
--- a/Tests/test_imagefile.py
+++ b/Tests/test_imagefile.py
@@ -71,7 +71,7 @@ class TestImageFile:
im1, im2 = roundtrip("JPEG") # lossy compression
assert_image(im1, im2.mode, im2.size)
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
roundtrip("PDF")
def test_ico(self):
@@ -95,7 +95,13 @@ class TestImageFile:
def test_raise_ioerror(self):
with pytest.raises(IOError):
- ImageFile.raise_ioerror(1)
+ with pytest.warns(DeprecationWarning) as record:
+ ImageFile.raise_ioerror(1)
+ assert len(record) == 1
+
+ def test_raise_oserror(self):
+ with pytest.raises(OSError):
+ ImageFile.raise_oserror(1)
def test_raise_typeerror(self):
with pytest.raises(TypeError):
@@ -107,17 +113,17 @@ class TestImageFile:
input = f.read()
p = ImageFile.Parser()
p.feed(input)
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
p.close()
@skip_unless_feature("zlib")
def test_truncated_with_errors(self):
with Image.open("Tests/images/truncated_image.png") as im:
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.load()
# Test that the error is raised if loaded a second time
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.load()
@skip_unless_feature("zlib")
@@ -132,7 +138,7 @@ class TestImageFile:
@skip_unless_feature("zlib")
def test_broken_datastream_with_errors(self):
with Image.open("Tests/images/broken_data_stream.png") as im:
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.load()
@skip_unless_feature("zlib")
@@ -255,9 +261,9 @@ class TestPyDecoder:
with Image.open(out) as reloaded:
reloaded_exif = reloaded.getexif()
assert reloaded_exif[258] == 8
- assert 40960 not in exif
+ assert 40960 not in reloaded_exif
assert reloaded_exif[40963] == 455
- assert exif[11] == "Pillow test"
+ assert reloaded_exif[11] == "Pillow test"
with Image.open("Tests/images/no-dpi-in-exif.jpg") as im: # Big endian
exif = im.getexif()
@@ -275,9 +281,9 @@ class TestPyDecoder:
with Image.open(out) as reloaded:
reloaded_exif = reloaded.getexif()
assert reloaded_exif[258] == 8
- assert 40960 not in exif
+ assert 34665 not in reloaded_exif
assert reloaded_exif[40963] == 455
- assert exif[305] == "Pillow test"
+ assert reloaded_exif[305] == "Pillow test"
@skip_unless_feature("webp")
@skip_unless_feature("webp_anim")
@@ -296,7 +302,7 @@ class TestPyDecoder:
reloaded_exif = reloaded.getexif()
assert reloaded_exif[258] == 8
assert reloaded_exif[40963] == 455
- assert exif[305] == "Pillow test"
+ assert reloaded_exif[305] == "Pillow test"
im.save(out, exif=exif)
check_exif()
diff --git a/Tests/test_imagefont.py b/Tests/test_imagefont.py
index e93aff4b2..e20950ca6 100644
--- a/Tests/test_imagefont.py
+++ b/Tests/test_imagefont.py
@@ -393,14 +393,14 @@ class TestImageFont:
filename = "somefilenamethatdoesntexist.ttf"
# Act/Assert
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
ImageFont.load_path(filename)
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
ImageFont.truetype(filename)
def test_load_non_font_bytes(self):
with open("Tests/images/hopper.jpg", "rb") as f:
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
ImageFont.truetype(f)
def test_default_font(self):
@@ -615,9 +615,9 @@ class TestImageFont:
font.get_variation_axes()
return
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
font.get_variation_names()
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
font.get_variation_axes()
font = ImageFont.truetype("Tests/fonts/AdobeVFPrototype.ttf")
@@ -660,6 +660,22 @@ class TestImageFont:
{"name": b"Size", "minimum": 0, "maximum": 300, "default": 0}
]
+ def _check_text(self, font, path, epsilon):
+ im = Image.new("RGB", (100, 75), "white")
+ d = ImageDraw.Draw(im)
+ d.text((10, 10), "Text", font=font, fill="black")
+
+ try:
+ with Image.open(path) as expected:
+ assert_image_similar(im, expected, epsilon)
+ except AssertionError:
+ if "_adobe" in path:
+ path = path.replace("_adobe", "_adobe_older_harfbuzz")
+ with Image.open(path) as expected:
+ assert_image_similar(im, expected, epsilon)
+ else:
+ raise
+
def test_variation_set_by_name(self):
font = self.get_font()
@@ -669,28 +685,20 @@ class TestImageFont:
font.set_variation_by_name("Bold")
return
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
font.set_variation_by_name("Bold")
- def _check_text(font, path, epsilon):
- im = Image.new("RGB", (100, 75), "white")
- d = ImageDraw.Draw(im)
- d.text((10, 10), "Text", font=font, fill="black")
-
- with Image.open(path) as expected:
- assert_image_similar(im, expected, epsilon)
-
font = ImageFont.truetype("Tests/fonts/AdobeVFPrototype.ttf", 36)
- _check_text(font, "Tests/images/variation_adobe.png", 11)
+ self._check_text(font, "Tests/images/variation_adobe.png", 11)
for name in ["Bold", b"Bold"]:
font.set_variation_by_name(name)
- _check_text(font, "Tests/images/variation_adobe_name.png", 11)
+ self._check_text(font, "Tests/images/variation_adobe_name.png", 11)
font = ImageFont.truetype("Tests/fonts/TINY5x3GX.ttf", 36)
- _check_text(font, "Tests/images/variation_tiny.png", 40)
+ self._check_text(font, "Tests/images/variation_tiny.png", 40)
for name in ["200", b"200"]:
font.set_variation_by_name(name)
- _check_text(font, "Tests/images/variation_tiny_name.png", 40)
+ self._check_text(font, "Tests/images/variation_tiny_name.png", 40)
def test_variation_set_by_axes(self):
font = self.get_font()
@@ -701,24 +709,16 @@ class TestImageFont:
font.set_variation_by_axes([100])
return
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
font.set_variation_by_axes([500, 50])
- def _check_text(font, path, epsilon):
- im = Image.new("RGB", (100, 75), "white")
- d = ImageDraw.Draw(im)
- d.text((10, 10), "Text", font=font, fill="black")
-
- with Image.open(path) as expected:
- assert_image_similar(im, expected, epsilon)
-
font = ImageFont.truetype("Tests/fonts/AdobeVFPrototype.ttf", 36)
font.set_variation_by_axes([500, 50])
- _check_text(font, "Tests/images/variation_adobe_axes.png", 5.1)
+ self._check_text(font, "Tests/images/variation_adobe_axes.png", 5.1)
font = ImageFont.truetype("Tests/fonts/TINY5x3GX.ttf", 36)
font.set_variation_by_axes([100])
- _check_text(font, "Tests/images/variation_tiny_axes.png", 32.5)
+ self._check_text(font, "Tests/images/variation_tiny_axes.png", 32.5)
@skip_unless_feature("raqm")
diff --git a/Tests/test_imagefontctl.py b/Tests/test_imagefontctl.py
index 6d7a9c2f4..386dd3be6 100644
--- a/Tests/test_imagefontctl.py
+++ b/Tests/test_imagefontctl.py
@@ -60,7 +60,7 @@ def test_complex_unicode_text():
target = "Tests/images/test_complex_unicode_text2.png"
with Image.open(target) as target_img:
- assert_image_similar(im, target_img, 2.3)
+ assert_image_similar(im, target_img, 2.33)
def test_text_direction_rtl():
diff --git a/Tests/test_imagegrab.py b/Tests/test_imagegrab.py
index 790847734..82e746fda 100644
--- a/Tests/test_imagegrab.py
+++ b/Tests/test_imagegrab.py
@@ -31,23 +31,23 @@ class TestImageGrab:
im2 = ImageGrab.grab(xdisplay="")
assert_image(im2, im2.mode, im2.size)
- except IOError as e:
+ except OSError as e:
pytest.skip(str(e))
@pytest.mark.skipif(Image.core.HAVE_XCB, reason="tests missing XCB")
def test_grab_no_xcb(self):
if sys.platform not in ("win32", "darwin"):
- with pytest.raises(IOError) as e:
+ with pytest.raises(OSError) as e:
ImageGrab.grab()
assert str(e.value).startswith("Pillow was built without XCB support")
- with pytest.raises(IOError) as e:
+ with pytest.raises(OSError) as e:
ImageGrab.grab(xdisplay="")
assert str(e.value).startswith("Pillow was built without XCB support")
@pytest.mark.skipif(not Image.core.HAVE_XCB, reason="requires XCB")
def test_grab_invalid_xdisplay(self):
- with pytest.raises(IOError) as e:
+ with pytest.raises(OSError) as e:
ImageGrab.grab(xdisplay="error.test:0.0")
assert str(e.value).startswith("X connection failed")
diff --git a/Tests/test_imagepalette.py b/Tests/test_imagepalette.py
index 29771cf03..4ef2d3ffd 100644
--- a/Tests/test_imagepalette.py
+++ b/Tests/test_imagepalette.py
@@ -145,5 +145,5 @@ def test_2bit_palette(tmp_path):
def test_invalid_palette():
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
ImagePalette.load("Tests/images/hopper.jpg")
diff --git a/Tests/test_imageshow.py b/Tests/test_imageshow.py
index 0d513a47d..64f15326b 100644
--- a/Tests/test_imageshow.py
+++ b/Tests/test_imageshow.py
@@ -1,7 +1,7 @@
import pytest
from PIL import Image, ImageShow
-from .helper import hopper, is_win32, on_ci, on_github_actions
+from .helper import hopper, is_win32, on_ci
def test_sanity():
@@ -38,8 +38,7 @@ def test_viewer_show():
@pytest.mark.skipif(
- not on_ci() or (is_win32() and on_github_actions()),
- reason="Only run on CIs; hangs on Windows on GitHub Actions",
+ not on_ci() or is_win32(), reason="Only run on CIs; hangs on Windows CIs",
)
def test_show():
for mode in ("1", "I;16", "LA", "RGB", "RGBA"):
diff --git a/Tests/test_map.py b/Tests/test_map.py
index b2f3ff227..bdb59bfe0 100644
--- a/Tests/test_map.py
+++ b/Tests/test_map.py
@@ -20,7 +20,7 @@ def test_overflow():
# This image hits the offset test.
with Image.open("Tests/images/l2rgb_read.bmp") as im:
- with pytest.raises((ValueError, MemoryError, IOError)):
+ with pytest.raises((ValueError, MemoryError, OSError)):
im.load()
Image.MAX_IMAGE_PIXELS = max_pixels
diff --git a/Tests/test_numpy.py b/Tests/test_numpy.py
index 30ab5132a..56addca1b 100644
--- a/Tests/test_numpy.py
+++ b/Tests/test_numpy.py
@@ -89,6 +89,11 @@ def test_3d_array():
assert_image(Image.fromarray(a[:, :, 1]), "L", TEST_IMAGE_SIZE)
+def test_1d_array():
+ a = numpy.ones(5, dtype=numpy.uint8)
+ assert_image(Image.fromarray(a), "L", (1, 5))
+
+
def _test_img_equals_nparray(img, np):
assert len(np.shape) >= 2
np_size = np.shape[1], np.shape[0]
diff --git a/Tests/test_pickle.py b/Tests/test_pickle.py
index ba4868988..dd241fd74 100644
--- a/Tests/test_pickle.py
+++ b/Tests/test_pickle.py
@@ -1,11 +1,14 @@
import pickle
+import pytest
from PIL import Image
+from .helper import skip_unless_feature
-def helper_pickle_file(tmp_path, pickle, protocol=0, mode=None):
+
+def helper_pickle_file(tmp_path, pickle, protocol, test_file, mode):
# Arrange
- with Image.open("Tests/images/hopper.jpg") as im:
+ with Image.open(test_file) as im:
filename = str(tmp_path / "temp.pkl")
if mode:
im = im.convert(mode)
@@ -20,9 +23,7 @@ def helper_pickle_file(tmp_path, pickle, protocol=0, mode=None):
assert im == loaded_im
-def helper_pickle_string(
- pickle, protocol=0, test_file="Tests/images/hopper.jpg", mode=None
-):
+def helper_pickle_string(pickle, protocol, test_file, mode):
with Image.open(test_file) as im:
if mode:
im = im.convert(mode)
@@ -35,41 +36,31 @@ def helper_pickle_string(
assert im == loaded_im
-def test_pickle_image(tmp_path):
+@pytest.mark.parametrize(
+ ("test_file", "test_mode"),
+ [
+ ("Tests/images/hopper.jpg", None),
+ ("Tests/images/hopper.jpg", "L"),
+ ("Tests/images/hopper.jpg", "PA"),
+ pytest.param(
+ "Tests/images/hopper.webp", None, marks=skip_unless_feature("webp")
+ ),
+ ("Tests/images/hopper.tif", None),
+ ("Tests/images/test-card.png", None),
+ ("Tests/images/zero_bb.png", None),
+ ("Tests/images/zero_bb_scale2.png", None),
+ ("Tests/images/non_zero_bb.png", None),
+ ("Tests/images/non_zero_bb_scale2.png", None),
+ ("Tests/images/p_trns_single.png", None),
+ ("Tests/images/pil123p.png", None),
+ ("Tests/images/itxt_chunks.png", None),
+ ],
+)
+def test_pickle_image(tmp_path, test_file, test_mode):
# Act / Assert
for protocol in range(0, pickle.HIGHEST_PROTOCOL + 1):
- helper_pickle_string(pickle, protocol)
- helper_pickle_file(tmp_path, pickle, protocol)
-
-
-def test_pickle_p_mode():
- # Act / Assert
- for test_file in [
- "Tests/images/test-card.png",
- "Tests/images/zero_bb.png",
- "Tests/images/zero_bb_scale2.png",
- "Tests/images/non_zero_bb.png",
- "Tests/images/non_zero_bb_scale2.png",
- "Tests/images/p_trns_single.png",
- "Tests/images/pil123p.png",
- "Tests/images/itxt_chunks.png",
- ]:
- for protocol in range(0, pickle.HIGHEST_PROTOCOL + 1):
- helper_pickle_string(pickle, protocol=protocol, test_file=test_file)
-
-
-def test_pickle_pa_mode(tmp_path):
- # Act / Assert
- for protocol in range(0, pickle.HIGHEST_PROTOCOL + 1):
- helper_pickle_string(pickle, protocol, mode="PA")
- helper_pickle_file(tmp_path, pickle, protocol, mode="PA")
-
-
-def test_pickle_l_mode(tmp_path):
- # Act / Assert
- for protocol in range(0, pickle.HIGHEST_PROTOCOL + 1):
- helper_pickle_string(pickle, protocol, mode="L")
- helper_pickle_file(tmp_path, pickle, protocol, mode="L")
+ helper_pickle_string(pickle, protocol, test_file, test_mode)
+ helper_pickle_file(tmp_path, pickle, protocol, test_file, test_mode)
def test_pickle_la_mode_with_palette(tmp_path):
@@ -88,3 +79,15 @@ def test_pickle_la_mode_with_palette(tmp_path):
im.mode = "PA"
assert im == loaded_im
+
+
+@skip_unless_feature("webp")
+def test_pickle_tell():
+ # Arrange
+ image = Image.open("Tests/images/hopper.webp")
+
+ # Act: roundtrip
+ unpickled_image = pickle.loads(pickle.dumps(image))
+
+ # Assert
+ assert unpickled_image.tell() == 0
diff --git a/Tests/test_sgi_crash.py b/Tests/test_sgi_crash.py
index 6f3fc6f5d..b1a3e1515 100644
--- a/Tests/test_sgi_crash.py
+++ b/Tests/test_sgi_crash.py
@@ -10,5 +10,5 @@ from PIL import Image
def test_crashes(test_file):
with open(test_file, "rb") as f:
im = Image.open(f)
- with pytest.raises(IOError):
+ with pytest.raises(OSError):
im.load()
diff --git a/depends/install_extra_test_images.sh b/depends/install_extra_test_images.sh
index 36af34b54..02da12d61 100755
--- a/depends/install_extra_test_images.sh
+++ b/depends/install_extra_test_images.sh
@@ -4,12 +4,12 @@
# Use SVN to just fetch a single Git subdirectory
svn_export()
{
- if [ ! -z $1 ]; then
- echo ""
- echo "Retrying svn export..."
- echo ""
- fi
+ if [ ! -z $1 ]; then
+ echo ""
+ echo "Retrying svn export..."
+ echo ""
+ fi
- svn export --force https://github.com/python-pillow/pillow-depends/trunk/test_images ../Tests/images
+ svn export --force https://github.com/python-pillow/pillow-depends/trunk/test_images ../Tests/images
}
svn_export || svn_export retry || svn_export retry || svn_export retry
diff --git a/docs/conf.py b/docs/conf.py
index d34318100..a0a3315c6 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -289,4 +289,4 @@ texinfo_documents = [
def setup(app):
- app.add_javascript("js/script.js")
+ app.add_js_file("js/script.js")
diff --git a/docs/deprecations.rst b/docs/deprecations.rst
index 227a5bc82..203921c0b 100644
--- a/docs/deprecations.rst
+++ b/docs/deprecations.rst
@@ -12,6 +12,15 @@ Deprecated features
Below are features which are considered deprecated. Where appropriate,
a ``DeprecationWarning`` is issued.
+ImageFile.raise_ioerror
+~~~~~~~~~~~~~~~~~~~~~~~
+
+.. deprecated:: 7.2.0
+
+``IOError`` was merged into ``OSError`` in Python 3.3. So, ``ImageFile.raise_ioerror``
+is now deprecated and will be removed in a future released. Use
+``ImageFile.raise_oserror`` instead.
+
PILLOW_VERSION constant
~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/docs/handbook/image-file-formats.rst b/docs/handbook/image-file-formats.rst
index a12de82e2..40db9fe2b 100644
--- a/docs/handbook/image-file-formats.rst
+++ b/docs/handbook/image-file-formats.rst
@@ -1226,7 +1226,7 @@ The :py:meth:`~PIL.Image.Image.save` method can take the following keyword argum
**append**
Set to True to append pages to an existing PDF file. If the file doesn't
- exist, an :py:exc:`IOError` will be raised.
+ exist, an :py:exc:`OSError` will be raised.
.. versionadded:: 5.1.0
diff --git a/docs/handbook/tutorial.rst b/docs/handbook/tutorial.rst
index 868402615..94a8e3aa1 100644
--- a/docs/handbook/tutorial.rst
+++ b/docs/handbook/tutorial.rst
@@ -29,7 +29,7 @@ bands in the image, and also the pixel type and depth. Common modes are “L”
(luminance) for greyscale images, “RGB” for true color images, and “CMYK” for
pre-press images.
-If the file cannot be opened, an :py:exc:`IOError` exception is raised.
+If the file cannot be opened, an :py:exc:`OSError` exception is raised.
Once you have an instance of the :py:class:`~PIL.Image.Image` class, you can use
the methods defined by this class to process and manipulate the image. For
@@ -76,7 +76,7 @@ Convert files to JPEG
try:
with Image.open(infile) as im:
im.save(outfile)
- except IOError:
+ except OSError:
print("cannot convert", infile)
A second argument can be supplied to the :py:meth:`~PIL.Image.Image.save`
@@ -100,7 +100,7 @@ Create JPEG thumbnails
with Image.open(infile) as im:
im.thumbnail(size)
im.save(outfile, "JPEG")
- except IOError:
+ except OSError:
print("cannot create thumbnail for", infile)
It is important to note that the library doesn’t decode or load the raster data
@@ -125,7 +125,7 @@ Identify Image Files
try:
with Image.open(infile) as im:
print(infile, im.format, "%dx%d" % im.size, im.mode)
- except IOError:
+ except OSError:
pass
Cutting, pasting, and merging images
@@ -450,7 +450,7 @@ context manager::
...
If everything goes well, the result is an :py:class:`PIL.Image.Image` object.
-Otherwise, an :exc:`IOError` exception is raised.
+Otherwise, an :exc:`OSError` exception is raised.
You can use a file-like object instead of the filename. The object must
implement :py:meth:`~file.read`, :py:meth:`~file.seek` and
diff --git a/docs/handbook/writing-your-own-file-decoder.rst b/docs/handbook/writing-your-own-file-decoder.rst
index 58e2bccc5..42a6c4822 100644
--- a/docs/handbook/writing-your-own-file-decoder.rst
+++ b/docs/handbook/writing-your-own-file-decoder.rst
@@ -17,8 +17,8 @@ itself. Such plug-ins usually have names like
Pillow decodes files in 2 stages:
1. It loops over the available image plugins in the loaded order, and
- calls the plugin's ``accept`` function with the first 16 bytes of
- the file. If the ``accept`` function returns true, the plugin's
+ calls the plugin's ``_accept`` function with the first 16 bytes of
+ the file. If the ``_accept`` function returns true, the plugin's
``_open`` method is called to set up the image metadata and image
tiles. The ``_open`` method is not for decoding the actual image
data.
@@ -53,6 +53,11 @@ true color.
from PIL import Image, ImageFile
+
+ def _accept(prefix):
+ return prefix[:4] == b"SPAM"
+
+
class SpamImageFile(ImageFile.ImageFile):
format = "SPAM"
@@ -60,12 +65,7 @@ true color.
def _open(self):
- # check header
- header = self.fp.read(128)
- if header[:4] != b"SPAM":
- raise SyntaxError("not a SPAM file")
-
- header = header.split()
+ header = self.fp.read(128).split()
# size in pixels (width, height)
self._size = int(header[1]), int(header[2])
@@ -86,7 +86,7 @@ true color.
("raw", (0, 0) + self.size, 128, (self.mode, 0, 1))
]
- Image.register_open(SpamImageFile.format, SpamImageFile)
+ Image.register_open(SpamImageFile.format, SpamImageFile, _accept)
Image.register_extension(SpamImageFile.format, ".spam")
Image.register_extension(SpamImageFile.format, ".spa") # dos version
@@ -179,7 +179,7 @@ complete list, see the table in the :py:mod:`Unpack.c` module. The following
table describes some commonly used **raw modes**:
+-----------+-----------------------------------------------------------------+
-| mode | description |
+| mode | description |
+===========+=================================================================+
| ``1`` | 1-bit bilevel, stored with the leftmost pixel in the most |
| | significant bit. 0 means black, 1 means white. |
@@ -223,7 +223,7 @@ You can use the ``raw`` decoder to read images where data is packed in any
standard machine data type, using one of the following raw modes:
============ =======================================
-mode description
+mode description
============ =======================================
``F`` 32-bit native floating point.
``F;8`` 8-bit unsigned integer.
diff --git a/docs/installation.rst b/docs/installation.rst
index a83bf5748..1b5f2e056 100644
--- a/docs/installation.rst
+++ b/docs/installation.rst
@@ -292,9 +292,10 @@ or from within the uncompressed source directory::
Building on Windows
^^^^^^^^^^^^^^^^^^^
-We don't recommend trying to build on Windows. It is a maze of twisty
-passages, mostly dead ends. There are build scripts and notes for the
-Windows build in the ``winbuild`` directory.
+We recommend you use prebuilt wheels from PyPI.
+If you wish to compile Pillow manually, you can use the build scripts
+in the ``winbuild`` directory used for CI testing and development.
+These scripts require Visual Studio 2017 or newer and NASM.
Building on FreeBSD
^^^^^^^^^^^^^^^^^^^
@@ -328,7 +329,7 @@ In Fedora, the command is::
.. Note:: ``redhat-rpm-config`` is required on Fedora 23, but not earlier versions.
-Prerequisites are installed on **Ubuntu 16.04 LTS** with::
+Prerequisites for **Ubuntu 16.04 LTS - 20.04 LTS** are installed with::
sudo apt-get install libtiff5-dev libjpeg8-dev libopenjp2-7-dev zlib1g-dev \
libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python3-tk \
@@ -396,17 +397,23 @@ These platforms are built and tested for every change.
+----------------------------------+--------------------------+-----------------------+
| Debian 10 Buster | 3.7 |x86 |
+----------------------------------+--------------------------+-----------------------+
-| Fedora 30 | 3.7 |x86-64 |
-+----------------------------------+--------------------------+-----------------------+
| Fedora 31 | 3.7 |x86-64 |
+----------------------------------+--------------------------+-----------------------+
+| Fedora 32 | 3.8 |x86-64 |
++----------------------------------+--------------------------+-----------------------+
| macOS 10.15 Catalina | 3.5, 3.6, 3.7, 3.8, PyPy3|x86-64 |
+----------------------------------+--------------------------+-----------------------+
| Ubuntu Linux 16.04 LTS | 3.5, 3.6, 3.7, 3.8, PyPy3|x86-64 |
+----------------------------------+--------------------------+-----------------------+
-| Windows Server 2012 R2 | 3.5, 3.8 |x86, x86-64 |
+| Ubuntu Linux 18.04 LTS | 3.6 |x86-64 |
++----------------------------------+--------------------------+-----------------------+
+| Ubuntu Linux 20.04 LTS | 3.8 |x86-64 |
++----------------------------------+--------------------------+-----------------------+
+| Windows Server 2016 | 3.8 |x86 |
| +--------------------------+-----------------------+
-| | PyPy3, 3.7/MinGW |x86 |
+| | 3.5 |x86-64 |
+| +--------------------------+-----------------------+
+| | 3.7/MinGW |x86 |
+----------------------------------+--------------------------+-----------------------+
| Windows Server 2019 | 3.5, 3.6, 3.7, 3.8 |x86, x86-64 |
| +--------------------------+-----------------------+
@@ -427,7 +434,7 @@ These platforms have been reported to work at the versions mentioned.
+----------------------------------+------------------------------+--------------------------------+-----------------------+
|**Operating system** |**Tested Python versions** |**Latest tested Pillow version**|**Tested processors** |
+----------------------------------+------------------------------+--------------------------------+-----------------------+
-| macOS 10.15 Catalina | 3.5, 3.6, 3.7, 3.8 | 7.0.0 |x86-64 |
+| macOS 10.15 Catalina | 3.5, 3.6, 3.7, 3.8 | 7.1.2 |x86-64 |
+----------------------------------+------------------------------+--------------------------------+-----------------------+
| macOS 10.14 Mojave | 2.7, 3.5, 3.6, 3.7 | 6.0.0 |x86-64 |
| +------------------------------+--------------------------------+ +
@@ -474,11 +481,13 @@ These platforms have been reported to work at the versions mentioned.
+----------------------------------+------------------------------+--------------------------------+-----------------------+
| FreeBSD 10.2 | 2.7, 3.4 | 3.1.0 |x86-64 |
+----------------------------------+------------------------------+--------------------------------+-----------------------+
+| Windows 10 | 3.7 | 7.1.0 |x86-64 |
++----------------------------------+------------------------------+--------------------------------+-----------------------+
| Windows 8.1 Pro | 2.6, 2.7, 3.2, 3.3, 3.4 | 2.4.0 |x86,x86-64 |
+----------------------------------+------------------------------+--------------------------------+-----------------------+
| Windows 8 Pro | 2.6, 2.7, 3.2, 3.3, 3.4a3 | 2.2.0 |x86,x86-64 |
+----------------------------------+------------------------------+--------------------------------+-----------------------+
-| Windows 7 Pro | 2.7, 3.2, 3.3 | 3.4.1 |x86-64 |
+| Windows 7 Professional | 3.7 | 7.0.0 |x86,x86-64 |
+----------------------------------+------------------------------+--------------------------------+-----------------------+
| Windows Server 2008 R2 Enterprise| 3.3 | |x86-64 |
+----------------------------------+------------------------------+--------------------------------+-----------------------+
diff --git a/docs/reference/Image.rst b/docs/reference/Image.rst
index 8af56f6c1..216fa1196 100644
--- a/docs/reference/Image.rst
+++ b/docs/reference/Image.rst
@@ -58,8 +58,8 @@ Functions
``warnings.simplefilter('ignore', Image.DecompressionBombWarning)``. See also `the logging
documentation`_ to have warnings output to the logging facility instead of stderr.
- .. _decompression bombs: https://en.wikipedia.org/wiki/Zip_bomb
- .. _the logging documentation: https://docs.python.org/3/library/logging.html#integration-with-the-warnings-module
+ .. _decompression bombs: https://en.wikipedia.org/wiki/Zip_bomb
+ .. _the logging documentation: https://docs.python.org/3/library/logging.html#integration-with-the-warnings-module
Image processing
^^^^^^^^^^^^^^^^
@@ -179,6 +179,7 @@ This helps to get the bounding box coordinates of the input image:
.. automethod:: PIL.Image.Image.getcolors
.. automethod:: PIL.Image.Image.getdata
.. automethod:: PIL.Image.Image.getextrema
+.. automethod:: PIL.Image.Image.getexif
.. automethod:: PIL.Image.Image.getpalette
.. automethod:: PIL.Image.Image.getpixel
.. automethod:: PIL.Image.Image.histogram
diff --git a/docs/reference/ImageCms.rst b/docs/reference/ImageCms.rst
index 922e1685a..67c581765 100644
--- a/docs/reference/ImageCms.rst
+++ b/docs/reference/ImageCms.rst
@@ -413,10 +413,10 @@ can be easily displayed in a chromaticity diagram, for example).
with :py:attr:`.intent_supported`.
:param intent: One of ``ImageCms.INTENT_ABSOLUTE_COLORIMETRIC``,
- ``ImageCms.INTENT_PERCEPTUAL``,
- ``ImageCms.INTENT_RELATIVE_COLORIMETRIC``
- and ``ImageCms.INTENT_SATURATION``.
+ ``ImageCms.INTENT_PERCEPTUAL``,
+ ``ImageCms.INTENT_RELATIVE_COLORIMETRIC``
+ and ``ImageCms.INTENT_SATURATION``.
:param direction: One of ``ImageCms.DIRECTION_INPUT``,
- ``ImageCms.DIRECTION_OUTPUT``
- and ``ImageCms.DIRECTION_PROOF``
+ ``ImageCms.DIRECTION_OUTPUT``
+ and ``ImageCms.DIRECTION_PROOF``
:return: Boolean if the intent and direction is supported.
diff --git a/docs/reference/ImageDraw.rst b/docs/reference/ImageDraw.rst
index d888913c3..782b0434b 100644
--- a/docs/reference/ImageDraw.rst
+++ b/docs/reference/ImageDraw.rst
@@ -81,13 +81,13 @@ Example: Draw Partial Opacity Text
from PIL import Image, ImageDraw, ImageFont
# get an image
- base = Image.open('Pillow/Tests/images/hopper.png').convert('RGBA')
+ base = Image.open("Pillow/Tests/images/hopper.png").convert("RGBA")
# make a blank image for the text, initialized to transparent text color
- txt = Image.new('RGBA', base.size, (255,255,255,0))
+ txt = Image.new("RGBA", base.size, (255,255,255,0))
# get a font
- fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 40)
+ fnt = ImageFont.truetype("Pillow/Tests/fonts/FreeMono.ttf", 40)
# get a drawing context
d = ImageDraw.Draw(txt)
@@ -100,6 +100,25 @@ Example: Draw Partial Opacity Text
out.show()
+Example: Draw Multiline Text
+----------------------------
+
+.. code-block:: python
+
+ from PIL import Image, ImageDraw, ImageFont
+
+ # create an image
+ out = Image.new("RGB", (150, 100), (255, 255, 255))
+
+ # get a font
+ fnt = ImageFont.truetype("Pillow/Tests/fonts/FreeMono.ttf", 40)
+ # get a drawing context
+ d = ImageDraw.Draw(out)
+
+ # draw multiline text
+ d.multiline_text((10,10), "Hello\nWorld", font=fnt, fill=(0, 0, 0))
+
+ out.show()
Functions
@@ -193,8 +212,7 @@ Methods
.. versionadded:: 1.1.5
.. note:: This option was broken until version 1.1.6.
- :param joint: Joint type between a sequence of lines. It can be "curve",
- for rounded edges, or None.
+ :param joint: Joint type between a sequence of lines. It can be ``"curve"``, for rounded edges, or ``None``.
.. versionadded:: 5.3.0
@@ -261,15 +279,18 @@ Methods
:param xy: Top left corner of the text.
:param text: Text to be drawn. If it contains any newline characters,
- the text is passed on to multiline_text()
+ the text is passed on to
+ :py:meth:`~PIL.ImageDraw.ImageDraw.multiline_text`.
:param fill: Color to use for the text.
:param font: An :py:class:`~PIL.ImageFont.ImageFont` instance.
- :param spacing: If the text is passed on to multiline_text(),
+ :param spacing: If the text is passed on to
+ :py:meth:`~PIL.ImageDraw.ImageDraw.multiline_text`,
the number of pixels between lines.
- :param align: If the text is passed on to multiline_text(),
- "left", "center" or "right".
- :param direction: Direction of the text. It can be 'rtl' (right to
- left), 'ltr' (left to right) or 'ttb' (top to bottom).
+ :param align: If the text is passed on to
+ :py:meth:`~PIL.ImageDraw.ImageDraw.multiline_text`,
+ ``"left"``, ``"center"`` or ``"right"``.
+ :param direction: Direction of the text. It can be ``"rtl"`` (right to
+ left), ``"ltr"`` (left to right) or ``"ttb"`` (top to bottom).
Requires libraqm.
.. versionadded:: 4.2.0
@@ -277,12 +298,11 @@ Methods
:param features: A list of OpenType font features to be used during text
layout. This is usually used to turn on optional
font features that are not enabled by default,
- for example 'dlig' or 'ss01', but can be also
- used to turn off default font features for
- example '-liga' to disable ligatures or '-kern'
+ for example ``"dlig"`` or ``"ss01"``, but can be also
+ used to turn off default font features, for
+ example ``"-liga"`` to disable ligatures or ``"-kern"``
to disable kerning. To get all supported
- features, see
- https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist
+ features, see `OpenType docs`_.
Requires libraqm.
.. versionadded:: 4.2.0
@@ -291,8 +311,7 @@ Methods
different glyph shapes or ligatures. This parameter tells
the font which language the text is in, and to apply the
correct substitutions as appropriate, if available.
- It should be a `BCP 47 language code
- `
+ It should be a `BCP 47 language code`_.
Requires libraqm.
.. versionadded:: 6.0.0
@@ -302,9 +321,9 @@ Methods
.. versionadded:: 6.2.0
:param stroke_fill: Color to use for the text stroke. If not given, will default to
- the ``fill`` parameter.
+ the ``fill`` parameter.
- .. versionadded:: 6.2.0
+ .. versionadded:: 6.2.0
.. py:method:: PIL.ImageDraw.ImageDraw.multiline_text(xy, text, fill=None, font=None, anchor=None, spacing=4, align="left", direction=None, features=None, language=None)
@@ -315,9 +334,9 @@ Methods
:param fill: Color to use for the text.
:param font: An :py:class:`~PIL.ImageFont.ImageFont` instance.
:param spacing: The number of pixels between lines.
- :param align: "left", "center" or "right".
- :param direction: Direction of the text. It can be 'rtl' (right to
- left), 'ltr' (left to right) or 'ttb' (top to bottom).
+ :param align: ``"left"``, ``"center"`` or ``"right"``.
+ :param direction: Direction of the text. It can be ``"rtl"`` (right to
+ left), ``"ltr"`` (left to right) or ``"ttb"`` (top to bottom).
Requires libraqm.
.. versionadded:: 4.2.0
@@ -325,12 +344,11 @@ Methods
:param features: A list of OpenType font features to be used during text
layout. This is usually used to turn on optional
font features that are not enabled by default,
- for example 'dlig' or 'ss01', but can be also
- used to turn off default font features for
- example '-liga' to disable ligatures or '-kern'
+ for example ``"dlig"`` or ``"ss01"``, but can be also
+ used to turn off default font features, for
+ example ``"-liga"`` to disable ligatures or ``"-kern"``
to disable kerning. To get all supported
- features, see
- https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist
+ features, see `OpenType docs`_.
Requires libraqm.
.. versionadded:: 4.2.0
@@ -339,8 +357,7 @@ Methods
different glyph shapes or ligatures. This parameter tells
the font which language the text is in, and to apply the
correct substitutions as appropriate, if available.
- It should be a `BCP 47 language code
- `
+ It should be a `BCP 47 language code`_.
Requires libraqm.
.. versionadded:: 6.0.0
@@ -350,24 +367,24 @@ Methods
Return the size of the given string, in pixels.
:param text: Text to be measured. If it contains any newline characters,
- the text is passed on to multiline_textsize()
+ the text is passed on to :py:meth:`~PIL.ImageDraw.ImageDraw.multiline_textsize`.
:param font: An :py:class:`~PIL.ImageFont.ImageFont` instance.
- :param spacing: If the text is passed on to multiline_textsize(),
+ :param spacing: If the text is passed on to
+ :py:meth:`~PIL.ImageDraw.ImageDraw.multiline_textsize`,
the number of pixels between lines.
- :param direction: Direction of the text. It can be 'rtl' (right to
- left), 'ltr' (left to right) or 'ttb' (top to bottom).
+ :param direction: Direction of the text. It can be ``"rtl"`` (right to
+ left), ``"ltr"`` (left to right) or ``"ttb"`` (top to bottom).
Requires libraqm.
.. versionadded:: 4.2.0
:param features: A list of OpenType font features to be used during text
layout. This is usually used to turn on optional
font features that are not enabled by default,
- for example 'dlig' or 'ss01', but can be also
- used to turn off default font features for
- example '-liga' to disable ligatures or '-kern'
+ for example ``"dlig"`` or ``"ss01"``, but can be also
+ used to turn off default font features, for
+ example ``"-liga"`` to disable ligatures or ``"-kern"``
to disable kerning. To get all supported
- features, see
- https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist
+ features, see `OpenType docs`_.
Requires libraqm.
.. versionadded:: 4.2.0
@@ -375,8 +392,7 @@ Methods
different glyph shapes or ligatures. This parameter tells
the font which language the text is in, and to apply the
correct substitutions as appropriate, if available.
- It should be a `BCP 47 language code
- `
+ It should be a `BCP 47 language code`_.
Requires libraqm.
.. versionadded:: 6.0.0
@@ -392,8 +408,8 @@ Methods
:param text: Text to be measured.
:param font: An :py:class:`~PIL.ImageFont.ImageFont` instance.
:param spacing: The number of pixels between lines.
- :param direction: Direction of the text. It can be 'rtl' (right to
- left), 'ltr' (left to right) or 'ttb' (top to bottom).
+ :param direction: Direction of the text. It can be ``"rtl"`` (right to
+ left), ``"ltr"`` (left to right) or ``"ttb"`` (top to bottom).
Requires libraqm.
.. versionadded:: 4.2.0
@@ -401,12 +417,11 @@ Methods
:param features: A list of OpenType font features to be used during text
layout. This is usually used to turn on optional
font features that are not enabled by default,
- for example 'dlig' or 'ss01', but can be also
- used to turn off default font features for
- example '-liga' to disable ligatures or '-kern'
+ for example ``"dlig"`` or ``"ss01"``, but can be also
+ used to turn off default font features, for
+ example ``"-liga"`` to disable ligatures or ``"-kern"``
to disable kerning. To get all supported
- features, see
- https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist
+ features, see `OpenType docs`_.
Requires libraqm.
.. versionadded:: 4.2.0
@@ -415,8 +430,7 @@ Methods
different glyph shapes or ligatures. This parameter tells
the font which language the text is in, and to apply the
correct substitutions as appropriate, if available.
- It should be a `BCP 47 language code
- `
+ It should be a `BCP 47 language code`_.
Requires libraqm.
.. versionadded:: 6.0.0
@@ -453,3 +467,6 @@ Methods
tolerable difference of a pixel value from the 'background' in
order for it to be replaced. Useful for filling regions of non-
homogeneous, but similar, colors.
+
+.. _BCP 47 language code: https://www.w3.org/International/articles/language-tags/
+.. _OpenType docs: https://docs.microsoft.com/en-us/typography/opentype/spec/featurelist
diff --git a/docs/reference/ImageFont.rst b/docs/reference/ImageFont.rst
index bb7538096..1aa22aa51 100644
--- a/docs/reference/ImageFont.rst
+++ b/docs/reference/ImageFont.rst
@@ -9,13 +9,14 @@ this class store bitmap fonts, and are used with the
:py:meth:`PIL.ImageDraw.Draw.text` method.
PIL uses its own font file format to store bitmap fonts. You can use the
-:command:`pilfont` utility to convert BDF and PCF font descriptors (X window
-font formats) to this format.
+:command:`pilfont` utility from
+`pillow-scripts `_
+to convert BDF and PCF font descriptors (X window font formats) to this format.
Starting with version 1.1.4, PIL can be configured to support TrueType and
OpenType fonts (as well as other font formats supported by the FreeType
library). For earlier versions, TrueType support is only available as part of
-the imToolkit package
+the imToolkit package.
Example
-------
diff --git a/docs/reference/ImageGrab.rst b/docs/reference/ImageGrab.rst
index ddd5bbbb5..943fdf69b 100644
--- a/docs/reference/ImageGrab.rst
+++ b/docs/reference/ImageGrab.rst
@@ -1,20 +1,18 @@
.. py:module:: PIL.ImageGrab
.. py:currentmodule:: PIL.ImageGrab
-:py:mod:`ImageGrab` Module (macOS and Windows only)
-===================================================
+:py:mod:`ImageGrab` Module
+==========================
The :py:mod:`ImageGrab` module can be used to copy the contents of the screen
or the clipboard to a PIL image memory.
-.. note:: The current version works on macOS and Windows only.
-
.. versionadded:: 1.1.3
-.. py:function:: PIL.ImageGrab.grab(bbox=None, include_layered_windows=False, all_screens=False, xdisplay=None)
+.. py:function:: grab(bbox=None, include_layered_windows=False, all_screens=False, xdisplay=None)
Take a snapshot of the screen. The pixels inside the bounding box are
- returned as an "RGB" image on Windows or "RGBA" on macOS.
+ returned as an "RGBA" on macOS, or an "RGB" image otherwise.
If the bounding box is omitted, the entire screen is copied.
.. versionadded:: 1.1.3 (Windows), 3.0.0 (macOS), 7.1.0 (Linux (X11))
@@ -28,15 +26,17 @@ or the clipboard to a PIL image memory.
.. versionadded:: 6.2.0
- :param xdisplay: X11 Display address. Pass ``None`` to grab the default system screen.
- Pass ``""`` to grab the default X11 screen on Windows or macOS.
+ :param xdisplay:
+ X11 Display address. Pass ``None`` to grab the default system screen. Pass ``""`` to grab the default X11 screen on Windows or macOS.
+
+ You can check X11 support using :py:func:`PIL.features.check_feature` with ``feature="xcb"``.
.. versionadded:: 7.1.0
:return: An image
-.. py:function:: PIL.ImageGrab.grabclipboard()
+.. py:function:: grabclipboard()
- Take a snapshot of the clipboard image, if any.
+ Take a snapshot of the clipboard image, if any. Only macOS and Windows are currently supported.
.. versionadded:: 1.1.4 (Windows), 3.3.0 (macOS)
diff --git a/docs/reference/features.rst b/docs/reference/features.rst
new file mode 100644
index 000000000..196f938ed
--- /dev/null
+++ b/docs/reference/features.rst
@@ -0,0 +1,60 @@
+.. py:module:: PIL.features
+.. py:currentmodule:: PIL.features
+
+:py:mod:`features` Module
+==========================
+
+The :py:mod:`PIL.features` module can be used to detect which Pillow features are available on your system.
+
+.. autofunction:: PIL.features.pilinfo
+.. autofunction:: PIL.features.check
+.. autofunction:: PIL.features.get_supported
+
+Modules
+-------
+
+Support for the following modules can be checked:
+
+* ``pil``: The Pillow core module, required for all functionality.
+* ``tkinter``: Tkinter support.
+* ``freetype2``: FreeType font support via :py:func:`PIL.ImageFont.truetype`.
+* ``littlecms2``: LittleCMS 2 support via :py:mod:`PIL.ImageCms`.
+* ``webp``: WebP image support.
+
+.. autofunction:: PIL.features.check_module
+.. autofunction:: PIL.features.get_supported_modules
+
+Codecs
+------
+
+These are only checked during Pillow compilation.
+If the required library was uninstalled from the system, the ``pil`` core module may fail to load instead.
+
+Support for the following codecs can be checked:
+
+* ``jpg``: (compile time) Libjpeg support, required for JPEG based image formats.
+* ``jpg_2000``: (compile time) OpenJPEG support, required for JPEG 2000 image formats.
+* ``zlib``: (compile time) Zlib support, required for zlib compressed formats, such as PNG.
+* ``libtiff``: (compile time) LibTIFF support, required for TIFF based image formats.
+
+.. autofunction:: PIL.features.check_codec
+.. autofunction:: PIL.features.get_supported_codecs
+
+Features
+--------
+
+Some of these are only checked during Pillow compilation.
+If the required library was uninstalled from the system, the relevant module may fail to load instead.
+
+Support for the following features can be checked:
+
+* ``libjpeg_turbo``: (compile time) Whether Pillow was compiled against the libjpeg-turbo version of libjpeg.
+* ``transp_webp``: Support for transparency in WebP images.
+* ``webp_mux``: (compile time) Support for EXIF data in WebP images.
+* ``webp_anim``: (compile time) Support for animated WebP images.
+* ``raqm``: Raqm library, required for ``ImageFont.LAYOUT_RAQM`` in :py:func:`PIL.ImageFont.truetype`.
+* ``libimagequant``: (compile time) ImageQuant quantization support in :py:func:`PIL.Image.Image.quantize`.
+* ``xcb``: (compile time) Support for X11 in :py:func:`PIL.ImageGrab.grab` via the XCB library.
+
+.. autofunction:: PIL.features.check_feature
+.. autofunction:: PIL.features.get_supported_features
diff --git a/docs/reference/index.rst b/docs/reference/index.rst
index 8c09e7b67..91cde0400 100644
--- a/docs/reference/index.rst
+++ b/docs/reference/index.rst
@@ -30,6 +30,7 @@ Reference
PSDraw
PixelAccess
PyAccess
+ features
../PIL
plugins
internal_design
diff --git a/docs/releasenotes/7.0.0.rst b/docs/releasenotes/7.0.0.rst
index e0e764342..73c44275c 100644
--- a/docs/releasenotes/7.0.0.rst
+++ b/docs/releasenotes/7.0.0.rst
@@ -85,7 +85,7 @@ Custom unidentified image error
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Pillow will now throw a custom ``UnidentifiedImageError`` when an image cannot be
-identified. For backwards compatibility, this will inherit from ``IOError``.
+identified. For backwards compatibility, this will inherit from ``OSError``.
New argument ``reducing_gap`` for Image.resize() and Image.thumbnail() methods
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
diff --git a/docs/releasenotes/7.1.0.rst b/docs/releasenotes/7.1.0.rst
index 346b9b490..55a970c1e 100644
--- a/docs/releasenotes/7.1.0.rst
+++ b/docs/releasenotes/7.1.0.rst
@@ -69,6 +69,16 @@ Passing a different value on Windows or macOS will force taking a snapshot
using the selected X server; pass an empty string to use the default X server.
XCB support is not included in pre-compiled wheels for Windows and macOS.
+Security
+========
+
+This release includes security fixes.
+
+* CVE-2020-10177 Fix multiple OOB reads in FLI decoding
+* CVE-2020-10378 Fix bounds overflow in PCX decoding
+* CVE-2020-10379 Fix two buffer overflows in TIFF decoding
+* CVE-2020-10994 Fix bounds overflow in JPEG 2000 decoding
+* CVE-2020-11538 Fix buffer overflow in SGI-RLE decoding
Other Changes
=============
diff --git a/docs/releasenotes/7.1.2.rst b/docs/releasenotes/7.1.2.rst
new file mode 100644
index 000000000..c9d0d54eb
--- /dev/null
+++ b/docs/releasenotes/7.1.2.rst
@@ -0,0 +1,16 @@
+7.1.2
+-----
+
+Fix another regression seeking PNG files
+========================================
+
+This fixes a regression introduced in 7.1.0 when adding support for APNG files.
+
+When calling ``seek(n)`` on a regular PNG where ``n > 0``, it failed to raise an
+``EOFError`` as it should have done, resulting in:
+
+.. code-block:: python
+
+ AttributeError: 'NoneType' object has no attribute 'read'
+
+Pillow 7.1.2 now raises the correct exception.
diff --git a/docs/releasenotes/7.2.0.rst b/docs/releasenotes/7.2.0.rst
new file mode 100644
index 000000000..904e9d5ab
--- /dev/null
+++ b/docs/releasenotes/7.2.0.rst
@@ -0,0 +1,29 @@
+7.2.0
+-----
+
+API Changes
+===========
+
+Replaced TiffImagePlugin DEBUG with logging
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+``TiffImagePlugin.DEBUG = True`` has been a way to print various debugging
+information when interacting with TIFF images. This has now been removed
+in favour of Python's ``logging`` module, already used in other places in the
+Pillow source code.
+
+Corrected default offset when writing EXIF data
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Previously, the default ``offset`` argument for
+:py:meth:`~PIL.Image.Exif.tobytes` was 0, which did not include the magic
+header. It is now 8.
+
+Moved to ImageFileDirectory_v2 in Image.Exif
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Moved from the legacy :py:class:`PIL.TiffImagePlugin.ImageFileDirectory_v1` to
+:py:class:`PIL.TiffImagePlugin.ImageFileDirectory_v2` in
+:py:class:`PIL.Image.Exif`. This means that Exif RATIONALs and SIGNED_RATIONALs
+are now read as :py:class:`PIL.TiffImagePlugin.IFDRational`, instead of as a
+tuple with a numerator and a denominator.
diff --git a/docs/releasenotes/index.rst b/docs/releasenotes/index.rst
index 7cdb58494..4dd7d5e63 100644
--- a/docs/releasenotes/index.rst
+++ b/docs/releasenotes/index.rst
@@ -6,6 +6,8 @@ Release Notes
.. toctree::
:maxdepth: 2
+ 7.2.0
+ 7.1.2
7.1.1
7.1.0
7.0.0
diff --git a/selftest.py b/selftest.py
index ea52256f7..a9a02ef71 100755
--- a/selftest.py
+++ b/selftest.py
@@ -47,7 +47,7 @@ def testimage():
('PPM', 'RGB', (128, 128))
>>> try:
... _info(Image.open("Tests/images/hopper.jpg"))
- ... except IOError as v:
+ ... except OSError as v:
... print(v)
('JPEG', 'RGB', (128, 128))
diff --git a/setup.cfg b/setup.cfg
index 17e85bd21..30843b847 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -10,3 +10,4 @@ multi_line_output = 3
[tool:pytest]
addopts = -rs
+testpaths = Tests
diff --git a/setup.py b/setup.py
index 3e1a812b6..b7982a5ba 100755
--- a/setup.py
+++ b/setup.py
@@ -579,7 +579,7 @@ class pil_build_ext(build_ext):
try:
listdir = os.listdir(directory)
except Exception:
- # WindowsError, FileNotFoundError
+ # OSError, FileNotFoundError
continue
for name in listdir:
if name.startswith("openjpeg-") and os.path.isfile(
@@ -711,7 +711,7 @@ class pil_build_ext(build_ext):
if feature.jpeg2000:
libs.append(feature.jpeg2000)
defs.append(("HAVE_OPENJPEG", None))
- if sys.platform == "win32":
+ if sys.platform == "win32" and not PLATFORM_MINGW:
defs.append(("OPJ_STATIC", None))
if feature.zlib:
libs.append(feature.zlib)
@@ -730,7 +730,11 @@ class pil_build_ext(build_ext):
if struct.unpack("h", b"\0\1")[0] == 1:
defs.append(("WORDS_BIGENDIAN", None))
- if sys.platform == "win32" and not (PLATFORM_PYPY or PLATFORM_MINGW):
+ if (
+ sys.platform == "win32"
+ and sys.version_info < (3, 9)
+ and not (PLATFORM_PYPY or PLATFORM_MINGW)
+ ):
defs.append(("PILLOW_VERSION", '"\\"%s\\""' % PILLOW_VERSION))
else:
defs.append(("PILLOW_VERSION", '"%s"' % PILLOW_VERSION))
diff --git a/src/PIL/DcxImagePlugin.py b/src/PIL/DcxImagePlugin.py
index 7d2aff325..a12d9195b 100644
--- a/src/PIL/DcxImagePlugin.py
+++ b/src/PIL/DcxImagePlugin.py
@@ -59,16 +59,10 @@ class DcxImageFile(PcxImageFile):
self.__fp = self.fp
self.frame = None
+ self.n_frames = len(self._offset)
+ self.is_animated = self.n_frames > 1
self.seek(0)
- @property
- def n_frames(self):
- return len(self._offset)
-
- @property
- def is_animated(self):
- return len(self._offset) > 1
-
def seek(self, frame):
if not self._seek_check(frame):
return
diff --git a/src/PIL/FliImagePlugin.py b/src/PIL/FliImagePlugin.py
index 9bf7d74d6..989094569 100644
--- a/src/PIL/FliImagePlugin.py
+++ b/src/PIL/FliImagePlugin.py
@@ -51,7 +51,8 @@ class FliImageFile(ImageFile.ImageFile):
raise SyntaxError("not an FLI/FLC file")
# frames
- self.__framecount = i16(s[6:8])
+ self.n_frames = i16(s[6:8])
+ self.is_animated = self.n_frames > 1
# image characteristics
self.mode = "P"
@@ -110,14 +111,6 @@ class FliImageFile(ImageFile.ImageFile):
palette[i] = (r, g, b)
i += 1
- @property
- def n_frames(self):
- return self.__framecount
-
- @property
- def is_animated(self):
- return self.__framecount > 1
-
def seek(self, frame):
if not self._seek_check(frame):
return
diff --git a/src/PIL/FpxImagePlugin.py b/src/PIL/FpxImagePlugin.py
index 8d252c79c..81501e244 100644
--- a/src/PIL/FpxImagePlugin.py
+++ b/src/PIL/FpxImagePlugin.py
@@ -99,7 +99,7 @@ class FpxImageFile(ImageFile.ImageFile):
colors = []
bands = i32(s, 4)
if bands > 4:
- raise IOError("Invalid number of bands")
+ raise OSError("Invalid number of bands")
for i in range(bands):
# note: for now, we ignore the "uncalibrated" flag
colors.append(i32(s, 8 + i * 4) & 0x7FFFFFFF)
diff --git a/src/PIL/GbrImagePlugin.py b/src/PIL/GbrImagePlugin.py
index 292de435c..f9d9cc772 100644
--- a/src/PIL/GbrImagePlugin.py
+++ b/src/PIL/GbrImagePlugin.py
@@ -84,6 +84,10 @@ class GbrImageFile(ImageFile.ImageFile):
self._data_size = width * height * color_depth
def load(self):
+ if self.im:
+ # Already loaded
+ return
+
self.im = Image.core.new(self.mode, self.size)
self.frombytes(self.fp.read(self._data_size))
diff --git a/src/PIL/GdImageFile.py b/src/PIL/GdImageFile.py
index 54c88712c..b3ab01a4e 100644
--- a/src/PIL/GdImageFile.py
+++ b/src/PIL/GdImageFile.py
@@ -74,7 +74,7 @@ def open(fp, mode="r"):
:param mode: Optional mode. In this version, if the mode argument
is given, it must be "r".
:returns: An image instance.
- :raises IOError: If the image could not be read.
+ :raises OSError: If the image could not be read.
"""
if mode != "r":
raise ValueError("bad mode")
diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py
index 1d94fc7c7..9d360beae 100644
--- a/src/PIL/GifImagePlugin.py
+++ b/src/PIL/GifImagePlugin.py
@@ -255,7 +255,7 @@ class GifImageFile(ImageFile.ImageFile):
else:
pass
- # raise IOError, "illegal GIF tag `%x`" % i8(s)
+ # raise OSError, "illegal GIF tag `%x`" % i8(s)
try:
if self.disposal_method < 2:
diff --git a/src/PIL/Image.py b/src/PIL/Image.py
index 3ced965e8..9d94bce0e 100644
--- a/src/PIL/Image.py
+++ b/src/PIL/Image.py
@@ -35,6 +35,7 @@ import struct
import sys
import tempfile
import warnings
+import xml.etree.ElementTree
from collections.abc import Callable, MutableMapping
from pathlib import Path
@@ -1050,10 +1051,12 @@ class Image:
of colors.
:param colors: The desired number of colors, <= 256
- :param method: 0 = median cut
- 1 = maximum coverage
- 2 = fast octree
- 3 = libimagequant
+ :param method: ``Image.MEDIANCUT=0`` (median cut),
+ ``Image.MAXCOVERAGE=1`` (maximum coverage),
+ ``Image.FASTOCTREE=2`` (fast octree),
+ ``Image.LIBIMAGEQUANT=3`` (libimagequant; check support using
+ :py:func:`PIL.features.check_feature`
+ with ``feature="libimagequant"``).
:param kmeans: Integer
:param palette: Quantize to the palette of given
:py:class:`PIL.Image.Image`.
@@ -1300,7 +1303,28 @@ class Image:
def getexif(self):
if self._exif is None:
self._exif = Exif()
- self._exif.load(self.info.get("exif"))
+
+ exif_info = self.info.get("exif")
+ if exif_info is None and "Raw profile type exif" in self.info:
+ exif_info = bytes.fromhex(
+ "".join(self.info["Raw profile type exif"].split("\n")[3:])
+ )
+ self._exif.load(exif_info)
+
+ # XMP tags
+ if 0x0112 not in self._exif:
+ xmp_tags = self.info.get("XML:com.adobe.xmp")
+ if xmp_tags:
+ root = xml.etree.ElementTree.fromstring(xmp_tags)
+ for elem in root.iter():
+ if elem.tag.endswith("}Description"):
+ orientation = elem.attrib.get(
+ "{http://ns.adobe.com/tiff/1.0/}Orientation"
+ )
+ if orientation:
+ self._exif[0x0112] = int(orientation)
+ break
+
return self._exif
def getim(self):
@@ -2080,7 +2104,7 @@ class Image:
:returns: None
:exception ValueError: If the output format could not be determined
from the file name. Use the format option to solve this.
- :exception IOError: If the file could not be written. The file
+ :exception OSError: If the file could not be written. The file
may have been created, and may contain partial data.
"""
@@ -2141,7 +2165,7 @@ class Image:
"""
Seeks to the given frame in this sequence file. If you seek
beyond the end of the sequence, the method raises an
- **EOFError** exception. When a sequence file is opened, the
+ ``EOFError`` exception. When a sequence file is opened, the
library automatically seeks to frame 0.
See :py:meth:`~PIL.Image.Image.tell`.
@@ -2247,6 +2271,7 @@ class Image:
:py:attr:`PIL.Image.BICUBIC`, or :py:attr:`PIL.Image.LANCZOS`.
If omitted, it defaults to :py:attr:`PIL.Image.BICUBIC`.
(was :py:attr:`PIL.Image.NEAREST` prior to version 2.5.0).
+ See: :ref:`concept-filters`.
:param reducing_gap: Apply optimization by resizing the image
in two steps. First, reducing the image by integer times
using :py:meth:`~PIL.Image.Image.reduce` or
@@ -2276,7 +2301,9 @@ class Image:
if x / y >= aspect:
x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y))
else:
- y = round_aspect(x / aspect, key=lambda n: abs(aspect - x / n))
+ y = round_aspect(
+ x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n)
+ )
size = (x, y)
box = None
@@ -2324,7 +2351,7 @@ class Image:
It may also be an object with a :py:meth:`~method.getdata` method
that returns a tuple supplying new **method** and **data** values::
- class Example(object):
+ class Example:
def getdata(self):
method = Image.EXTENT
data = (0, 0, 100, 100)
@@ -2336,6 +2363,7 @@ class Image:
environment), or :py:attr:`PIL.Image.BICUBIC` (cubic spline
interpolation in a 4x4 environment). If omitted, or if the image
has mode "1" or "P", it is set to :py:attr:`PIL.Image.NEAREST`.
+ See: :ref:`concept-filters`.
:param fill: If **method** is an
:py:class:`~PIL.Image.ImageTransformHandler` object, this is one of
the arguments passed to it. Otherwise, it is unused.
@@ -2725,7 +2753,7 @@ def fromarray(obj, mode=None):
if ndim > ndmax:
raise ValueError("Too many dimensions: %d > %d." % (ndim, ndmax))
- size = shape[1], shape[0]
+ size = 1 if ndim == 1 else shape[1], shape[0]
if strides is not None:
if hasattr(obj, "tobytes"):
obj = obj.tobytes()
@@ -3222,7 +3250,7 @@ class Exif(MutableMapping):
def _fixup(self, value):
try:
- if len(value) == 1 and not isinstance(value, dict):
+ if len(value) == 1 and isinstance(value, tuple):
return value[0]
except Exception:
pass
@@ -3243,7 +3271,7 @@ class Exif(MutableMapping):
else:
from . import TiffImagePlugin
- info = TiffImagePlugin.ImageFileDirectory_v1(self.head)
+ info = TiffImagePlugin.ImageFileDirectory_v2(self.head)
info.load(self.fp)
return self._fixup_dict(info)
@@ -3263,12 +3291,14 @@ class Exif(MutableMapping):
if not data:
return
- self.fp = io.BytesIO(data[6:])
+ if data.startswith(b"Exif\x00\x00"):
+ data = data[6:]
+ self.fp = io.BytesIO(data)
self.head = self.fp.read(8)
# process dictionary
from . import TiffImagePlugin
- self._info = TiffImagePlugin.ImageFileDirectory_v1(self.head)
+ self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head)
self.endian = self._info._endian
self.fp.seek(self._info.next)
self._info.load(self.fp)
@@ -3279,7 +3309,7 @@ class Exif(MutableMapping):
self._data.update(ifd)
self._ifds[0x8769] = ifd
- def tobytes(self, offset=0):
+ def tobytes(self, offset=8):
from . import TiffImagePlugin
if self.endian == "<":
diff --git a/src/PIL/ImageChops.py b/src/PIL/ImageChops.py
index 2d13b529f..c1a2574e4 100644
--- a/src/PIL/ImageChops.py
+++ b/src/PIL/ImageChops.py
@@ -54,7 +54,7 @@ def invert(image):
def lighter(image1, image2):
"""
Compares the two images, pixel by pixel, and returns a new image containing
- the lighter values. At least one of the images must have mode "1".
+ the lighter values.
.. code-block:: python
@@ -71,7 +71,7 @@ def lighter(image1, image2):
def darker(image1, image2):
"""
Compares the two images, pixel by pixel, and returns a new image containing
- the darker values. At least one of the images must have mode "1".
+ the darker values.
.. code-block:: python
@@ -88,7 +88,7 @@ def darker(image1, image2):
def difference(image1, image2):
"""
Returns the absolute value of the pixel-by-pixel difference between the two
- images. At least one of the images must have mode "1".
+ images.
.. code-block:: python
@@ -107,8 +107,7 @@ def multiply(image1, image2):
Superimposes two images on top of each other.
If you multiply an image with a solid black image, the result is black. If
- you multiply with a solid white image, the image is unaffected. At least
- one of the images must have mode "1".
+ you multiply with a solid white image, the image is unaffected.
.. code-block:: python
@@ -124,8 +123,7 @@ def multiply(image1, image2):
def screen(image1, image2):
"""
- Superimposes two inverted images on top of each other. At least one of the
- images must have mode "1".
+ Superimposes two inverted images on top of each other.
.. code-block:: python
@@ -179,7 +177,6 @@ def add(image1, image2, scale=1.0, offset=0):
"""
Adds two images, dividing the result by scale and adding the
offset. If omitted, scale defaults to 1.0, and offset to 0.0.
- At least one of the images must have mode "1".
.. code-block:: python
@@ -196,8 +193,7 @@ def add(image1, image2, scale=1.0, offset=0):
def subtract(image1, image2, scale=1.0, offset=0):
"""
Subtracts two images, dividing the result by scale and adding the offset.
- If omitted, scale defaults to 1.0, and offset to 0.0. At least one of the
- images must have mode "1".
+ If omitted, scale defaults to 1.0, and offset to 0.0.
.. code-block:: python
@@ -212,8 +208,7 @@ def subtract(image1, image2, scale=1.0, offset=0):
def add_modulo(image1, image2):
- """Add two images, without clipping the result. At least one of the images
- must have mode "1".
+ """Add two images, without clipping the result.
.. code-block:: python
@@ -228,8 +223,7 @@ def add_modulo(image1, image2):
def subtract_modulo(image1, image2):
- """Subtract two images, without clipping the result. At least one of the
- images must have mode "1".
+ """Subtract two images, without clipping the result.
.. code-block:: python
@@ -244,8 +238,12 @@ def subtract_modulo(image1, image2):
def logical_and(image1, image2):
- """Logical AND between two images. At least one of the images must have
- mode "1".
+ """Logical AND between two images.
+
+ Both of the images must have mode "1". If you would like to perform a
+ logical AND on an image with a mode other than "1", try
+ :py:meth:`~PIL.ImageChops.multiply` instead, using a black-and-white mask
+ as the second image.
.. code-block:: python
@@ -260,8 +258,9 @@ def logical_and(image1, image2):
def logical_or(image1, image2):
- """Logical OR between two images. At least one of the images must have
- mode "1".
+ """Logical OR between two images.
+
+ Both of the images must have mode "1".
.. code-block:: python
@@ -276,8 +275,9 @@ def logical_or(image1, image2):
def logical_xor(image1, image2):
- """Logical XOR between two images. At least one of the images must have
- mode "1".
+ """Logical XOR between two images.
+
+ Both of the images must have mode "1".
.. code-block:: python
diff --git a/src/PIL/ImageCms.py b/src/PIL/ImageCms.py
index 661c3f33b..723e7ceb7 100644
--- a/src/PIL/ImageCms.py
+++ b/src/PIL/ImageCms.py
@@ -192,9 +192,9 @@ class ImageCmsTransform(Image.ImagePointHandler):
"""
Transform. This can be used with the procedural API, or with the standard
- Image.point() method.
+ :py:func:`~PIL.Image.Image.point` method.
- Will return the output profile in the output.info['icc_profile'].
+ Will return the output profile in the ``output.info['icc_profile']``.
"""
def __init__(
@@ -251,7 +251,7 @@ class ImageCmsTransform(Image.ImagePointHandler):
def get_display_profile(handle=None):
""" (experimental) Fetches the profile for the current display device.
- :returns: None if the profile is not known.
+ :returns: ``None`` if the profile is not known.
"""
if sys.platform != "win32":
@@ -292,27 +292,27 @@ def profileToProfile(
):
"""
(pyCMS) Applies an ICC transformation to a given image, mapping from
- inputProfile to outputProfile.
+ ``inputProfile`` to ``outputProfile``.
If the input or output profiles specified are not valid filenames, a
- PyCMSError will be raised. If inPlace is True and outputMode != im.mode,
- a PyCMSError will be raised. If an error occurs during application of
- the profiles, a PyCMSError will be raised. If outputMode is not a mode
- supported by the outputProfile (or by pyCMS), a PyCMSError will be
- raised.
+ ``PyCMSError`` will be raised. If ``inPlace`` is ``True`` and
+ ``outputMode != im.mode``, a ``PyCMSError`` will be raised. If an error
+ occurs during application of the profiles, a ``PyCMSError`` will be raised.
+ If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS),
+ a ``PyCMSError`` will be raised.
- This function applies an ICC transformation to im from inputProfile's
- color space to outputProfile's color space using the specified rendering
+ This function applies an ICC transformation to im from ``inputProfile``'s
+ color space to ``outputProfile``'s color space using the specified rendering
intent to decide how to handle out-of-gamut colors.
- OutputMode can be used to specify that a color mode conversion is to
+ ``outputMode`` can be used to specify that a color mode conversion is to
be done using these profiles, but the specified profiles must be able
to handle that mode. I.e., if converting im from RGB to CMYK using
profiles, the input profile must handle RGB data, and the output
profile must handle CMYK data.
- :param im: An open PIL image object (i.e. Image.new(...) or
- Image.open(...), etc.)
+ :param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...)
+ or Image.open(...), etc.)
:param inputProfile: String, as a valid filename path to the ICC input
profile you wish to use for this image, or a profile object
:param outputProfile: String, as a valid filename path to the ICC output
@@ -332,12 +332,12 @@ def profileToProfile(
MUST be the same mode as the input, or omitted completely. If
omitted, the outputMode will be the same as the mode of the input
image (im.mode)
- :param inPlace: Boolean. If True, the original image is modified in-place,
- and None is returned. If False (default), a new Image object is
- returned with the transform applied.
+ :param inPlace: Boolean. If ``True``, the original image is modified in-place,
+ and ``None`` is returned. If ``False`` (default), a new
+ :py:class:`~PIL.Image.Image` object is returned with the transform applied.
:param flags: Integer (0-...) specifying additional flags
- :returns: Either None or a new PIL image object, depending on value of
- inPlace
+ :returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on
+ the value of ``inPlace``
:exception PyCMSError:
"""
@@ -381,7 +381,7 @@ def getOpenProfile(profileFilename):
The PyCMSProfile object can be passed back into pyCMS for use in creating
transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
- If profileFilename is not a valid filename for an ICC profile, a PyCMSError
+ If ``profileFilename`` is not a valid filename for an ICC profile, a ``PyCMSError``
will be raised.
:param profileFilename: String, as a valid filename path to the ICC profile
@@ -405,21 +405,21 @@ def buildTransform(
flags=0,
):
"""
- (pyCMS) Builds an ICC transform mapping from the inputProfile to the
- outputProfile. Use applyTransform to apply the transform to a given
+ (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
+ ``outputProfile``. Use applyTransform to apply the transform to a given
image.
If the input or output profiles specified are not valid filenames, a
- PyCMSError will be raised. If an error occurs during creation of the
- transform, a PyCMSError will be raised.
+ ``PyCMSError`` will be raised. If an error occurs during creation of the
+ transform, a ``PyCMSError`` will be raised.
- If inMode or outMode are not a mode supported by the outputProfile (or
- by pyCMS), a PyCMSError will be raised.
+ If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
+ (or by pyCMS), a ``PyCMSError`` will be raised.
- This function builds and returns an ICC transform from the inputProfile
- to the outputProfile using the renderingIntent to determine what to do
+ This function builds and returns an ICC transform from the ``inputProfile``
+ to the ``outputProfile`` using the ``renderingIntent`` to determine what to do
with out-of-gamut colors. It will ONLY work for converting images that
- are in inMode to images that are in outMode color format (PIL mode,
+ are in ``inMode`` to images that are in ``outMode`` color format (PIL mode,
i.e. "RGB", "RGBA", "CMYK", etc.).
Building the transform is a fair part of the overhead in
@@ -432,7 +432,7 @@ def buildTransform(
The reason pyCMS returns a class object rather than a handle directly
to the transform is that it needs to keep track of the PIL input/output
modes that the transform is meant for. These attributes are stored in
- the "inMode" and "outMode" attributes of the object (which can be
+ the ``inMode`` and ``outMode`` attributes of the object (which can be
manually overridden if you really want to, but I don't know of any
time that would be of use, or would even work).
@@ -488,25 +488,25 @@ def buildProofTransform(
flags=FLAGS["SOFTPROOFING"],
):
"""
- (pyCMS) Builds an ICC transform mapping from the inputProfile to the
- outputProfile, but tries to simulate the result that would be
- obtained on the proofProfile device.
+ (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
+ ``outputProfile``, but tries to simulate the result that would be
+ obtained on the ``proofProfile`` device.
If the input, output, or proof profiles specified are not valid
- filenames, a PyCMSError will be raised.
+ filenames, a ``PyCMSError`` will be raised.
- If an error occurs during creation of the transform, a PyCMSError will
- be raised.
+ If an error occurs during creation of the transform, a ``PyCMSError``
+ will be raised.
- If inMode or outMode are not a mode supported by the outputProfile
- (or by pyCMS), a PyCMSError will be raised.
+ If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
+ (or by pyCMS), a ``PyCMSError`` will be raised.
- This function builds and returns an ICC transform from the inputProfile
- to the outputProfile, but tries to simulate the result that would be
- obtained on the proofProfile device using renderingIntent and
- proofRenderingIntent to determine what to do with out-of-gamut
+ This function builds and returns an ICC transform from the ``inputProfile``
+ to the ``outputProfile``, but tries to simulate the result that would be
+ obtained on the ``proofProfile`` device using ``renderingIntent`` and
+ ``proofRenderingIntent`` to determine what to do with out-of-gamut
colors. This is known as "soft-proofing". It will ONLY work for
- converting images that are in inMode to images that are in outMode
+ converting images that are in ``inMode`` to images that are in outMode
color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.).
Usage of the resulting transform object is exactly the same as with
@@ -514,7 +514,7 @@ def buildProofTransform(
Proof profiling is generally used when using an output device to get a
good idea of what the final printed/displayed image would look like on
- the proofProfile device when it's quicker and easier to use the
+ the ``proofProfile`` device when it's quicker and easier to use the
output device for judging color. Generally, this means that the
output device is a monitor, or a dye-sub printer (etc.), and the simulated
device is something more expensive, complicated, or time consuming
@@ -596,39 +596,40 @@ def applyTransform(im, transform, inPlace=False):
"""
(pyCMS) Applies a transform to a given image.
- If im.mode != transform.inMode, a PyCMSError is raised.
+ If ``im.mode != transform.inMode``, a ``PyCMSError`` is raised.
- If inPlace is True and transform.inMode != transform.outMode, a
- PyCMSError is raised.
+ If ``inPlace`` is ``True`` and ``transform.inMode != transform.outMode``, a
+ ``PyCMSError`` is raised.
- If im.mode, transform.inMode, or transform.outMode is not supported by
- pyCMSdll or the profiles you used for the transform, a PyCMSError is
- raised.
+ If ``im.mode``, ``transform.inMode`` or ``transform.outMode`` is not
+ supported by pyCMSdll or the profiles you used for the transform, a
+ ``PyCMSError`` is raised.
- If an error occurs while the transform is being applied, a PyCMSError
+ If an error occurs while the transform is being applied, a ``PyCMSError``
is raised.
This function applies a pre-calculated transform (from
ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles())
- to an image. The transform can be used for multiple images, saving
+ to an image. The transform can be used for multiple images, saving
considerable calculation time if doing the same conversion multiple times.
If you want to modify im in-place instead of receiving a new image as
- the return value, set inPlace to True. This can only be done if
- transform.inMode and transform.outMode are the same, because we can't
+ the return value, set ``inPlace`` to ``True``. This can only be done if
+ ``transform.inMode`` and ``transform.outMode`` are the same, because we can't
change the mode in-place (the buffer sizes for some modes are
- different). The default behavior is to return a new Image object of
- the same dimensions in mode transform.outMode.
+ different). The default behavior is to return a new :py:class:`~PIL.Image.Image`
+ object of the same dimensions in mode ``transform.outMode``.
- :param im: A PIL Image object, and im.mode must be the same as the inMode
- supported by the transform.
+ :param im: An :py:class:`~PIL.Image.Image` object, and im.mode must be the same
+ as the ``inMode`` supported by the transform.
:param transform: A valid CmsTransform class object
- :param inPlace: Bool. If True, im is modified in place and None is
- returned, if False, a new Image object with the transform applied is
- returned (and im is not changed). The default is False.
- :returns: Either None, or a new PIL Image object, depending on the value of
- inPlace. The profile will be returned in the image's
- info['icc_profile'].
+ :param inPlace: Bool. If ``True``, ``im` is modified in place and ``None`` is
+ returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the
+ transform applied is returned (and ``im`` is not changed). The default is
+ ``False``.
+ :returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object,
+ depending on the value of ``inPlace``. The profile will be returned in
+ the image's ``info['icc_profile']``.
:exception PyCMSError:
"""
@@ -648,11 +649,12 @@ def createProfile(colorSpace, colorTemp=-1):
"""
(pyCMS) Creates a profile.
- If colorSpace not in ["LAB", "XYZ", "sRGB"], a PyCMSError is raised
+ If colorSpace not in ``["LAB", "XYZ", "sRGB"]``, a ``PyCMSError`` is raised.
- If using LAB and colorTemp != a positive integer, a PyCMSError is raised.
+ If using LAB and ``colorTemp`` is not a positive integer, a ``PyCMSError`` is
+ raised.
- If an error occurs while creating the profile, a PyCMSError is raised.
+ If an error occurs while creating the profile, a ``PyCMSError`` is raised.
Use this function to create common profiles on-the-fly instead of
having to supply a profile on disk and knowing the path to it. It
@@ -696,9 +698,9 @@ def getProfileName(profile):
(pyCMS) Gets the internal product name for the given profile.
- If profile isn't a valid CmsProfile object or filename to a profile,
- a PyCMSError is raised If an error occurs while trying to obtain the
- name tag, a PyCMSError is raised.
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile,
+ a ``PyCMSError`` is raised If an error occurs while trying to obtain the
+ name tag, a ``PyCMSError`` is raised.
Use this function to obtain the INTERNAL name of the profile (stored
in an ICC tag in the profile itself), usually the one used when the
@@ -737,11 +739,11 @@ def getProfileInfo(profile):
"""
(pyCMS) Gets the internal product information for the given profile.
- If profile isn't a valid CmsProfile object or filename to a profile,
- a PyCMSError is raised.
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile,
+ a ``PyCMSError`` is raised.
- If an error occurs while trying to obtain the info tag, a PyCMSError
- is raised
+ If an error occurs while trying to obtain the info tag, a ``PyCMSError``
+ is raised.
Use this function to obtain the information stored in the profile's
info tag. This often contains details about the profile, and how it
@@ -777,11 +779,11 @@ def getProfileCopyright(profile):
"""
(pyCMS) Gets the copyright for the given profile.
- If profile isn't a valid CmsProfile object or filename to a profile,
- a PyCMSError is raised.
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
+ ``PyCMSError`` is raised.
- If an error occurs while trying to obtain the copyright tag, a PyCMSError
- is raised
+ If an error occurs while trying to obtain the copyright tag, a ``PyCMSError``
+ is raised.
Use this function to obtain the information stored in the profile's
copyright tag.
@@ -805,11 +807,11 @@ def getProfileManufacturer(profile):
"""
(pyCMS) Gets the manufacturer for the given profile.
- If profile isn't a valid CmsProfile object or filename to a profile,
- a PyCMSError is raised.
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
+ ``PyCMSError`` is raised.
If an error occurs while trying to obtain the manufacturer tag, a
- PyCMSError is raised
+ ``PyCMSError`` is raised.
Use this function to obtain the information stored in the profile's
manufacturer tag.
@@ -833,11 +835,11 @@ def getProfileModel(profile):
"""
(pyCMS) Gets the model for the given profile.
- If profile isn't a valid CmsProfile object or filename to a profile,
- a PyCMSError is raised.
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
+ ``PyCMSError`` is raised.
- If an error occurs while trying to obtain the model tag, a PyCMSError
- is raised
+ If an error occurs while trying to obtain the model tag, a ``PyCMSError``
+ is raised.
Use this function to obtain the information stored in the profile's
model tag.
@@ -862,11 +864,11 @@ def getProfileDescription(profile):
"""
(pyCMS) Gets the description for the given profile.
- If profile isn't a valid CmsProfile object or filename to a profile,
- a PyCMSError is raised.
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
+ ``PyCMSError`` is raised.
- If an error occurs while trying to obtain the description tag, a PyCMSError
- is raised
+ If an error occurs while trying to obtain the description tag, a ``PyCMSError``
+ is raised.
Use this function to obtain the information stored in the profile's
description tag.
@@ -891,11 +893,11 @@ def getDefaultIntent(profile):
"""
(pyCMS) Gets the default intent name for the given profile.
- If profile isn't a valid CmsProfile object or filename to a profile,
- a PyCMSError is raised.
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
+ ``PyCMSError`` is raised.
If an error occurs while trying to obtain the default intent, a
- PyCMSError is raised.
+ ``PyCMSError`` is raised.
Use this function to determine the default (and usually best optimized)
rendering intent for this profile. Most profiles support multiple
@@ -931,14 +933,14 @@ def isIntentSupported(profile, intent, direction):
(pyCMS) Checks if a given intent is supported.
Use this function to verify that you can use your desired
- renderingIntent with profile, and that profile can be used for the
+ ``intent`` with ``profile``, and that ``profile`` can be used for the
input/output/proof profile as you desire.
Some profiles are created specifically for one "direction", can cannot
- be used for others. Some profiles can only be used for certain
- rendering intents... so it's best to either verify this before trying
+ be used for others. Some profiles can only be used for certain
+ rendering intents, so it's best to either verify this before trying
to create a transform with them (using this function), or catch the
- potential PyCMSError that will occur if they don't support the modes
+ potential ``PyCMSError`` that will occur if they don't support the modes
you select.
:param profile: EITHER a valid CmsProfile object, OR a string of the
diff --git a/src/PIL/ImageDraw.py b/src/PIL/ImageDraw.py
index 7abd459f9..cbecf652d 100644
--- a/src/PIL/ImageDraw.py
+++ b/src/PIL/ImageDraw.py
@@ -156,6 +156,8 @@ class ImageDraw:
if ink is not None:
self.draw.draw_lines(xy, ink, width)
if joint == "curve" and width > 4:
+ if not isinstance(xy[0], (list, tuple)):
+ xy = [tuple(xy[i : i + 2]) for i in range(0, len(xy), 2)]
for i in range(1, len(xy) - 1):
point = xy[i]
angles = [
diff --git a/src/PIL/ImageFile.py b/src/PIL/ImageFile.py
index 628796865..9a780b4e0 100644
--- a/src/PIL/ImageFile.py
+++ b/src/PIL/ImageFile.py
@@ -30,6 +30,7 @@
import io
import struct
import sys
+import warnings
from . import Image
from ._util import isPath
@@ -49,7 +50,12 @@ ERRORS = {
}
-def raise_ioerror(error):
+#
+# --------------------------------------------------------------------
+# Helpers
+
+
+def raise_oserror(error):
try:
message = Image.core.getcodecstatus(error)
except AttributeError:
@@ -59,9 +65,13 @@ def raise_ioerror(error):
raise OSError(message + " when reading image file")
-#
-# --------------------------------------------------------------------
-# Helpers
+def raise_ioerror(error):
+ warnings.warn(
+ "raise_ioerror is deprecated and will be removed in a future release. "
+ "Use raise_oserror instead.",
+ DeprecationWarning,
+ )
+ return raise_oserror(error)
def _tilesort(t):
@@ -140,10 +150,10 @@ class ImageFile(Image.Image):
def load(self):
"""Load image data based on tile list"""
- pixel = Image.Image.load(self)
-
if self.tile is None:
raise OSError("cannot load this image")
+
+ pixel = Image.Image.load(self)
if not self.tile:
return pixel
@@ -267,7 +277,7 @@ class ImageFile(Image.Image):
if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0:
# still raised if decoder fails to return anything
- raise_ioerror(err_code)
+ raise_oserror(err_code)
return Image.Image.load(self)
@@ -358,7 +368,7 @@ class Parser:
(Consumer) Feed data to the parser.
:param data: A string buffer.
- :exception IOError: If the parser failed to parse the image file.
+ :exception OSError: If the parser failed to parse the image file.
"""
# collect data
@@ -390,7 +400,7 @@ class Parser:
if e < 0:
# decoding error
self.image = None
- raise_ioerror(e)
+ raise_oserror(e)
else:
# end of image
return
@@ -444,7 +454,7 @@ class Parser:
(Consumer) Close the stream.
:returns: An image object.
- :exception IOError: If the parser failed to parse the image file either
+ :exception OSError: If the parser failed to parse the image file either
because it cannot be identified or cannot be
decoded.
"""
diff --git a/src/PIL/ImageFont.py b/src/PIL/ImageFont.py
index 027e4c42e..79c161713 100644
--- a/src/PIL/ImageFont.py
+++ b/src/PIL/ImageFont.py
@@ -499,7 +499,7 @@ class FreeTypeFont:
def get_variation_names(self):
"""
:returns: A list of the named styles in a variation font.
- :exception IOError: If the font is not a variation font.
+ :exception OSError: If the font is not a variation font.
"""
try:
names = self.font.getvarnames()
@@ -510,7 +510,7 @@ class FreeTypeFont:
def set_variation_by_name(self, name):
"""
:param name: The name of the style.
- :exception IOError: If the font is not a variation font.
+ :exception OSError: If the font is not a variation font.
"""
names = self.get_variation_names()
if not isinstance(name, bytes):
@@ -529,7 +529,7 @@ class FreeTypeFont:
def get_variation_axes(self):
"""
:returns: A list of the axes in a variation font.
- :exception IOError: If the font is not a variation font.
+ :exception OSError: If the font is not a variation font.
"""
try:
axes = self.font.getvaraxes()
@@ -542,7 +542,7 @@ class FreeTypeFont:
def set_variation_by_axes(self, axes):
"""
:param axes: A list of values for each axis.
- :exception IOError: If the font is not a variation font.
+ :exception OSError: If the font is not a variation font.
"""
try:
self.font.setvaraxes(axes)
@@ -586,7 +586,7 @@ def load(filename):
:param filename: Name of font file.
:return: A font object.
- :exception IOError: If the file could not be read.
+ :exception OSError: If the file could not be read.
"""
f = ImageFont()
f._load_pilfont(filename)
@@ -637,8 +637,13 @@ def truetype(font=None, size=10, index=0, encoding="", layout_engine=None):
encoding of any text provided in subsequent operations.
:param layout_engine: Which layout engine to use, if available:
`ImageFont.LAYOUT_BASIC` or `ImageFont.LAYOUT_RAQM`.
+
+ You can check support for Raqm layout using
+ :py:func:`PIL.features.check_feature` with ``feature="raqm"``.
+
+ .. versionadded:: 4.2.0
:return: A font object.
- :exception IOError: If the file could not be read.
+ :exception OSError: If the file could not be read.
"""
def freetype(font):
@@ -698,7 +703,7 @@ def load_path(filename):
:param filename: Name of font file.
:return: A font object.
- :exception IOError: If the file could not be read.
+ :exception OSError: If the file could not be read.
"""
for directory in sys.path:
if isDirectory(directory):
diff --git a/src/PIL/ImageGrab.py b/src/PIL/ImageGrab.py
index 66e2e8560..8b38df323 100644
--- a/src/PIL/ImageGrab.py
+++ b/src/PIL/ImageGrab.py
@@ -2,7 +2,7 @@
# The Python Imaging Library
# $Id$
#
-# screen grabber (macOS and Windows only)
+# screen grabber
#
# History:
# 2001-04-26 fl created
@@ -60,7 +60,7 @@ def grab(bbox=None, include_layered_windows=False, all_screens=False, xdisplay=N
return im
# use xdisplay=None for default display on non-win32/macOS systems
if not Image.core.HAVE_XCB:
- raise IOError("Pillow was built without XCB support")
+ raise OSError("Pillow was built without XCB support")
size, data = Image.core.grabscreen_x11(xdisplay)
im = Image.frombytes("RGB", size, data, "raw", "BGRX", size[0] * 4, 1)
if bbox:
diff --git a/src/PIL/ImageQt.py b/src/PIL/ImageQt.py
index dfe2f80bd..a15f4ab5e 100644
--- a/src/PIL/ImageQt.py
+++ b/src/PIL/ImageQt.py
@@ -142,12 +142,7 @@ def _toqclass_helper(im):
data = im.tobytes("raw", "BGRX")
format = QImage.Format_RGB32
elif im.mode == "RGBA":
- try:
- data = im.tobytes("raw", "BGRA")
- except SystemError:
- # workaround for earlier versions
- r, g, b, a = im.split()
- im = Image.merge("RGBA", (b, g, r, a))
+ data = im.tobytes("raw", "BGRA")
format = QImage.Format_ARGB32
else:
raise ValueError("unsupported image mode %r" % im.mode)
diff --git a/src/PIL/ImageWin.py b/src/PIL/ImageWin.py
index 927b1694b..afba61c32 100644
--- a/src/PIL/ImageWin.py
+++ b/src/PIL/ImageWin.py
@@ -173,7 +173,7 @@ class Dib:
Load display memory contents from byte data.
:param buffer: A buffer containing display data (usually
- data returned from tobytes)
+ data returned from :py:func:`~PIL.ImageWin.Dib.tobytes`)
"""
return self.image.frombytes(buffer)
diff --git a/src/PIL/JpegImagePlugin.py b/src/PIL/JpegImagePlugin.py
index 2aa029efb..89e70f0e9 100644
--- a/src/PIL/JpegImagePlugin.py
+++ b/src/PIL/JpegImagePlugin.py
@@ -221,7 +221,7 @@ def SOF(self, marker):
else:
icc_profile = None # wrong number of fragments
self.info["icc_profile"] = icc_profile
- self.icclist = None
+ self.icclist = []
for i in range(6, len(s), 3):
t = s[i : i + 3]
@@ -593,9 +593,9 @@ def convert_dict_qtables(qtables):
def get_sampling(im):
- # There's no subsampling when image have only 1 layer
+ # There's no subsampling when images have only 1 layer
# (grayscale images) or when they are CMYK (4 layers),
- # so set subsampling to default value.
+ # so set subsampling to the default value.
#
# NOTE: currently Pillow can't encode JPEG to YCCK format.
# If YCCK support is added in the future, subsampling code will have
diff --git a/src/PIL/JpegPresets.py b/src/PIL/JpegPresets.py
index 012bf81b0..118dab061 100644
--- a/src/PIL/JpegPresets.py
+++ b/src/PIL/JpegPresets.py
@@ -71,7 +71,7 @@ https://web.archive.org/web/20120328125543/http://www.jpegcameras.com/libjpeg/li
"""
# fmt: off
-presets = { # noqa: E128
+presets = {
'web_low': {'subsampling': 2, # "4:2:0"
'quantization': [
[20, 16, 25, 39, 50, 46, 62, 68,
@@ -112,16 +112,16 @@ presets = { # noqa: E128
]},
'web_high': {'subsampling': 0, # "4:4:4"
'quantization': [
- [6, 4, 4, 6, 9, 11, 12, 16,
- 4, 5, 5, 6, 8, 10, 12, 12,
- 4, 5, 5, 6, 10, 12, 14, 19,
- 6, 6, 6, 11, 12, 15, 19, 28,
- 9, 8, 10, 12, 16, 20, 27, 31,
+ [6, 4, 4, 6, 9, 11, 12, 16,
+ 4, 5, 5, 6, 8, 10, 12, 12,
+ 4, 5, 5, 6, 10, 12, 14, 19,
+ 6, 6, 6, 11, 12, 15, 19, 28,
+ 9, 8, 10, 12, 16, 20, 27, 31,
11, 10, 12, 15, 20, 27, 31, 31,
12, 12, 14, 19, 27, 31, 31, 31,
16, 12, 19, 28, 31, 31, 31, 31],
- [7, 7, 13, 24, 26, 31, 31, 31,
- 7, 12, 16, 21, 31, 31, 31, 31,
+ [7, 7, 13, 24, 26, 31, 31, 31,
+ 7, 12, 16, 21, 31, 31, 31, 31,
13, 16, 17, 31, 31, 31, 31, 31,
24, 21, 31, 31, 31, 31, 31, 31,
26, 31, 31, 31, 31, 31, 31, 31,
@@ -131,18 +131,18 @@ presets = { # noqa: E128
]},
'web_very_high': {'subsampling': 0, # "4:4:4"
'quantization': [
- [2, 2, 2, 2, 3, 4, 5, 6,
- 2, 2, 2, 2, 3, 4, 5, 6,
- 2, 2, 2, 2, 4, 5, 7, 9,
- 2, 2, 2, 4, 5, 7, 9, 12,
- 3, 3, 4, 5, 8, 10, 12, 12,
- 4, 4, 5, 7, 10, 12, 12, 12,
- 5, 5, 7, 9, 12, 12, 12, 12,
- 6, 6, 9, 12, 12, 12, 12, 12],
- [3, 3, 5, 9, 13, 15, 15, 15,
- 3, 4, 6, 11, 14, 12, 12, 12,
- 5, 6, 9, 14, 12, 12, 12, 12,
- 9, 11, 14, 12, 12, 12, 12, 12,
+ [2, 2, 2, 2, 3, 4, 5, 6,
+ 2, 2, 2, 2, 3, 4, 5, 6,
+ 2, 2, 2, 2, 4, 5, 7, 9,
+ 2, 2, 2, 4, 5, 7, 9, 12,
+ 3, 3, 4, 5, 8, 10, 12, 12,
+ 4, 4, 5, 7, 10, 12, 12, 12,
+ 5, 5, 7, 9, 12, 12, 12, 12,
+ 6, 6, 9, 12, 12, 12, 12, 12],
+ [3, 3, 5, 9, 13, 15, 15, 15,
+ 3, 4, 6, 11, 14, 12, 12, 12,
+ 5, 6, 9, 14, 12, 12, 12, 12,
+ 9, 11, 14, 12, 12, 12, 12, 12,
13, 14, 12, 12, 12, 12, 12, 12,
15, 12, 12, 12, 12, 12, 12, 12,
15, 12, 12, 12, 12, 12, 12, 12,
@@ -189,8 +189,8 @@ presets = { # noqa: E128
'medium': {'subsampling': 2, # "4:2:0"
'quantization': [
[12, 8, 8, 12, 17, 21, 24, 17,
- 8, 9, 9, 11, 15, 19, 12, 12,
- 8, 9, 10, 12, 19, 12, 12, 12,
+ 8, 9, 9, 11, 15, 19, 12, 12,
+ 8, 9, 10, 12, 19, 12, 12, 12,
12, 11, 12, 21, 12, 12, 12, 12,
17, 15, 19, 12, 12, 12, 12, 12,
21, 19, 12, 12, 12, 12, 12, 12,
@@ -207,16 +207,16 @@ presets = { # noqa: E128
]},
'high': {'subsampling': 0, # "4:4:4"
'quantization': [
- [6, 4, 4, 6, 9, 11, 12, 16,
- 4, 5, 5, 6, 8, 10, 12, 12,
- 4, 5, 5, 6, 10, 12, 12, 12,
- 6, 6, 6, 11, 12, 12, 12, 12,
- 9, 8, 10, 12, 12, 12, 12, 12,
+ [6, 4, 4, 6, 9, 11, 12, 16,
+ 4, 5, 5, 6, 8, 10, 12, 12,
+ 4, 5, 5, 6, 10, 12, 12, 12,
+ 6, 6, 6, 11, 12, 12, 12, 12,
+ 9, 8, 10, 12, 12, 12, 12, 12,
11, 10, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
16, 12, 12, 12, 12, 12, 12, 12],
- [7, 7, 13, 24, 20, 20, 17, 17,
- 7, 12, 16, 14, 14, 12, 12, 12,
+ [7, 7, 13, 24, 20, 20, 17, 17,
+ 7, 12, 16, 14, 14, 12, 12, 12,
13, 16, 14, 14, 12, 12, 12, 12,
24, 14, 14, 12, 12, 12, 12, 12,
20, 14, 12, 12, 12, 12, 12, 12,
@@ -226,18 +226,18 @@ presets = { # noqa: E128
]},
'maximum': {'subsampling': 0, # "4:4:4"
'quantization': [
- [2, 2, 2, 2, 3, 4, 5, 6,
- 2, 2, 2, 2, 3, 4, 5, 6,
- 2, 2, 2, 2, 4, 5, 7, 9,
- 2, 2, 2, 4, 5, 7, 9, 12,
- 3, 3, 4, 5, 8, 10, 12, 12,
- 4, 4, 5, 7, 10, 12, 12, 12,
- 5, 5, 7, 9, 12, 12, 12, 12,
- 6, 6, 9, 12, 12, 12, 12, 12],
- [3, 3, 5, 9, 13, 15, 15, 15,
- 3, 4, 6, 10, 14, 12, 12, 12,
- 5, 6, 9, 14, 12, 12, 12, 12,
- 9, 10, 14, 12, 12, 12, 12, 12,
+ [2, 2, 2, 2, 3, 4, 5, 6,
+ 2, 2, 2, 2, 3, 4, 5, 6,
+ 2, 2, 2, 2, 4, 5, 7, 9,
+ 2, 2, 2, 4, 5, 7, 9, 12,
+ 3, 3, 4, 5, 8, 10, 12, 12,
+ 4, 4, 5, 7, 10, 12, 12, 12,
+ 5, 5, 7, 9, 12, 12, 12, 12,
+ 6, 6, 9, 12, 12, 12, 12, 12],
+ [3, 3, 5, 9, 13, 15, 15, 15,
+ 3, 4, 6, 10, 14, 12, 12, 12,
+ 5, 6, 9, 14, 12, 12, 12, 12,
+ 9, 10, 14, 12, 12, 12, 12, 12,
13, 14, 12, 12, 12, 12, 12, 12,
15, 12, 12, 12, 12, 12, 12, 12,
15, 12, 12, 12, 12, 12, 12, 12,
diff --git a/src/PIL/MicImagePlugin.py b/src/PIL/MicImagePlugin.py
index 8610988fc..1d7af7c7a 100644
--- a/src/PIL/MicImagePlugin.py
+++ b/src/PIL/MicImagePlugin.py
@@ -64,20 +64,14 @@ class MicImageFile(TiffImagePlugin.TiffImageFile):
self.__fp = self.fp
self.frame = None
+ self._n_frames = len(self.images)
+ self.is_animated = self._n_frames > 1
if len(self.images) > 1:
self.category = Image.CONTAINER
self.seek(0)
- @property
- def n_frames(self):
- return len(self.images)
-
- @property
- def is_animated(self):
- return len(self.images) > 1
-
def seek(self, frame):
if not self._seek_check(frame):
return
diff --git a/src/PIL/MpoImagePlugin.py b/src/PIL/MpoImagePlugin.py
index e97176d57..575cc9c8e 100644
--- a/src/PIL/MpoImagePlugin.py
+++ b/src/PIL/MpoImagePlugin.py
@@ -48,15 +48,16 @@ class MpoImageFile(JpegImagePlugin.JpegImageFile):
def _after_jpeg_open(self, mpheader=None):
self.mpinfo = mpheader if mpheader is not None else self._getmp()
- self.__framecount = self.mpinfo[0xB001]
+ self.n_frames = self.mpinfo[0xB001]
self.__mpoffsets = [
mpent["DataOffset"] + self.info["mpoffset"] for mpent in self.mpinfo[0xB002]
]
self.__mpoffsets[0] = 0
# Note that the following assertion will only be invalid if something
# gets broken within JpegImagePlugin.
- assert self.__framecount == len(self.__mpoffsets)
+ assert self.n_frames == len(self.__mpoffsets)
del self.info["mpoffset"] # no longer needed
+ self.is_animated = self.n_frames > 1
self.__fp = self.fp # FIXME: hack
self.__fp.seek(self.__mpoffsets[0]) # get ready to read first frame
self.__frame = 0
@@ -67,14 +68,6 @@ class MpoImageFile(JpegImagePlugin.JpegImageFile):
def load_seek(self, pos):
self.__fp.seek(pos)
- @property
- def n_frames(self):
- return self.__framecount
-
- @property
- def is_animated(self):
- return self.__framecount > 1
-
def seek(self, frame):
if not self._seek_check(frame):
return
diff --git a/src/PIL/PalmImagePlugin.py b/src/PIL/PalmImagePlugin.py
index 804ece34a..9fc55d795 100644
--- a/src/PIL/PalmImagePlugin.py
+++ b/src/PIL/PalmImagePlugin.py
@@ -11,7 +11,7 @@ from . import Image, ImageFile
from ._binary import o8, o16be as o16b
# fmt: off
-_Palm8BitColormapValues = ( # noqa: E131
+_Palm8BitColormapValues = (
(255, 255, 255), (255, 204, 255), (255, 153, 255), (255, 102, 255),
(255, 51, 255), (255, 0, 255), (255, 255, 204), (255, 204, 204),
(255, 153, 204), (255, 102, 204), (255, 51, 204), (255, 0, 204),
@@ -30,15 +30,15 @@ _Palm8BitColormapValues = ( # noqa: E131
(102, 255, 204), (102, 204, 204), (102, 153, 204), (102, 102, 204),
(102, 51, 204), (102, 0, 204), (102, 255, 153), (102, 204, 153),
(102, 153, 153), (102, 102, 153), (102, 51, 153), (102, 0, 153),
- (51, 255, 255), (51, 204, 255), (51, 153, 255), (51, 102, 255),
- (51, 51, 255), (51, 0, 255), (51, 255, 204), (51, 204, 204),
- (51, 153, 204), (51, 102, 204), (51, 51, 204), (51, 0, 204),
- (51, 255, 153), (51, 204, 153), (51, 153, 153), (51, 102, 153),
- (51, 51, 153), (51, 0, 153), (0, 255, 255), (0, 204, 255),
- (0, 153, 255), (0, 102, 255), (0, 51, 255), (0, 0, 255),
- (0, 255, 204), (0, 204, 204), (0, 153, 204), (0, 102, 204),
- (0, 51, 204), (0, 0, 204), (0, 255, 153), (0, 204, 153),
- (0, 153, 153), (0, 102, 153), (0, 51, 153), (0, 0, 153),
+ (51, 255, 255), (51, 204, 255), (51, 153, 255), (51, 102, 255),
+ (51, 51, 255), (51, 0, 255), (51, 255, 204), (51, 204, 204),
+ (51, 153, 204), (51, 102, 204), (51, 51, 204), (51, 0, 204),
+ (51, 255, 153), (51, 204, 153), (51, 153, 153), (51, 102, 153),
+ (51, 51, 153), (51, 0, 153), (0, 255, 255), (0, 204, 255),
+ (0, 153, 255), (0, 102, 255), (0, 51, 255), (0, 0, 255),
+ (0, 255, 204), (0, 204, 204), (0, 153, 204), (0, 102, 204),
+ (0, 51, 204), (0, 0, 204), (0, 255, 153), (0, 204, 153),
+ (0, 153, 153), (0, 102, 153), (0, 51, 153), (0, 0, 153),
(255, 255, 102), (255, 204, 102), (255, 153, 102), (255, 102, 102),
(255, 51, 102), (255, 0, 102), (255, 255, 51), (255, 204, 51),
(255, 153, 51), (255, 102, 51), (255, 51, 51), (255, 0, 51),
@@ -57,25 +57,25 @@ _Palm8BitColormapValues = ( # noqa: E131
(102, 255, 51), (102, 204, 51), (102, 153, 51), (102, 102, 51),
(102, 51, 51), (102, 0, 51), (102, 255, 0), (102, 204, 0),
(102, 153, 0), (102, 102, 0), (102, 51, 0), (102, 0, 0),
- (51, 255, 102), (51, 204, 102), (51, 153, 102), (51, 102, 102),
- (51, 51, 102), (51, 0, 102), (51, 255, 51), (51, 204, 51),
- (51, 153, 51), (51, 102, 51), (51, 51, 51), (51, 0, 51),
- (51, 255, 0), (51, 204, 0), (51, 153, 0), (51, 102, 0),
- (51, 51, 0), (51, 0, 0), (0, 255, 102), (0, 204, 102),
- (0, 153, 102), (0, 102, 102), (0, 51, 102), (0, 0, 102),
- (0, 255, 51), (0, 204, 51), (0, 153, 51), (0, 102, 51),
- (0, 51, 51), (0, 0, 51), (0, 255, 0), (0, 204, 0),
- (0, 153, 0), (0, 102, 0), (0, 51, 0), (17, 17, 17),
- (34, 34, 34), (68, 68, 68), (85, 85, 85), (119, 119, 119),
+ (51, 255, 102), (51, 204, 102), (51, 153, 102), (51, 102, 102),
+ (51, 51, 102), (51, 0, 102), (51, 255, 51), (51, 204, 51),
+ (51, 153, 51), (51, 102, 51), (51, 51, 51), (51, 0, 51),
+ (51, 255, 0), (51, 204, 0), (51, 153, 0), (51, 102, 0),
+ (51, 51, 0), (51, 0, 0), (0, 255, 102), (0, 204, 102),
+ (0, 153, 102), (0, 102, 102), (0, 51, 102), (0, 0, 102),
+ (0, 255, 51), (0, 204, 51), (0, 153, 51), (0, 102, 51),
+ (0, 51, 51), (0, 0, 51), (0, 255, 0), (0, 204, 0),
+ (0, 153, 0), (0, 102, 0), (0, 51, 0), (17, 17, 17),
+ (34, 34, 34), (68, 68, 68), (85, 85, 85), (119, 119, 119),
(136, 136, 136), (170, 170, 170), (187, 187, 187), (221, 221, 221),
(238, 238, 238), (192, 192, 192), (128, 0, 0), (128, 0, 128),
- (0, 128, 0), (0, 128, 128), (0, 0, 0), (0, 0, 0),
- (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
- (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
- (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
- (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
- (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
- (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0))
+ (0, 128, 0), (0, 128, 128), (0, 0, 0), (0, 0, 0),
+ (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
+ (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
+ (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
+ (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
+ (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
+ (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0))
# fmt: on
diff --git a/src/PIL/PngImagePlugin.py b/src/PIL/PngImagePlugin.py
index ee9d52b4c..f62bf8542 100644
--- a/src/PIL/PngImagePlugin.py
+++ b/src/PIL/PngImagePlugin.py
@@ -931,16 +931,7 @@ class PngImageFile(ImageFile.ImageFile):
if "exif" not in self.info:
self.load()
- if self._exif is None:
- self._exif = Image.Exif()
-
- exif_info = self.info.get("exif")
- if exif_info is None and "Raw profile type exif" in self.info:
- exif_info = bytes.fromhex(
- "".join(self.info["Raw profile type exif"].split("\n")[3:])
- )
- self._exif.load(exif_info)
- return self._exif
+ return super().getexif()
def _close__fp(self):
try:
diff --git a/src/PIL/PsdImagePlugin.py b/src/PIL/PsdImagePlugin.py
index cceb85c5b..044df443d 100644
--- a/src/PIL/PsdImagePlugin.py
+++ b/src/PIL/PsdImagePlugin.py
@@ -119,6 +119,8 @@ class PsdImageFile(ImageFile.ImageFile):
if size:
self.layers = _layerinfo(self.fp)
self.fp.seek(end)
+ self.n_frames = len(self.layers)
+ self.is_animated = self.n_frames > 1
#
# image descriptor
@@ -130,14 +132,6 @@ class PsdImageFile(ImageFile.ImageFile):
self.frame = 1
self._min_frame = 1
- @property
- def n_frames(self):
- return len(self.layers)
-
- @property
- def is_animated(self):
- return len(self.layers) > 1
-
def seek(self, layer):
if not self._seek_check(layer):
return
diff --git a/src/PIL/PyAccess.py b/src/PIL/PyAccess.py
index 359a94919..494f5f9f4 100644
--- a/src/PIL/PyAccess.py
+++ b/src/PIL/PyAccess.py
@@ -23,23 +23,29 @@
import logging
import sys
-from cffi import FFI
+try:
+ from cffi import FFI
+
+ defs = """
+ struct Pixel_RGBA {
+ unsigned char r,g,b,a;
+ };
+ struct Pixel_I16 {
+ unsigned char l,r;
+ };
+ """
+ ffi = FFI()
+ ffi.cdef(defs)
+except ImportError as ex:
+ # Allow error import for doc purposes, but error out when accessing
+ # anything in core.
+ from ._util import deferred_error
+
+ FFI = ffi = deferred_error(ex)
logger = logging.getLogger(__name__)
-defs = """
-struct Pixel_RGBA {
- unsigned char r,g,b,a;
-};
-struct Pixel_I16 {
- unsigned char l,r;
-};
-"""
-ffi = FFI()
-ffi.cdef(defs)
-
-
class PyAccess:
def __init__(self, img, readonly=False):
vals = dict(img.im.unsafe_ptrs)
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py
index 74fb69516..8e7570062 100644
--- a/src/PIL/TiffImagePlugin.py
+++ b/src/PIL/TiffImagePlugin.py
@@ -40,6 +40,7 @@
#
import io
import itertools
+import logging
import os
import struct
import warnings
@@ -51,7 +52,7 @@ from . import Image, ImageFile, ImagePalette, TiffTags
from ._binary import i8, o8
from .TiffTags import TYPES
-DEBUG = False # Needs to be merged with the new logging approach.
+logger = logging.getLogger(__name__)
# Set these to true to force use of libtiff for reading or writing.
READ_LIBTIFF = False
@@ -734,29 +735,21 @@ class ImageFileDirectory_v2(MutableMapping):
try:
for i in range(self._unpack("H", self._ensure_read(fp, 2))[0]):
tag, typ, count, data = self._unpack("HHL4s", self._ensure_read(fp, 12))
- if DEBUG:
- tagname = TiffTags.lookup(tag).name
- typname = TYPES.get(typ, "unknown")
- print(
- "tag: %s (%d) - type: %s (%d)" % (tagname, tag, typname, typ),
- end=" ",
- )
+
+ tagname = TiffTags.lookup(tag).name
+ typname = TYPES.get(typ, "unknown")
+ msg = "tag: %s (%d) - type: %s (%d)" % (tagname, tag, typname, typ)
try:
unit_size, handler = self._load_dispatch[typ]
except KeyError:
- if DEBUG:
- print("- unsupported type", typ)
+ logger.debug(msg + " - unsupported type {}".format(typ))
continue # ignore unsupported type
size = count * unit_size
if size > 4:
here = fp.tell()
(offset,) = self._unpack("L", data)
- if DEBUG:
- print(
- "Tag Location: {} - Data Location: {}".format(here, offset),
- end=" ",
- )
+ msg += " Tag Location: {} - Data Location: {}".format(here, offset)
fp.seek(offset)
data = ImageFile._safe_read(fp, size)
fp.seek(here)
@@ -769,19 +762,20 @@ class ImageFileDirectory_v2(MutableMapping):
"Expecting to read %d bytes but only got %d."
" Skipping tag %s" % (size, len(data), tag)
)
+ logger.debug(msg)
continue
if not data:
+ logger.debug(msg)
continue
self._tagdata[tag] = data
self.tagtype[tag] = typ
- if DEBUG:
- if size > 32:
- print("- value: " % size)
- else:
- print("- value:", self[tag])
+ msg += " - value: " + (
+ "" % size if size > 32 else str(data)
+ )
+ logger.debug(msg)
(self.next,) = self._unpack("L", self._ensure_read(fp, 4))
except OSError as msg:
@@ -802,21 +796,17 @@ class ImageFileDirectory_v2(MutableMapping):
if tag == STRIPOFFSETS:
stripoffsets = len(entries)
typ = self.tagtype.get(tag)
- if DEBUG:
- print("Tag {}, Type: {}, Value: {}".format(tag, typ, value))
+ logger.debug("Tag {}, Type: {}, Value: {}".format(tag, typ, value))
values = value if isinstance(value, tuple) else (value,)
data = self._write_dispatch[typ](self, *values)
- if DEBUG:
- tagname = TiffTags.lookup(tag).name
- typname = TYPES.get(typ, "unknown")
- print(
- "save: %s (%d) - type: %s (%d)" % (tagname, tag, typname, typ),
- end=" ",
- )
- if len(data) >= 16:
- print("- value: " % len(data))
- else:
- print("- value:", values)
+
+ tagname = TiffTags.lookup(tag).name
+ typname = TYPES.get(typ, "unknown")
+ msg = "save: %s (%d) - type: %s (%d)" % (tagname, tag, typname, typ)
+ msg += " - value: " + (
+ "" % len(data) if len(data) >= 16 else str(values)
+ )
+ logger.debug(msg)
# count is sum of lengths for string and arbitrary data
if typ in [TiffTags.BYTE, TiffTags.ASCII, TiffTags.UNDEFINED]:
@@ -840,8 +830,9 @@ class ImageFileDirectory_v2(MutableMapping):
# pass 2: write entries to file
for tag, typ, count, value, data in entries:
- if DEBUG:
- print(tag, typ, count, repr(value), repr(data))
+ logger.debug(
+ "{} {} {} {} {}".format(tag, typ, count, repr(value), repr(data))
+ )
result += self._pack("HHL4s", tag, typ, count, value)
# -- overwrite here for multi-page --
@@ -997,10 +988,9 @@ class TiffImageFile(ImageFile.ImageFile):
self._frame_pos = []
self._n_frames = None
- if DEBUG:
- print("*** TiffImageFile._open ***")
- print("- __first:", self.__first)
- print("- ifh: ", ifh)
+ logger.debug("*** TiffImageFile._open ***")
+ logger.debug("- __first: {}".format(self.__first))
+ logger.debug("- ifh: {}".format(ifh))
# and load the first frame
self._seek(0)
@@ -1015,10 +1005,6 @@ class TiffImageFile(ImageFile.ImageFile):
self.seek(current)
return self._n_frames
- @property
- def is_animated(self):
- return self._is_animated
-
def seek(self, frame):
"""Select a given frame as current image"""
if not self._seek_check(frame):
@@ -1035,24 +1021,22 @@ class TiffImageFile(ImageFile.ImageFile):
while len(self._frame_pos) <= frame:
if not self.__next:
raise EOFError("no more images in TIFF file")
- if DEBUG:
- print(
- "Seeking to frame %s, on frame %s, __next %s, location: %s"
- % (frame, self.__frame, self.__next, self.fp.tell())
- )
+ logger.debug(
+ "Seeking to frame %s, on frame %s, __next %s, location: %s"
+ % (frame, self.__frame, self.__next, self.fp.tell())
+ )
# reset buffered io handle in case fp
# was passed to libtiff, invalidating the buffer
self.fp.tell()
self.fp.seek(self.__next)
self._frame_pos.append(self.__next)
- if DEBUG:
- print("Loading tags, location: %s" % self.fp.tell())
+ logger.debug("Loading tags, location: %s" % self.fp.tell())
self.tag_v2.load(self.fp)
self.__next = self.tag_v2.next
if self.__next == 0:
self._n_frames = frame + 1
if len(self._frame_pos) == 1:
- self._is_animated = self.__next != 0
+ self.is_animated = self.__next != 0
self.__frame += 1
self.fp.seek(self._frame_pos[frame])
self.tag_v2.load(self.fp)
@@ -1066,7 +1050,7 @@ class TiffImageFile(ImageFile.ImageFile):
return self.__frame
def load(self):
- if self.use_load_libtiff:
+ if self.tile and self.use_load_libtiff:
return self._load_libtiff()
return super().load()
@@ -1087,19 +1071,14 @@ class TiffImageFile(ImageFile.ImageFile):
# allow closing if we're on the first frame, there's no next
# This is the ImageFile.load path only, libtiff specific below.
- if not self._is_animated:
+ if not self.is_animated:
self._close_exclusive_fp_after_loading = True
def _load_libtiff(self):
""" Overload method triggered when we detect a compressed tiff
Calls out to libtiff """
- pixel = Image.Image.load(self)
-
- if self.tile is None:
- raise OSError("cannot load this image")
- if not self.tile:
- return pixel
+ Image.Image.load(self)
self.load_prepare()
@@ -1123,7 +1102,7 @@ class TiffImageFile(ImageFile.ImageFile):
if hasattr(self.fp, "flush"):
self.fp.flush()
except OSError:
- # io.BytesIO have a fileno, but returns an IOError if
+ # io.BytesIO have a fileno, but returns an OSError if
# it doesn't use a file descriptor.
fp = False
@@ -1138,7 +1117,7 @@ class TiffImageFile(ImageFile.ImageFile):
except ValueError:
raise OSError("Couldn't set the image")
- close_self_fp = self._exclusive_fp and not self._is_animated
+ close_self_fp = self._exclusive_fp and not self.is_animated
if hasattr(self.fp, "getvalue"):
# We've got a stringio like thing passed in. Yay for all in memory.
# The decoder needs the entire file in one shot, so there's not
@@ -1147,23 +1126,20 @@ class TiffImageFile(ImageFile.ImageFile):
# underlying string for stringio.
#
# Rearranging for supporting byteio items, since they have a fileno
- # that returns an IOError if there's no underlying fp. Easier to
+ # that returns an OSError if there's no underlying fp. Easier to
# deal with here by reordering.
- if DEBUG:
- print("have getvalue. just sending in a string from getvalue")
+ logger.debug("have getvalue. just sending in a string from getvalue")
n, err = decoder.decode(self.fp.getvalue())
elif fp:
# we've got a actual file on disk, pass in the fp.
- if DEBUG:
- print("have fileno, calling fileno version of the decoder.")
+ logger.debug("have fileno, calling fileno version of the decoder.")
if not close_self_fp:
self.fp.seek(0)
# 4 bytes, otherwise the trace might error out
n, err = decoder.decode(b"fpfp")
else:
# we have something else.
- if DEBUG:
- print("don't have fileno or getvalue. just reading")
+ logger.debug("don't have fileno or getvalue. just reading")
self.fp.seek(0)
# UNDONE -- so much for that buffer size thing.
n, err = decoder.decode(self.fp.read())
@@ -1203,21 +1179,19 @@ class TiffImageFile(ImageFile.ImageFile):
fillorder = self.tag_v2.get(FILLORDER, 1)
- if DEBUG:
- print("*** Summary ***")
- print("- compression:", self._compression)
- print("- photometric_interpretation:", photo)
- print("- planar_configuration:", self._planar_configuration)
- print("- fill_order:", fillorder)
- print("- YCbCr subsampling:", self.tag.get(530))
+ logger.debug("*** Summary ***")
+ logger.debug("- compression: {}".format(self._compression))
+ logger.debug("- photometric_interpretation: {}".format(photo))
+ logger.debug("- planar_configuration: {}".format(self._planar_configuration))
+ logger.debug("- fill_order: {}".format(fillorder))
+ logger.debug("- YCbCr subsampling: {}".format(self.tag.get(530)))
# size
xsize = int(self.tag_v2.get(IMAGEWIDTH))
ysize = int(self.tag_v2.get(IMAGELENGTH))
self._size = xsize, ysize
- if DEBUG:
- print("- size:", self.size)
+ logger.debug("- size: {}".format(self.size))
sampleFormat = self.tag_v2.get(SAMPLEFORMAT, (1,))
if len(sampleFormat) > 1 and max(sampleFormat) == min(sampleFormat) == 1:
@@ -1251,18 +1225,15 @@ class TiffImageFile(ImageFile.ImageFile):
bps_tuple,
extra_tuple,
)
- if DEBUG:
- print("format key:", key)
+ logger.debug("format key: {}".format(key))
try:
self.mode, rawmode = OPEN_INFO[key]
except KeyError:
- if DEBUG:
- print("- unsupported format")
+ logger.debug("- unsupported format")
raise SyntaxError("unknown pixel mode")
- if DEBUG:
- print("- raw mode:", rawmode)
- print("- pil mode:", self.mode)
+ logger.debug("- raw mode: {}".format(rawmode))
+ logger.debug("- pil mode: {}".format(self.mode))
self.info["compression"] = self._compression
@@ -1303,8 +1274,7 @@ class TiffImageFile(ImageFile.ImageFile):
if fillorder == 2:
# Replace fillorder with fillorder=1
key = key[:3] + (1,) + key[4:]
- if DEBUG:
- print("format key:", key)
+ logger.debug("format key: {}".format(key))
# this should always work, since all the
# fillorder==2 modes have a corresponding
# fillorder=1 mode
@@ -1366,8 +1336,7 @@ class TiffImageFile(ImageFile.ImageFile):
x = y = 0
layer += 1
else:
- if DEBUG:
- print("- unsupported data organization")
+ logger.debug("- unsupported data organization")
raise SyntaxError("unknown data organization")
# Fix up info.
@@ -1447,8 +1416,7 @@ def _save(im, fp, filename):
# write any arbitrary tags passed in as an ImageFileDirectory
info = im.encoderinfo.get("tiffinfo", {})
- if DEBUG:
- print("Tiffinfo Keys: %s" % list(info))
+ logger.debug("Tiffinfo Keys: %s" % list(info))
if isinstance(info, ImageFileDirectory_v1):
info = info.to_v2()
for key in info:
@@ -1533,9 +1501,8 @@ def _save(im, fp, filename):
)
ifd[JPEGQUALITY] = quality
- if DEBUG:
- print("Saving using libtiff encoder")
- print("Items: %s" % sorted(ifd.items()))
+ logger.debug("Saving using libtiff encoder")
+ logger.debug("Items: %s" % sorted(ifd.items()))
_fp = 0
if hasattr(fp, "fileno"):
try:
@@ -1597,8 +1564,7 @@ def _save(im, fp, filename):
else:
atts[tag] = value
- if DEBUG:
- print("Converted items: %s" % sorted(atts.items()))
+ logger.debug("Converted items: %s" % sorted(atts.items()))
# libtiff always expects the bytes in native order.
# we're storing image byte order. So, if the rawmode
diff --git a/src/PIL/WebPImagePlugin.py b/src/PIL/WebPImagePlugin.py
index eda685508..3b9fe8f75 100644
--- a/src/PIL/WebPImagePlugin.py
+++ b/src/PIL/WebPImagePlugin.py
@@ -38,6 +38,8 @@ class WebPImageFile(ImageFile.ImageFile):
format = "WEBP"
format_description = "WebP image"
+ __loaded = 0
+ __logical_frame = 0
def _open(self):
if not _webp.HAVE_WEBPANIM:
@@ -52,7 +54,8 @@ class WebPImageFile(ImageFile.ImageFile):
self._size = width, height
self.fp = BytesIO(data)
self.tile = [("raw", (0, 0) + self.size, 0, self.mode)]
- self._n_frames = 1
+ self.n_frames = 1
+ self.is_animated = False
return
# Use the newer AnimDecoder API to parse the (possibly) animated file,
@@ -70,7 +73,8 @@ class WebPImageFile(ImageFile.ImageFile):
bgcolor & 0xFF,
)
self.info["background"] = (bg_r, bg_g, bg_b, bg_a)
- self._n_frames = frame_count
+ self.n_frames = frame_count
+ self.is_animated = self.n_frames > 1
self.mode = "RGB" if mode == "RGBX" else mode
self.rawmode = mode
self.tile = []
@@ -88,30 +92,15 @@ class WebPImageFile(ImageFile.ImageFile):
# Initialize seek state
self._reset(reset=False)
- self.seek(0)
def _getexif(self):
if "exif" not in self.info:
return None
return dict(self.getexif())
- @property
- def n_frames(self):
- return self._n_frames
-
- @property
- def is_animated(self):
- return self._n_frames > 1
-
def seek(self, frame):
- if not _webp.HAVE_WEBPANIM:
- return super().seek(frame)
-
- # Perform some simple checks first
- if frame >= self._n_frames:
- raise EOFError("attempted to seek beyond end of sequence")
- if frame < 0:
- raise EOFError("negative frame index is not valid")
+ if not self._seek_check(frame):
+ return
# Set logical frame to requested position
self.__logical_frame = frame
diff --git a/src/PIL/__init__.py b/src/PIL/__init__.py
index f9cb15772..81b87e012 100644
--- a/src/PIL/__init__.py
+++ b/src/PIL/__init__.py
@@ -131,5 +131,5 @@ _plugins = [
]
-class UnidentifiedImageError(IOError):
+class UnidentifiedImageError(OSError):
pass
diff --git a/src/PIL/features.py b/src/PIL/features.py
index ac06c0f71..33e89cf24 100644
--- a/src/PIL/features.py
+++ b/src/PIL/features.py
@@ -17,6 +17,13 @@ modules = {
def check_module(feature):
+ """
+ Checks if a module is available.
+
+ :param feature: The module to check for.
+ :returns: ``True`` if available, ``False`` otherwise.
+ :raises ValueError: If the module is not defined in this version of Pillow.
+ """
if not (feature in modules):
raise ValueError("Unknown module %s" % feature)
@@ -30,6 +37,9 @@ def check_module(feature):
def get_supported_modules():
+ """
+ :returns: A list of all supported modules.
+ """
return [f for f in modules if check_module(f)]
@@ -37,6 +47,13 @@ codecs = {"jpg": "jpeg", "jpg_2000": "jpeg2k", "zlib": "zip", "libtiff": "libtif
def check_codec(feature):
+ """
+ Checks if a codec is available.
+
+ :param feature: The codec to check for.
+ :returns: ``True`` if available, ``False`` otherwise.
+ :raises ValueError: If the codec is not defined in this version of Pillow.
+ """
if feature not in codecs:
raise ValueError("Unknown codec %s" % feature)
@@ -46,6 +63,9 @@ def check_codec(feature):
def get_supported_codecs():
+ """
+ :returns: A list of all supported codecs.
+ """
return [f for f in codecs if check_codec(f)]
@@ -61,6 +81,13 @@ features = {
def check_feature(feature):
+ """
+ Checks if a feature is available.
+
+ :param feature: The feature to check for.
+ :returns: ``True`` if available, ``False`` if unavailable, ``None`` if unknown.
+ :raises ValueError: If the feature is not defined in this version of Pillow.
+ """
if feature not in features:
raise ValueError("Unknown feature %s" % feature)
@@ -74,10 +101,20 @@ def check_feature(feature):
def get_supported_features():
+ """
+ :returns: A list of all supported features.
+ """
return [f for f in features if check_feature(f)]
def check(feature):
+ """
+ :param feature: A module, feature, or codec name.
+ :returns:
+ ``True`` if the module, feature, or codec is available,
+ ``False`` or ``None`` otherwise.
+ """
+
if feature in modules:
return check_module(feature)
if feature in codecs:
@@ -89,6 +126,10 @@ def check(feature):
def get_supported():
+ """
+ :returns: A list of all supported modules, features, and codecs.
+ """
+
ret = get_supported_modules()
ret.extend(get_supported_features())
ret.extend(get_supported_codecs())
@@ -96,6 +137,16 @@ def get_supported():
def pilinfo(out=None, supported_formats=True):
+ """
+ Prints information about this installation of Pillow.
+ This function can be called with ``python -m PIL``.
+
+ :param out:
+ The output stream to print to. Defaults to ``sys.stdout`` if ``None``.
+ :param supported_formats:
+ If ``True``, a list of all supported image file formats will be printed.
+ """
+
if out is None:
out = sys.stdout
diff --git a/src/Tk/tkImaging.c b/src/Tk/tkImaging.c
index 59801f58e..161a835fb 100644
--- a/src/Tk/tkImaging.c
+++ b/src/Tk/tkImaging.c
@@ -68,8 +68,9 @@ ImagingFind(const char* name)
#else
id = atol(name);
#endif
- if (!id)
+ if (!id) {
return NULL;
+ }
return (Imaging) id;
}
@@ -119,10 +120,11 @@ PyImagingPhotoPut(ClientData clientdata, Tcl_Interp* interp,
block.offset[0] = 0;
block.offset[1] = 1;
block.offset[2] = 2;
- if (strcmp(im->mode, "RGBA") == 0)
+ if (strcmp(im->mode, "RGBA") == 0) {
block.offset[3] = 3; /* alpha (or reserved, under 8.2) */
- else
+ } else {
block.offset[3] = 0; /* no alpha */
+ }
} else {
TCL_APPEND_RESULT(interp, "Bad mode", (char*) NULL);
return TCL_ERROR;
@@ -136,10 +138,11 @@ PyImagingPhotoPut(ClientData clientdata, Tcl_Interp* interp,
if (TK_LT_85) { /* Tk 8.4 */
TK_PHOTO_PUT_BLOCK_84(photo, &block, 0, 0, block.width, block.height,
TK_PHOTO_COMPOSITE_SET);
- if (strcmp(im->mode, "RGBA") == 0)
+ if (strcmp(im->mode, "RGBA") == 0) {
/* Tk workaround: we need apply ToggleComplexAlphaIfNeeded */
/* (fixed in Tk 8.5a3) */
TK_PHOTO_SET_SIZE_84(photo, block.width, block.height);
+ }
} else {
/* Tk >=8.5 */
TK_PHOTO_PUT_BLOCK_85(interp, photo, &block, 0, 0, block.width,
diff --git a/src/_imaging.c b/src/_imaging.c
index 0c3d766f3..40bfbf2fe 100644
--- a/src/_imaging.c
+++ b/src/_imaging.c
@@ -170,8 +170,9 @@ PyImagingNew(Imaging imOut)
{
ImagingObject* imagep;
- if (!imOut)
+ if (!imOut) {
return NULL;
+ }
imagep = PyObject_New(ImagingObject, &Imaging_Type);
if (imagep == NULL) {
@@ -197,8 +198,9 @@ _dealloc(ImagingObject* imagep)
printf("imaging %p deleted\n", imagep);
#endif
- if (imagep->access)
+ if (imagep->access) {
ImagingAccessDelete(imagep->image, imagep->access);
+ }
ImagingDelete(imagep->image);
PyObject_Del(imagep);
}
@@ -268,9 +270,9 @@ static const char* readonly = "image is readonly";
/* static const char* no_content = "image has no content"; */
void *
-ImagingError_IOError(void)
+ImagingError_OSError(void)
{
- PyErr_SetString(PyExc_IOError, "error when accessing file");
+ PyErr_SetString(PyExc_OSError, "error when accessing file");
return NULL;
}
@@ -322,8 +324,9 @@ getbands(const char* mode)
/* FIXME: add primitive to libImaging to avoid extra allocation */
im = ImagingNew(mode, 0, 0);
- if (!im)
+ if (!im) {
return -1;
+ }
bands = im->bands;
@@ -373,8 +376,9 @@ getlist(PyObject* arg, Py_ssize_t* length, const char* wrong_length, int type)
/* malloc check ok, type & ff is just a sizeof(something)
calloc checks for overflow */
list = calloc(n, type & 0xff);
- if ( ! list)
+ if ( ! list) {
return PyErr_NoMemory();
+ }
seq = PySequence_Fast(arg, must_be_sequence);
if ( ! seq) {
@@ -413,8 +417,9 @@ getlist(PyObject* arg, Py_ssize_t* length, const char* wrong_length, int type)
return NULL;
}
- if (length)
+ if (length) {
*length = n;
+ }
return list;
}
@@ -485,8 +490,9 @@ getpixel(Imaging im, ImagingAccess access, int x, int y)
case IMAGING_TYPE_FLOAT32:
return PyFloat_FromDouble(pixel.f);
case IMAGING_TYPE_SPECIAL:
- if (strncmp(im->mode, "I;16", 4) == 0)
+ if (strncmp(im->mode, "I;16", 4) == 0) {
return PyLong_FromLong(pixel.h);
+ }
break;
}
@@ -546,12 +552,14 @@ getink(PyObject* color, Imaging im, char* ink)
r = (UINT8) r;
} else {
if (im->bands == 2) {
- if (!PyArg_ParseTuple(color, "L|i", &r, &a))
+ if (!PyArg_ParseTuple(color, "L|i", &r, &a)) {
return NULL;
+ }
g = b = r;
} else {
- if (!PyArg_ParseTuple(color, "Lii|i", &r, &g, &b, &a))
+ if (!PyArg_ParseTuple(color, "Lii|i", &r, &g, &b, &a)) {
return NULL;
+ }
}
}
ink[0] = (char) CLIP8(r);
@@ -562,23 +570,26 @@ getink(PyObject* color, Imaging im, char* ink)
return ink;
case IMAGING_TYPE_INT32:
/* signed integer */
- if (rIsInt != 1)
+ if (rIsInt != 1) {
return NULL;
+ }
itmp = r;
memcpy(ink, &itmp, sizeof(itmp));
return ink;
case IMAGING_TYPE_FLOAT32:
/* floating point */
f = PyFloat_AsDouble(color);
- if (f == -1.0 && PyErr_Occurred())
+ if (f == -1.0 && PyErr_Occurred()) {
return NULL;
+ }
ftmp = f;
memcpy(ink, &ftmp, sizeof(ftmp));
return ink;
case IMAGING_TYPE_SPECIAL:
if (strncmp(im->mode, "I;16", 4) == 0) {
- if (rIsInt != 1)
+ if (rIsInt != 1) {
return NULL;
+ }
ink[0] = (UINT8) r;
ink[1] = (UINT8) (r >> 8);
ink[2] = ink[3] = 0;
@@ -606,12 +617,14 @@ _fill(PyObject* self, PyObject* args)
xsize = ysize = 256;
color = NULL;
- if (!PyArg_ParseTuple(args, "s|(ii)O", &mode, &xsize, &ysize, &color))
+ if (!PyArg_ParseTuple(args, "s|(ii)O", &mode, &xsize, &ysize, &color)) {
return NULL;
+ }
im = ImagingNewDirty(mode, xsize, ysize);
- if (!im)
+ if (!im) {
return NULL;
+ }
buffer[0] = buffer[1] = buffer[2] = buffer[3] = 0;
if (color) {
@@ -633,8 +646,9 @@ _new(PyObject* self, PyObject* args)
char* mode;
int xsize, ysize;
- if (!PyArg_ParseTuple(args, "s(ii)", &mode, &xsize, &ysize))
+ if (!PyArg_ParseTuple(args, "s(ii)", &mode, &xsize, &ysize)) {
return NULL;
+ }
return PyImagingNew(ImagingNew(mode, xsize, ysize));
}
@@ -645,8 +659,9 @@ _new_block(PyObject* self, PyObject* args)
char* mode;
int xsize, ysize;
- if (!PyArg_ParseTuple(args, "s(ii)", &mode, &xsize, &ysize))
+ if (!PyArg_ParseTuple(args, "s(ii)", &mode, &xsize, &ysize)) {
return NULL;
+ }
return PyImagingNew(ImagingNewBlock(mode, xsize, ysize));
}
@@ -656,8 +671,9 @@ _linear_gradient(PyObject* self, PyObject* args)
{
char* mode;
- if (!PyArg_ParseTuple(args, "s", &mode))
+ if (!PyArg_ParseTuple(args, "s", &mode)) {
return NULL;
+ }
return PyImagingNew(ImagingFillLinearGradient(mode));
}
@@ -667,8 +683,9 @@ _radial_gradient(PyObject* self, PyObject* args)
{
char* mode;
- if (!PyArg_ParseTuple(args, "s", &mode))
+ if (!PyArg_ParseTuple(args, "s", &mode)) {
return NULL;
+ }
return PyImagingNew(ImagingFillRadialGradient(mode));
}
@@ -681,8 +698,9 @@ _alpha_composite(ImagingObject* self, PyObject* args)
if (!PyArg_ParseTuple(args, "O!O!",
&Imaging_Type, &imagep1,
- &Imaging_Type, &imagep2))
+ &Imaging_Type, &imagep2)) {
return NULL;
+ }
return PyImagingNew(ImagingAlphaComposite(imagep1->image, imagep2->image));
}
@@ -698,8 +716,9 @@ _blend(ImagingObject* self, PyObject* args)
if (!PyArg_ParseTuple(args, "O!O!|d",
&Imaging_Type, &imagep1,
&Imaging_Type, &imagep2,
- &alpha))
+ &alpha)) {
return NULL;
+ }
return PyImagingNew(ImagingBlend(imagep1->image, imagep2->image,
(float) alpha));
@@ -762,8 +781,9 @@ _prepare_lut_table(PyObject* table, Py_ssize_t table_size)
/* malloc check ok, max is 2 * 4 * 65**3 = 2197000 */
prepared = (INT16*) malloc(sizeof(INT16) * table_size);
if ( ! prepared) {
- if (free_table_data)
+ if (free_table_data) {
free(table_data);
+ }
return (INT16*) PyErr_NoMemory();
}
@@ -880,8 +900,9 @@ _convert(ImagingObject* self, PyObject* args)
int dither = 0;
ImagingObject *paletteimage = NULL;
- if (!PyArg_ParseTuple(args, "s|iO", &mode, &dither, &paletteimage))
+ if (!PyArg_ParseTuple(args, "s|iO", &mode, &dither, &paletteimage)) {
return NULL;
+ }
if (paletteimage != NULL) {
if (!PyImaging_Check(paletteimage)) {
PyObject_Print((PyObject *)paletteimage, stderr, 0);
@@ -904,11 +925,13 @@ _convert2(ImagingObject* self, PyObject* args)
ImagingObject* imagep2;
if (!PyArg_ParseTuple(args, "O!O!",
&Imaging_Type, &imagep1,
- &Imaging_Type, &imagep2))
+ &Imaging_Type, &imagep2)) {
return NULL;
+ }
- if (!ImagingConvert2(imagep1->image, imagep2->image))
+ if (!ImagingConvert2(imagep1->image, imagep2->image)) {
return NULL;
+ }
Py_INCREF(Py_None);
return Py_None;
@@ -950,8 +973,9 @@ _convert_transparent(ImagingObject* self, PyObject* args)
static PyObject*
_copy(ImagingObject* self, PyObject* args)
{
- if (!PyArg_ParseTuple(args, ""))
+ if (!PyArg_ParseTuple(args, "")) {
return NULL;
+ }
return PyImagingNew(ImagingCopy(self->image));
}
@@ -960,8 +984,9 @@ static PyObject*
_crop(ImagingObject* self, PyObject* args)
{
int x0, y0, x1, y1;
- if (!PyArg_ParseTuple(args, "(iiii)", &x0, &y0, &x1, &y1))
+ if (!PyArg_ParseTuple(args, "(iiii)", &x0, &y0, &x1, &y1)) {
return NULL;
+ }
return PyImagingNew(ImagingCrop(self->image, x0, y0, x1, y1));
}
@@ -971,8 +996,9 @@ _expand_image(ImagingObject* self, PyObject* args)
{
int x, y;
int mode = 0;
- if (!PyArg_ParseTuple(args, "ii|i", &x, &y, &mode))
+ if (!PyArg_ParseTuple(args, "ii|i", &x, &y, &mode)) {
return NULL;
+ }
return PyImagingNew(ImagingExpand(self->image, x, y, mode));
}
@@ -988,13 +1014,15 @@ _filter(ImagingObject* self, PyObject* args)
float divisor, offset;
PyObject* kernel = NULL;
if (!PyArg_ParseTuple(args, "(ii)ffO", &xsize, &ysize,
- &divisor, &offset, &kernel))
+ &divisor, &offset, &kernel)) {
return NULL;
+ }
/* get user-defined kernel */
kerneldata = getlist(kernel, &kernelsize, NULL, TYPE_FLOAT32);
- if (!kerneldata)
+ if (!kerneldata) {
return NULL;
+ }
if (kernelsize != (Py_ssize_t) xsize * (Py_ssize_t) ysize) {
free(kerneldata);
return ImagingError_ValueError("bad kernel size");
@@ -1022,13 +1050,15 @@ _gaussian_blur(ImagingObject* self, PyObject* args)
float radius = 0;
int passes = 3;
- if (!PyArg_ParseTuple(args, "f|i", &radius, &passes))
+ if (!PyArg_ParseTuple(args, "f|i", &radius, &passes)) {
return NULL;
+ }
imIn = self->image;
imOut = ImagingNewDirty(imIn->mode, imIn->xsize, imIn->ysize);
- if (!imOut)
+ if (!imOut) {
return NULL;
+ }
if (!ImagingGaussianBlur(imOut, imIn, radius, passes)) {
ImagingDelete(imOut);
@@ -1049,8 +1079,9 @@ _getpalette(ImagingObject* self, PyObject* args)
char* mode = "RGB";
char* rawmode = "RGB";
- if (!PyArg_ParseTuple(args, "|ss", &mode, &rawmode))
+ if (!PyArg_ParseTuple(args, "|ss", &mode, &rawmode)) {
return NULL;
+ }
if (!self->image->palette) {
PyErr_SetString(PyExc_ValueError, no_palette);
@@ -1064,8 +1095,9 @@ _getpalette(ImagingObject* self, PyObject* args)
}
palette = PyBytes_FromStringAndSize(NULL, palettesize * bits / 8);
- if (!palette)
+ if (!palette) {
return NULL;
+ }
pack((UINT8*) PyBytes_AsString(palette),
self->image->palette->palette, palettesize);
@@ -1089,24 +1121,27 @@ _getxy(PyObject* xy, int* x, int *y)
{
PyObject* value;
- if (!PyTuple_Check(xy) || PyTuple_GET_SIZE(xy) != 2)
+ if (!PyTuple_Check(xy) || PyTuple_GET_SIZE(xy) != 2) {
goto badarg;
+ }
value = PyTuple_GET_ITEM(xy, 0);
- if (PyLong_Check(value))
+ if (PyLong_Check(value)) {
*x = PyLong_AS_LONG(value);
- else if (PyFloat_Check(value))
+ } else if (PyFloat_Check(value)) {
*x = (int) PyFloat_AS_DOUBLE(value);
- else
+ } else {
goto badval;
+ }
value = PyTuple_GET_ITEM(xy, 1);
- if (PyLong_Check(value))
+ if (PyLong_Check(value)) {
*y = PyLong_AS_LONG(value);
- else if (PyFloat_Check(value))
+ } else if (PyFloat_Check(value)) {
*y = (int) PyFloat_AS_DOUBLE(value);
- else
+ } else {
goto badval;
+ }
return 0;
@@ -1141,8 +1176,9 @@ _getpixel(ImagingObject* self, PyObject* args)
xy = PyTuple_GET_ITEM(args, 0);
- if (_getxy(xy, &x, &y))
+ if (_getxy(xy, &x, &y)) {
return NULL;
+ }
if (self->access == NULL) {
Py_INCREF(Py_None);
@@ -1168,20 +1204,23 @@ parse_histogram_extremap(ImagingObject* self, PyObject* extremap,
if (extremap) {
switch (self->image->type) {
case IMAGING_TYPE_UINT8:
- if (!PyArg_ParseTuple(extremap, "ii", &i0, &i1))
+ if (!PyArg_ParseTuple(extremap, "ii", &i0, &i1)) {
return NULL;
+ }
ep->u[0] = CLIP8(i0);
ep->u[1] = CLIP8(i1);
break;
case IMAGING_TYPE_INT32:
- if (!PyArg_ParseTuple(extremap, "ii", &i0, &i1))
+ if (!PyArg_ParseTuple(extremap, "ii", &i0, &i1)) {
return NULL;
+ }
ep->i[0] = i0;
ep->i[1] = i1;
break;
case IMAGING_TYPE_FLOAT32:
- if (!PyArg_ParseTuple(extremap, "dd", &f0, &f1))
+ if (!PyArg_ParseTuple(extremap, "dd", &f0, &f1)) {
return NULL;
+ }
ep->f[0] = (FLOAT32) f0;
ep->f[1] = (FLOAT32) f1;
break;
@@ -1205,15 +1244,17 @@ _histogram(ImagingObject* self, PyObject* args)
PyObject* extremap = NULL;
ImagingObject* maskp = NULL;
- if (!PyArg_ParseTuple(args, "|OO!", &extremap, &Imaging_Type, &maskp))
+ if (!PyArg_ParseTuple(args, "|OO!", &extremap, &Imaging_Type, &maskp)) {
return NULL;
+ }
/* Using a var to avoid allocations. */
ep = parse_histogram_extremap(self, extremap, &extrema);
h = ImagingGetHistogram(self->image, (maskp) ? maskp->image : NULL, ep);
- if (!h)
+ if (!h) {
return NULL;
+ }
/* Build an integer list containing the histogram */
list = PyList_New(h->bands * 256);
@@ -1246,15 +1287,17 @@ _entropy(ImagingObject* self, PyObject* args)
PyObject* extremap = NULL;
ImagingObject* maskp = NULL;
- if (!PyArg_ParseTuple(args, "|OO!", &extremap, &Imaging_Type, &maskp))
+ if (!PyArg_ParseTuple(args, "|OO!", &extremap, &Imaging_Type, &maskp)) {
return NULL;
+ }
/* Using a local var to avoid allocations. */
ep = parse_histogram_extremap(self, extremap, &extrema);
h = ImagingGetHistogram(self->image, (maskp) ? maskp->image : NULL, ep);
- if (!h)
+ if (!h) {
return NULL;
+ }
/* Calculate the histogram entropy */
/* First, sum the histogram data */
@@ -1286,8 +1329,9 @@ static PyObject*
_modefilter(ImagingObject* self, PyObject* args)
{
int size;
- if (!PyArg_ParseTuple(args, "i", &size))
+ if (!PyArg_ParseTuple(args, "i", &size)) {
return NULL;
+ }
return PyImagingNew(ImagingModeFilter(self->image, size));
}
@@ -1297,8 +1341,9 @@ static PyObject*
_offset(ImagingObject* self, PyObject* args)
{
int xoffset, yoffset;
- if (!PyArg_ParseTuple(args, "ii", &xoffset, &yoffset))
+ if (!PyArg_ParseTuple(args, "ii", &xoffset, &yoffset)) {
return NULL;
+ }
return PyImagingNew(ImagingOffset(self->image, xoffset, yoffset));
}
@@ -1315,19 +1360,21 @@ _paste(ImagingObject* self, PyObject* args)
if (!PyArg_ParseTuple(args, "O(iiii)|O!",
&source,
&x0, &y0, &x1, &y1,
- &Imaging_Type, &maskp))
- return NULL;
+ &Imaging_Type, &maskp)) {
+ return NULL;
+ }
- if (PyImaging_Check(source))
+ if (PyImaging_Check(source)) {
status = ImagingPaste(
self->image, PyImaging_AsImaging(source),
(maskp) ? maskp->image : NULL,
x0, y0, x1, y1
);
- else {
- if (!getink(source, self->image, ink))
+ } else {
+ if (!getink(source, self->image, ink)) {
return NULL;
+ }
status = ImagingFill2(
self->image, ink,
(maskp) ? maskp->image : NULL,
@@ -1335,8 +1382,9 @@ _paste(ImagingObject* self, PyObject* args)
);
}
- if (status < 0)
+ if (status < 0) {
return NULL;
+ }
Py_INCREF(Py_None);
return Py_None;
@@ -1353,8 +1401,9 @@ _point(ImagingObject* self, PyObject* args)
PyObject* list;
char* mode;
- if (!PyArg_ParseTuple(args, "Oz", &list, &mode))
- return NULL;
+ if (!PyArg_ParseTuple(args, "Oz", &list, &mode)) {
+ return NULL;
+ }
if (mode && !strcmp(mode, "F")) {
FLOAT32* data;
@@ -1362,8 +1411,9 @@ _point(ImagingObject* self, PyObject* args)
/* map from 8-bit data to floating point */
n = 256;
data = getlist(list, &n, wrong_number, TYPE_FLOAT32);
- if (!data)
+ if (!data) {
return NULL;
+ }
im = ImagingPoint(self->image, mode, (void*) data);
free(data);
@@ -1374,8 +1424,9 @@ _point(ImagingObject* self, PyObject* args)
/* FIXME: support arbitrary number of entries (requires API change) */
n = 65536;
data = getlist(list, &n, wrong_number, TYPE_UINT8);
- if (!data)
+ if (!data) {
return NULL;
+ }
im = ImagingPoint(self->image, mode, (void*) data);
free(data);
@@ -1385,32 +1436,37 @@ _point(ImagingObject* self, PyObject* args)
if (mode) {
bands = getbands(mode);
- if (bands < 0)
+ if (bands < 0) {
return NULL;
- } else
+ }
+ } else {
bands = self->image->bands;
+ }
/* map to integer data */
n = 256 * bands;
data = getlist(list, &n, wrong_number, TYPE_INT32);
- if (!data)
+ if (!data) {
return NULL;
+ }
- if (mode && !strcmp(mode, "I"))
+ if (mode && !strcmp(mode, "I")) {
im = ImagingPoint(self->image, mode, (void*) data);
- else if (mode && bands > 1) {
+ } else if (mode && bands > 1) {
for (i = 0; i < 256; i++) {
lut[i*4] = CLIP8(data[i]);
lut[i*4+1] = CLIP8(data[i+256]);
lut[i*4+2] = CLIP8(data[i+512]);
- if (n > 768)
+ if (n > 768) {
lut[i*4+3] = CLIP8(data[i+768]);
+ }
}
im = ImagingPoint(self->image, mode, (void*) lut);
} else {
/* map individual bands */
- for (i = 0; i < n; i++)
+ for (i = 0; i < n; i++) {
lut[i] = CLIP8(data[i]);
+ }
im = ImagingPoint(self->image, mode, (void*) lut);
}
free(data);
@@ -1424,8 +1480,9 @@ _point_transform(ImagingObject* self, PyObject* args)
{
double scale = 1.0;
double offset = 0.0;
- if (!PyArg_ParseTuple(args, "|dd", &scale, &offset))
- return NULL;
+ if (!PyArg_ParseTuple(args, "|dd", &scale, &offset)) {
+ return NULL;
+ }
return PyImagingNew(ImagingPointTransform(self->image, scale, offset));
}
@@ -1443,8 +1500,9 @@ _putdata(ImagingObject* self, PyObject* args)
double scale = 1.0;
double offset = 0.0;
- if (!PyArg_ParseTuple(args, "O|dd", &data, &scale, &offset))
+ if (!PyArg_ParseTuple(args, "O|dd", &data, &scale, &offset)) {
return NULL;
+ }
if (!PySequence_Check(data)) {
PyErr_SetString(PyExc_TypeError, must_be_sequence);
@@ -1463,21 +1521,24 @@ _putdata(ImagingObject* self, PyObject* args)
if (PyBytes_Check(data)) {
unsigned char* p;
p = (unsigned char*) PyBytes_AS_STRING(data);
- if (scale == 1.0 && offset == 0.0)
+ if (scale == 1.0 && offset == 0.0) {
/* Plain string data */
for (i = y = 0; i < n; i += image->xsize, y++) {
x = n - i;
- if (x > (int) image->xsize)
+ if (x > (int) image->xsize) {
x = image->xsize;
+ }
memcpy(image->image8[y], p+i, x);
}
- else
+ } else {
/* Scaled and clipped string data */
for (i = x = y = 0; i < n; i++) {
image->image8[y][x] = CLIP8((int) (p[i] * scale + offset));
- if (++x >= (int) image->xsize)
+ if (++x >= (int) image->xsize) {
x = 0, y++;
+ }
}
+ }
} else {
seq = PySequence_Fast(data, must_be_sequence);
if (!seq) {
@@ -1576,8 +1637,9 @@ _quantize(ImagingObject* self, PyObject* args)
int colours = 256;
int method = 0;
int kmeans = 0;
- if (!PyArg_ParseTuple(args, "|iii", &colours, &method, &kmeans))
+ if (!PyArg_ParseTuple(args, "|iii", &colours, &method, &kmeans)) {
return NULL;
+ }
if (!self->image->xsize || !self->image->ysize) {
/* no content; return an empty image */
@@ -1599,8 +1661,9 @@ _putpalette(ImagingObject* self, PyObject* args)
char* rawmode;
UINT8* palette;
Py_ssize_t palettesize;
- if (!PyArg_ParseTuple(args, "sy#", &rawmode, &palette, &palettesize))
+ if (!PyArg_ParseTuple(args, "sy#", &rawmode, &palette, &palettesize)) {
return NULL;
+ }
if (strcmp(self->image->mode, "L") && strcmp(self->image->mode, "LA") &&
strcmp(self->image->mode, "P") && strcmp(self->image->mode, "PA")) {
@@ -1636,8 +1699,9 @@ _putpalettealpha(ImagingObject* self, PyObject* args)
{
int index;
int alpha = 0;
- if (!PyArg_ParseTuple(args, "i|i", &index, &alpha))
+ if (!PyArg_ParseTuple(args, "i|i", &index, &alpha)) {
return NULL;
+ }
if (!self->image->palette) {
PyErr_SetString(PyExc_ValueError, no_palette);
@@ -1662,8 +1726,9 @@ _putpalettealphas(ImagingObject* self, PyObject* args)
int i;
UINT8 *values;
Py_ssize_t length;
- if (!PyArg_ParseTuple(args, "y#", &values, &length))
+ if (!PyArg_ParseTuple(args, "y#", &values, &length)) {
return NULL;
+ }
if (!self->image->palette) {
PyErr_SetString(PyExc_ValueError, no_palette);
@@ -1692,8 +1757,9 @@ _putpixel(ImagingObject* self, PyObject* args)
int x, y;
PyObject* color;
- if (!PyArg_ParseTuple(args, "(ii)O", &x, &y, &color))
+ if (!PyArg_ParseTuple(args, "(ii)O", &x, &y, &color)) {
return NULL;
+ }
im = self->image;
@@ -1709,11 +1775,13 @@ _putpixel(ImagingObject* self, PyObject* args)
return NULL;
}
- if (!getink(color, im, ink))
+ if (!getink(color, im, ink)) {
return NULL;
+ }
- if (self->access)
+ if (self->access) {
self->access->put_pixel(im, x, y, ink);
+ }
Py_INCREF(Py_None);
return Py_None;
@@ -1724,8 +1792,9 @@ static PyObject*
_rankfilter(ImagingObject* self, PyObject* args)
{
int size, rank;
- if (!PyArg_ParseTuple(args, "ii", &size, &rank))
+ if (!PyArg_ParseTuple(args, "ii", &size, &rank)) {
return NULL;
+ }
return PyImagingNew(ImagingRankFilter(self->image, size, rank));
}
@@ -1746,8 +1815,9 @@ _resize(ImagingObject* self, PyObject* args)
box[3] = imIn->ysize;
if (!PyArg_ParseTuple(args, "(ii)|i(ffff)", &xsize, &ysize, &filter,
- &box[0], &box[1], &box[2], &box[3]))
+ &box[0], &box[1], &box[2], &box[3])) {
return NULL;
+ }
if (xsize < 1 || ysize < 1) {
return ImagingError_ValueError("height and width must be > 0");
@@ -1807,8 +1877,9 @@ _reduce(ImagingObject* self, PyObject* args)
box[3] = imIn->ysize;
if (!PyArg_ParseTuple(args, "(ii)|(iiii)", &xscale, &yscale,
- &box[0], &box[1], &box[2], &box[3]))
+ &box[0], &box[1], &box[2], &box[3])) {
return NULL;
+ }
if (xscale < 1 || yscale < 1) {
return ImagingError_ValueError("scale must be > 0");
@@ -1851,8 +1922,9 @@ im_setmode(ImagingObject* self, PyObject* args)
char* mode;
Py_ssize_t modelen;
- if (!PyArg_ParseTuple(args, "s#:setmode", &mode, &modelen))
+ if (!PyArg_ParseTuple(args, "s#:setmode", &mode, &modelen)) {
return NULL;
+ }
im = self->image;
@@ -1864,16 +1936,19 @@ im_setmode(ImagingObject* self, PyObject* args)
/* color to color */
strcpy(im->mode, mode);
im->bands = modelen;
- if (!strcmp(mode, "RGBA"))
+ if (!strcmp(mode, "RGBA")) {
(void) ImagingFillBand(im, 3, 255);
+ }
} else {
/* trying doing an in-place conversion */
- if (!ImagingConvertInPlace(im, mode))
+ if (!ImagingConvertInPlace(im, mode)) {
return NULL;
+ }
}
- if (self->access)
+ if (self->access) {
ImagingAccessDelete(im, self->access);
+ }
self->access = ImagingAccessNew(im);
Py_INCREF(Py_None);
@@ -1900,8 +1975,9 @@ _transform2(ImagingObject* self, PyObject* args)
&x0, &y0, &x1, &y1,
&Imaging_Type, &imagep,
&method, &data,
- &filter, &fill))
- return NULL;
+ &filter, &fill)) {
+ return NULL;
+ }
switch (method) {
case IMAGING_TRANSFORM_AFFINE:
@@ -1918,8 +1994,9 @@ _transform2(ImagingObject* self, PyObject* args)
}
a = getlist(data, &n, wrong_number, TYPE_DOUBLE);
- if (!a)
+ if (!a) {
return NULL;
+ }
imOut = ImagingTransform(
self->image, imagep->image, method,
@@ -1927,8 +2004,9 @@ _transform2(ImagingObject* self, PyObject* args)
free(a);
- if (!imOut)
+ if (!imOut) {
return NULL;
+ }
Py_INCREF(Py_None);
return Py_None;
@@ -1941,8 +2019,9 @@ _transpose(ImagingObject* self, PyObject* args)
Imaging imOut;
int op;
- if (!PyArg_ParseTuple(args, "i", &op))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i", &op)) {
+ return NULL;
+ }
imIn = self->image;
@@ -1963,7 +2042,7 @@ _transpose(ImagingObject* self, PyObject* args)
return NULL;
}
- if (imOut)
+ if (imOut) {
switch (op) {
case 0:
(void) ImagingFlipLeftRight(imOut, imIn);
@@ -1987,6 +2066,7 @@ _transpose(ImagingObject* self, PyObject* args)
(void) ImagingTransverse(imOut, imIn);
break;
}
+ }
return PyImagingNew(imOut);
}
@@ -2000,16 +2080,19 @@ _unsharp_mask(ImagingObject* self, PyObject* args)
float radius;
int percent, threshold;
- if (!PyArg_ParseTuple(args, "fii", &radius, &percent, &threshold))
+ if (!PyArg_ParseTuple(args, "fii", &radius, &percent, &threshold)) {
return NULL;
+ }
imIn = self->image;
imOut = ImagingNewDirty(imIn->mode, imIn->xsize, imIn->ysize);
- if (!imOut)
+ if (!imOut) {
return NULL;
+ }
- if (!ImagingUnsharpMask(imOut, imIn, radius, percent, threshold))
+ if (!ImagingUnsharpMask(imOut, imIn, radius, percent, threshold)) {
return NULL;
+ }
return PyImagingNew(imOut);
}
@@ -2023,13 +2106,15 @@ _box_blur(ImagingObject* self, PyObject* args)
float radius;
int n = 1;
- if (!PyArg_ParseTuple(args, "f|i", &radius, &n))
+ if (!PyArg_ParseTuple(args, "f|i", &radius, &n)) {
return NULL;
+ }
imIn = self->image;
imOut = ImagingNewDirty(imIn->mode, imIn->xsize, imIn->ysize);
- if (!imOut)
+ if (!imOut) {
return NULL;
+ }
if (!ImagingBoxBlur(imOut, imIn, radius, n)) {
ImagingDelete(imOut);
@@ -2067,12 +2152,14 @@ _getcolors(ImagingObject* self, PyObject* args)
PyObject* out;
int maxcolors = 256;
- if (!PyArg_ParseTuple(args, "i:getcolors", &maxcolors))
+ if (!PyArg_ParseTuple(args, "i:getcolors", &maxcolors)) {
return NULL;
+ }
items = ImagingGetColors(self->image, maxcolors, &colors);
- if (!items)
+ if (!items) {
return NULL;
+ }
if (colors > maxcolors) {
out = Py_None;
@@ -2105,10 +2192,11 @@ _getextrema(ImagingObject* self, PyObject* args)
int status;
status = ImagingGetExtrema(self->image, &extrema);
- if (status < 0)
+ if (status < 0) {
return NULL;
+ }
- if (status)
+ if (status) {
switch (self->image->type) {
case IMAGING_TYPE_UINT8:
return Py_BuildValue("BB", extrema.u[0], extrema.u[1]);
@@ -2121,6 +2209,7 @@ _getextrema(ImagingObject* self, PyObject* args)
return Py_BuildValue("HH", extrema.s[0], extrema.s[1]);
}
}
+ }
Py_INCREF(Py_None);
return Py_None;
@@ -2162,8 +2251,9 @@ _getband(ImagingObject* self, PyObject* args)
{
int band;
- if (!PyArg_ParseTuple(args, "i", &band))
+ if (!PyArg_ParseTuple(args, "i", &band)) {
return NULL;
+ }
return PyImagingNew(ImagingGetBand(self->image, band));
}
@@ -2174,11 +2264,13 @@ _fillband(ImagingObject* self, PyObject* args)
int band;
int color;
- if (!PyArg_ParseTuple(args, "ii", &band, &color))
+ if (!PyArg_ParseTuple(args, "ii", &band, &color)) {
return NULL;
+ }
- if (!ImagingFillBand(self->image, band, color))
+ if (!ImagingFillBand(self->image, band, color)) {
return NULL;
+ }
Py_INCREF(Py_None);
return Py_None;
@@ -2191,11 +2283,13 @@ _putband(ImagingObject* self, PyObject* args)
int band;
if (!PyArg_ParseTuple(args, "O!i",
&Imaging_Type, &imagep,
- &band))
+ &band)) {
return NULL;
+ }
- if (!ImagingPutBand(self->image, imagep->image, band))
+ if (!ImagingPutBand(self->image, imagep->image, band)) {
return NULL;
+ }
Py_INCREF(Py_None);
return Py_None;
@@ -2213,13 +2307,22 @@ _merge(PyObject* self, PyObject* args)
if (!PyArg_ParseTuple(args, "sO!|O!O!O!", &mode,
&Imaging_Type, &band0, &Imaging_Type, &band1,
- &Imaging_Type, &band2, &Imaging_Type, &band3))
+ &Imaging_Type, &band2, &Imaging_Type, &band3)) {
return NULL;
+ }
- if (band0) bands[0] = band0->image;
- if (band1) bands[1] = band1->image;
- if (band2) bands[2] = band2->image;
- if (band3) bands[3] = band3->image;
+ if (band0) {
+ bands[0] = band0->image;
+ }
+ if (band1) {
+ bands[1] = band1->image;
+ }
+ if (band2) {
+ bands[2] = band2->image;
+ }
+ if (band3) {
+ bands[3] = band3->image;
+ }
return PyImagingNew(ImagingMerge(mode, bands));
}
@@ -2233,14 +2336,16 @@ _split(ImagingObject* self, PyObject* args)
PyObject* imaging_object;
Imaging bands[4] = {NULL, NULL, NULL, NULL};
- if ( ! ImagingSplit(self->image, bands))
+ if ( ! ImagingSplit(self->image, bands)) {
return NULL;
+ }
list = PyTuple_New(self->image->bands);
for (i = 0; i < self->image->bands; i++) {
imaging_object = PyImagingNew(bands[i]);
- if ( ! imaging_object)
+ if ( ! imaging_object) {
fails += 1;
+ }
PyTuple_SET_ITEM(list, i, imaging_object);
}
if (fails) {
@@ -2265,8 +2370,9 @@ _chop_lighter(ImagingObject* self, PyObject* args)
{
ImagingObject* imagep;
- if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep))
+ if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
return NULL;
+ }
return PyImagingNew(ImagingChopLighter(self->image, imagep->image));
}
@@ -2276,8 +2382,9 @@ _chop_darker(ImagingObject* self, PyObject* args)
{
ImagingObject* imagep;
- if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep))
+ if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
return NULL;
+ }
return PyImagingNew(ImagingChopDarker(self->image, imagep->image));
}
@@ -2287,8 +2394,9 @@ _chop_difference(ImagingObject* self, PyObject* args)
{
ImagingObject* imagep;
- if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep))
+ if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
return NULL;
+ }
return PyImagingNew(ImagingChopDifference(self->image, imagep->image));
}
@@ -2298,8 +2406,9 @@ _chop_multiply(ImagingObject* self, PyObject* args)
{
ImagingObject* imagep;
- if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep))
+ if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
return NULL;
+ }
return PyImagingNew(ImagingChopMultiply(self->image, imagep->image));
}
@@ -2309,8 +2418,9 @@ _chop_screen(ImagingObject* self, PyObject* args)
{
ImagingObject* imagep;
- if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep))
+ if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
return NULL;
+ }
return PyImagingNew(ImagingChopScreen(self->image, imagep->image));
}
@@ -2326,8 +2436,9 @@ _chop_add(ImagingObject* self, PyObject* args)
offset = 0;
if (!PyArg_ParseTuple(args, "O!|fi", &Imaging_Type, &imagep,
- &scale, &offset))
+ &scale, &offset)) {
return NULL;
+ }
return PyImagingNew(ImagingChopAdd(self->image, imagep->image,
scale, offset));
@@ -2344,8 +2455,9 @@ _chop_subtract(ImagingObject* self, PyObject* args)
offset = 0;
if (!PyArg_ParseTuple(args, "O!|fi", &Imaging_Type, &imagep,
- &scale, &offset))
+ &scale, &offset)) {
return NULL;
+ }
return PyImagingNew(ImagingChopSubtract(self->image, imagep->image,
scale, offset));
@@ -2356,8 +2468,9 @@ _chop_and(ImagingObject* self, PyObject* args)
{
ImagingObject* imagep;
- if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep))
+ if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
return NULL;
+ }
return PyImagingNew(ImagingChopAnd(self->image, imagep->image));
}
@@ -2367,8 +2480,9 @@ _chop_or(ImagingObject* self, PyObject* args)
{
ImagingObject* imagep;
- if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep))
+ if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
return NULL;
+ }
return PyImagingNew(ImagingChopOr(self->image, imagep->image));
}
@@ -2378,8 +2492,9 @@ _chop_xor(ImagingObject* self, PyObject* args)
{
ImagingObject* imagep;
- if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep))
+ if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
return NULL;
+ }
return PyImagingNew(ImagingChopXor(self->image, imagep->image));
}
@@ -2389,8 +2504,9 @@ _chop_add_modulo(ImagingObject* self, PyObject* args)
{
ImagingObject* imagep;
- if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep))
+ if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
return NULL;
+ }
return PyImagingNew(ImagingChopAddModulo(self->image, imagep->image));
}
@@ -2400,8 +2516,9 @@ _chop_subtract_modulo(ImagingObject* self, PyObject* args)
{
ImagingObject* imagep;
- if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep))
+ if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
return NULL;
+ }
return PyImagingNew(ImagingChopSubtractModulo(self->image, imagep->image));
}
@@ -2411,8 +2528,9 @@ _chop_soft_light(ImagingObject* self, PyObject* args)
{
ImagingObject* imagep;
- if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep))
+ if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
return NULL;
+ }
return PyImagingNew(ImagingChopSoftLight(self->image, imagep->image));
}
@@ -2422,8 +2540,9 @@ _chop_hard_light(ImagingObject* self, PyObject* args)
{
ImagingObject* imagep;
- if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep))
+ if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
return NULL;
+ }
return PyImagingNew(ImagingChopHardLight(self->image, imagep->image));
}
@@ -2433,8 +2552,9 @@ _chop_overlay(ImagingObject* self, PyObject* args)
{
ImagingObject* imagep;
- if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep))
+ if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) {
return NULL;
+ }
return PyImagingNew(ImagingOverlay(self->image, imagep->image));
}
@@ -2457,8 +2577,9 @@ _font_new(PyObject* self_, PyObject* args)
Py_ssize_t glyphdata_length;
if (!PyArg_ParseTuple(args, "O!y#",
&Imaging_Type, &imagep,
- &glyphdata, &glyphdata_length))
+ &glyphdata, &glyphdata_length)) {
return NULL;
+ }
if (glyphdata_length != 256 * 20) {
PyErr_SetString(PyExc_ValueError, wrong_length);
@@ -2466,8 +2587,9 @@ _font_new(PyObject* self_, PyObject* args)
}
self = PyObject_New(ImagingFontObject, &ImagingFont_Type);
- if (self == NULL)
+ if (self == NULL) {
return NULL;
+ }
/* glyph bitmap */
self->bitmap = imagep->image;
@@ -2486,10 +2608,12 @@ _font_new(PyObject* self_, PyObject* args)
self->glyphs[i].sy0 = S16(B16(glyphdata, 14));
self->glyphs[i].sx1 = S16(B16(glyphdata, 16));
self->glyphs[i].sy1 = S16(B16(glyphdata, 18));
- if (self->glyphs[i].dy0 < y0)
+ if (self->glyphs[i].dy0 < y0) {
y0 = self->glyphs[i].dy0;
- if (self->glyphs[i].dy1 > y1)
+ }
+ if (self->glyphs[i].dy1 > y1) {
y1 = self->glyphs[i].dy1;
+ }
glyphdata += 20;
}
@@ -2515,8 +2639,9 @@ textwidth(ImagingFontObject* self, const unsigned char* text)
{
int xsize;
- for (xsize = 0; *text; text++)
+ for (xsize = 0; *text; text++) {
xsize += self->glyphs[*text].dx;
+ }
return xsize;
}
@@ -2595,15 +2720,17 @@ _font_getmask(ImagingFontObject* self, PyObject* args)
self->bitmap,
glyph->sx0, glyph->sy0, glyph->sx1, glyph->sy1
);
- if (!bitmap)
+ if (!bitmap) {
goto failed;
+ }
status = ImagingPaste(
im, bitmap, NULL,
glyph->dx0+x, glyph->dy0+b, glyph->dx1+x, glyph->dy1+b
);
ImagingDelete(bitmap);
- if (status < 0)
+ if (status < 0) {
goto failed;
+ }
x = x + glyph->dx;
b = b + glyph->dy;
}
@@ -2623,8 +2750,9 @@ _font_getsize(ImagingFontObject* self, PyObject* args)
PyObject* encoded_string;
PyObject* val;
- if (!PyArg_ParseTuple(args, "O:getsize", &encoded_string))
+ if (!PyArg_ParseTuple(args, "O:getsize", &encoded_string)) {
return NULL;
+ }
_font_text_asBytes(encoded_string, &text);
if (!text) {
@@ -2651,12 +2779,14 @@ _draw_new(PyObject* self_, PyObject* args)
ImagingObject* imagep;
int blend = 0;
- if (!PyArg_ParseTuple(args, "O!|i", &Imaging_Type, &imagep, &blend))
+ if (!PyArg_ParseTuple(args, "O!|i", &Imaging_Type, &imagep, &blend)) {
return NULL;
+ }
self = PyObject_New(ImagingDrawObject, &ImagingDraw_Type);
- if (self == NULL)
+ if (self == NULL) {
return NULL;
+ }
/* keep a reference to the image object */
Py_INCREF(imagep);
@@ -2683,11 +2813,13 @@ _draw_ink(ImagingDrawObject* self, PyObject* args)
{
INT32 ink = 0;
PyObject* color;
- if (!PyArg_ParseTuple(args, "O", &color))
+ if (!PyArg_ParseTuple(args, "O", &color)) {
return NULL;
+ }
- if (!getink(color, self->image->image, (char*) &ink))
+ if (!getink(color, self->image->image, (char*) &ink)) {
return NULL;
+ }
return PyLong_FromLong((int) ink);
}
@@ -2703,12 +2835,14 @@ _draw_arc(ImagingDrawObject* self, PyObject* args)
int width = 0;
float start, end;
int op = 0;
- if (!PyArg_ParseTuple(args, "Offi|ii", &data, &start, &end, &ink, &width))
+ if (!PyArg_ParseTuple(args, "Offi|ii", &data, &start, &end, &ink, &width)) {
return NULL;
+ }
n = PyPath_Flatten(data, &xy);
- if (n < 0)
+ if (n < 0) {
return NULL;
+ }
if (n != 2) {
PyErr_SetString(PyExc_TypeError, must_be_two_coordinates);
free(xy);
@@ -2723,8 +2857,9 @@ _draw_arc(ImagingDrawObject* self, PyObject* args)
free(xy);
- if (n < 0)
+ if (n < 0) {
return NULL;
+ }
Py_INCREF(Py_None);
return Py_None;
@@ -2739,12 +2874,14 @@ _draw_bitmap(ImagingDrawObject* self, PyObject* args)
PyObject *data;
ImagingObject* bitmap;
int ink;
- if (!PyArg_ParseTuple(args, "OO!i", &data, &Imaging_Type, &bitmap, &ink))
+ if (!PyArg_ParseTuple(args, "OO!i", &data, &Imaging_Type, &bitmap, &ink)) {
return NULL;
+ }
n = PyPath_Flatten(data, &xy);
- if (n < 0)
+ if (n < 0) {
return NULL;
+ }
if (n != 1) {
PyErr_SetString(PyExc_TypeError,
"coordinate list must contain exactly 1 coordinate"
@@ -2760,8 +2897,9 @@ _draw_bitmap(ImagingDrawObject* self, PyObject* args)
free(xy);
- if (n < 0)
+ if (n < 0) {
return NULL;
+ }
Py_INCREF(Py_None);
return Py_None;
@@ -2778,12 +2916,14 @@ _draw_chord(ImagingDrawObject* self, PyObject* args)
int width = 0;
float start, end;
if (!PyArg_ParseTuple(args, "Offii|i",
- &data, &start, &end, &ink, &fill, &width))
+ &data, &start, &end, &ink, &fill, &width)) {
return NULL;
+ }
n = PyPath_Flatten(data, &xy);
- if (n < 0)
+ if (n < 0) {
return NULL;
+ }
if (n != 2) {
PyErr_SetString(PyExc_TypeError, must_be_two_coordinates);
free(xy);
@@ -2798,8 +2938,9 @@ _draw_chord(ImagingDrawObject* self, PyObject* args)
free(xy);
- if (n < 0)
+ if (n < 0) {
return NULL;
+ }
Py_INCREF(Py_None);
return Py_None;
@@ -2815,12 +2956,14 @@ _draw_ellipse(ImagingDrawObject* self, PyObject* args)
int ink;
int fill = 0;
int width = 0;
- if (!PyArg_ParseTuple(args, "Oi|ii", &data, &ink, &fill, &width))
+ if (!PyArg_ParseTuple(args, "Oi|ii", &data, &ink, &fill, &width)) {
return NULL;
+ }
n = PyPath_Flatten(data, &xy);
- if (n < 0)
+ if (n < 0) {
return NULL;
+ }
if (n != 2) {
PyErr_SetString(PyExc_TypeError, must_be_two_coordinates);
free(xy);
@@ -2835,8 +2978,9 @@ _draw_ellipse(ImagingDrawObject* self, PyObject* args)
free(xy);
- if (n < 0)
+ if (n < 0) {
return NULL;
+ }
Py_INCREF(Py_None);
return Py_None;
@@ -2851,12 +2995,14 @@ _draw_lines(ImagingDrawObject* self, PyObject* args)
PyObject *data;
int ink;
int width = 0;
- if (!PyArg_ParseTuple(args, "Oi|i", &data, &ink, &width))
+ if (!PyArg_ParseTuple(args, "Oi|i", &data, &ink, &width)) {
return NULL;
+ }
n = PyPath_Flatten(data, &xy);
- if (n < 0)
+ if (n < 0) {
return NULL;
+ }
if (width <= 1) {
double *p = NULL;
@@ -2870,12 +3016,13 @@ _draw_lines(ImagingDrawObject* self, PyObject* args)
return NULL;
}
}
- if (p) /* draw last point */
+ if (p) {/* draw last point */
ImagingDrawPoint(
self->image->image,
(int) p[2], (int) p[3],
&ink, self->blend
);
+ }
} else {
for (i = 0; i < n-1; i++) {
double *p = &xy[i+i];
@@ -2903,12 +3050,14 @@ _draw_points(ImagingDrawObject* self, PyObject* args)
PyObject *data;
int ink;
- if (!PyArg_ParseTuple(args, "Oi", &data, &ink))
+ if (!PyArg_ParseTuple(args, "Oi", &data, &ink)) {
return NULL;
+ }
n = PyPath_Flatten(data, &xy);
- if (n < 0)
+ if (n < 0) {
return NULL;
+ }
for (i = 0; i < n; i++) {
double *p = &xy[i+i];
@@ -2938,8 +3087,9 @@ _draw_outline(ImagingDrawObject* self, PyObject* args)
PyObject* outline_;
int ink;
int fill = 0;
- if (!PyArg_ParseTuple(args, "Oi|i", &outline_, &ink, &fill))
+ if (!PyArg_ParseTuple(args, "Oi|i", &outline_, &ink, &fill)) {
return NULL;
+ }
outline = PyOutline_AsOutline(outline_);
if (!outline) {
@@ -2948,8 +3098,9 @@ _draw_outline(ImagingDrawObject* self, PyObject* args)
}
if (ImagingDrawOutline(self->image->image, outline,
- &ink, fill, self->blend) < 0)
- return NULL;
+ &ink, fill, self->blend) < 0) {
+ return NULL;
+ }
Py_INCREF(Py_None);
return Py_None;
@@ -2967,12 +3118,14 @@ _draw_pieslice(ImagingDrawObject* self, PyObject* args)
int ink, fill;
int width = 0;
float start, end;
- if (!PyArg_ParseTuple(args, "Offii|i", &data, &start, &end, &ink, &fill, &width))
+ if (!PyArg_ParseTuple(args, "Offii|i", &data, &start, &end, &ink, &fill, &width)) {
return NULL;
+ }
n = PyPath_Flatten(data, &xy);
- if (n < 0)
+ if (n < 0) {
return NULL;
+ }
if (n != 2) {
PyErr_SetString(PyExc_TypeError, must_be_two_coordinates);
free(xy);
@@ -2987,8 +3140,9 @@ _draw_pieslice(ImagingDrawObject* self, PyObject* args)
free(xy);
- if (n < 0)
+ if (n < 0) {
return NULL;
+ }
Py_INCREF(Py_None);
return Py_None;
@@ -3004,12 +3158,14 @@ _draw_polygon(ImagingDrawObject* self, PyObject* args)
PyObject* data;
int ink;
int fill = 0;
- if (!PyArg_ParseTuple(args, "Oi|i", &data, &ink, &fill))
+ if (!PyArg_ParseTuple(args, "Oi|i", &data, &ink, &fill)) {
return NULL;
+ }
n = PyPath_Flatten(data, &xy);
- if (n < 0)
+ if (n < 0) {
return NULL;
+ }
if (n < 2) {
PyErr_SetString(PyExc_TypeError,
"coordinate list must contain at least 2 coordinates"
@@ -3050,12 +3206,14 @@ _draw_rectangle(ImagingDrawObject* self, PyObject* args)
int ink;
int fill = 0;
int width = 0;
- if (!PyArg_ParseTuple(args, "Oi|ii", &data, &ink, &fill, &width))
+ if (!PyArg_ParseTuple(args, "Oi|ii", &data, &ink, &fill, &width)) {
return NULL;
+ }
n = PyPath_Flatten(data, &xy);
- if (n < 0)
+ if (n < 0) {
return NULL;
+ }
if (n != 2) {
PyErr_SetString(PyExc_TypeError, must_be_two_coordinates);
free(xy);
@@ -3070,8 +3228,9 @@ _draw_rectangle(ImagingDrawObject* self, PyObject* args)
free(xy);
- if (n < 0)
+ if (n < 0) {
return NULL;
+ }
Py_INCREF(Py_None);
return Py_None;
@@ -3106,12 +3265,14 @@ pixel_access_new(ImagingObject* imagep, PyObject* args)
PixelAccessObject *self;
int readonly = 0;
- if (!PyArg_ParseTuple(args, "|i", &readonly))
+ if (!PyArg_ParseTuple(args, "|i", &readonly)) {
return NULL;
+ }
self = PyObject_New(PixelAccessObject, &PixelAccess_Type);
- if (self == NULL)
+ if (self == NULL) {
return NULL;
+ }
/* keep a reference to the image object */
Py_INCREF(imagep);
@@ -3133,8 +3294,9 @@ static PyObject *
pixel_access_getitem(PixelAccessObject *self, PyObject *xy)
{
int x, y;
- if (_getxy(xy, &x, &y))
+ if (_getxy(xy, &x, &y)) {
return NULL;
+ }
return getpixel(self->image->image, self->image->access, x, y);
}
@@ -3151,8 +3313,9 @@ pixel_access_setitem(PixelAccessObject *self, PyObject *xy, PyObject *color)
return -1;
}
- if (_getxy(xy, &x, &y))
+ if (_getxy(xy, &x, &y)) {
return -1;
+ }
if (x < 0) {
x = im->xsize + x;
@@ -3166,11 +3329,13 @@ pixel_access_setitem(PixelAccessObject *self, PyObject *xy, PyObject *color)
return -1;
}
- if (!color) /* FIXME: raise exception? */
+ if (!color) {/* FIXME: raise exception? */
return 0;
+ }
- if (!getink(color, im, ink))
+ if (!getink(color, im, ink)) {
return -1;
+ }
self->image->access->put_pixel(im, x, y, ink);
@@ -3196,8 +3361,9 @@ _effect_mandelbrot(ImagingObject* self, PyObject* args)
if (!PyArg_ParseTuple(args, "|(ii)(dddd)i", &xsize, &ysize,
&extent[0], &extent[1], &extent[2], &extent[3],
- &quality))
- return NULL;
+ &quality)) {
+ return NULL;
+ }
return PyImagingNew(ImagingEffectMandelbrot(xsize, ysize, extent, quality));
}
@@ -3207,8 +3373,9 @@ _effect_noise(ImagingObject* self, PyObject* args)
{
int xsize, ysize;
float sigma = 128;
- if (!PyArg_ParseTuple(args, "(ii)|f", &xsize, &ysize, &sigma))
+ if (!PyArg_ParseTuple(args, "(ii)|f", &xsize, &ysize, &sigma)) {
return NULL;
+ }
return PyImagingNew(ImagingEffectNoise(xsize, ysize, sigma));
}
@@ -3218,8 +3385,9 @@ _effect_spread(ImagingObject* self, PyObject* args)
{
int dist;
- if (!PyArg_ParseTuple(args, "i", &dist))
+ if (!PyArg_ParseTuple(args, "i", &dist)) {
return NULL;
+ }
return PyImagingNew(ImagingEffectSpread(self->image, dist));
}
@@ -3237,8 +3405,9 @@ _getcodecstatus(PyObject* self, PyObject* args)
int status;
char* msg;
- if (!PyArg_ParseTuple(args, "i", &status))
+ if (!PyArg_ParseTuple(args, "i", &status)) {
return NULL;
+ }
switch (status) {
case IMAGING_CODEC_OVERRUN:
@@ -3268,11 +3437,13 @@ _save_ppm(ImagingObject* self, PyObject* args)
{
char* filename;
- if (!PyArg_ParseTuple(args, "s", &filename))
+ if (!PyArg_ParseTuple(args, "s", &filename)) {
return NULL;
+ }
- if (!ImagingSavePPM(self->image, filename))
+ if (!ImagingSavePPM(self->image, filename)) {
return NULL;
+ }
Py_INCREF(Py_None);
return Py_None;
@@ -3457,8 +3628,9 @@ image_item(ImagingObject *self, Py_ssize_t i)
if (im->xsize > 0) {
x = i % im->xsize;
y = i / im->xsize;
- } else
+ } else {
x = y = 0; /* leave it to getpixel to raise an exception */
+ }
return getpixel(im, self->access, x, y);
}
@@ -3614,12 +3786,14 @@ _get_stats(PyObject* self, PyObject* args)
PyObject* d;
ImagingMemoryArena arena = &ImagingDefaultArena;
- if (!PyArg_ParseTuple(args, ":get_stats"))
+ if (!PyArg_ParseTuple(args, ":get_stats")) {
return NULL;
+ }
d = PyDict_New();
- if ( ! d)
+ if ( ! d) {
return NULL;
+ }
PyDict_SetItemString(d, "new_count",
PyLong_FromLong(arena->stats_new_count));
PyDict_SetItemString(d, "allocated_blocks",
@@ -3640,8 +3814,9 @@ _reset_stats(PyObject* self, PyObject* args)
{
ImagingMemoryArena arena = &ImagingDefaultArena;
- if (!PyArg_ParseTuple(args, ":reset_stats"))
+ if (!PyArg_ParseTuple(args, ":reset_stats")) {
return NULL;
+ }
arena->stats_new_count = 0;
arena->stats_allocated_blocks = 0;
@@ -3656,8 +3831,9 @@ _reset_stats(PyObject* self, PyObject* args)
static PyObject*
_get_alignment(PyObject* self, PyObject* args)
{
- if (!PyArg_ParseTuple(args, ":get_alignment"))
+ if (!PyArg_ParseTuple(args, ":get_alignment")) {
return NULL;
+ }
return PyLong_FromLong(ImagingDefaultArena.alignment);
}
@@ -3665,8 +3841,9 @@ _get_alignment(PyObject* self, PyObject* args)
static PyObject*
_get_block_size(PyObject* self, PyObject* args)
{
- if (!PyArg_ParseTuple(args, ":get_block_size"))
+ if (!PyArg_ParseTuple(args, ":get_block_size")) {
return NULL;
+ }
return PyLong_FromLong(ImagingDefaultArena.block_size);
}
@@ -3674,8 +3851,9 @@ _get_block_size(PyObject* self, PyObject* args)
static PyObject*
_get_blocks_max(PyObject* self, PyObject* args)
{
- if (!PyArg_ParseTuple(args, ":get_blocks_max"))
+ if (!PyArg_ParseTuple(args, ":get_blocks_max")) {
return NULL;
+ }
return PyLong_FromLong(ImagingDefaultArena.blocks_max);
}
@@ -3684,8 +3862,9 @@ static PyObject*
_set_alignment(PyObject* self, PyObject* args)
{
int alignment;
- if (!PyArg_ParseTuple(args, "i:set_alignment", &alignment))
+ if (!PyArg_ParseTuple(args, "i:set_alignment", &alignment)) {
return NULL;
+ }
if (alignment < 1 || alignment > 128) {
PyErr_SetString(PyExc_ValueError, "alignment should be from 1 to 128");
@@ -3707,8 +3886,9 @@ static PyObject*
_set_block_size(PyObject* self, PyObject* args)
{
int block_size;
- if (!PyArg_ParseTuple(args, "i:set_block_size", &block_size))
+ if (!PyArg_ParseTuple(args, "i:set_block_size", &block_size)) {
return NULL;
+ }
if (block_size <= 0) {
PyErr_SetString(PyExc_ValueError,
@@ -3732,8 +3912,9 @@ static PyObject*
_set_blocks_max(PyObject* self, PyObject* args)
{
int blocks_max;
- if (!PyArg_ParseTuple(args, "i:set_blocks_max", &blocks_max))
+ if (!PyArg_ParseTuple(args, "i:set_blocks_max", &blocks_max)) {
return NULL;
+ }
if (blocks_max < 0) {
PyErr_SetString(PyExc_ValueError,
@@ -3761,8 +3942,9 @@ _clear_cache(PyObject* self, PyObject* args)
{
int i = 0;
- if (!PyArg_ParseTuple(args, "|i:clear_cache", &i))
+ if (!PyArg_ParseTuple(args, "|i:clear_cache", &i)) {
return NULL;
+ }
ImagingMemoryClearCache(&ImagingDefaultArena, i);
@@ -3951,18 +4133,22 @@ setup_module(PyObject* m) {
const char* version = (char*)PILLOW_VERSION;
/* Ready object types */
- if (PyType_Ready(&Imaging_Type) < 0)
+ if (PyType_Ready(&Imaging_Type) < 0) {
return -1;
+ }
#ifdef WITH_IMAGEDRAW
- if (PyType_Ready(&ImagingFont_Type) < 0)
+ if (PyType_Ready(&ImagingFont_Type) < 0) {
return -1;
+ }
- if (PyType_Ready(&ImagingDraw_Type) < 0)
+ if (PyType_Ready(&ImagingDraw_Type) < 0) {
return -1;
+ }
#endif
- if (PyType_Ready(&PixelAccess_Type) < 0)
+ if (PyType_Ready(&PixelAccess_Type) < 0) {
return -1;
+ }
ImagingAccessInit();
@@ -4046,8 +4232,9 @@ PyInit__imaging(void) {
m = PyModule_Create(&module_def);
- if (setup_module(m) < 0)
+ if (setup_module(m) < 0) {
return NULL;
+ }
return m;
}
diff --git a/src/_imagingcms.c b/src/_imagingcms.c
index 0b22ab695..60b6b7228 100644
--- a/src/_imagingcms.c
+++ b/src/_imagingcms.c
@@ -88,8 +88,9 @@ cms_profile_new(cmsHPROFILE profile)
CmsProfileObject* self;
self = PyObject_New(CmsProfileObject, &CmsProfile_Type);
- if (!self)
+ if (!self) {
return NULL;
+ }
self->profile = profile;
@@ -102,12 +103,13 @@ cms_profile_open(PyObject* self, PyObject* args)
cmsHPROFILE hProfile;
char* sProfile;
- if (!PyArg_ParseTuple(args, "s:profile_open", &sProfile))
+ if (!PyArg_ParseTuple(args, "s:profile_open", &sProfile)) {
return NULL;
+ }
hProfile = cmsOpenProfileFromFile(sProfile, "r");
if (!hProfile) {
- PyErr_SetString(PyExc_IOError, "cannot open profile file");
+ PyErr_SetString(PyExc_OSError, "cannot open profile file");
return NULL;
}
@@ -121,12 +123,13 @@ cms_profile_fromstring(PyObject* self, PyObject* args)
char* pProfile;
Py_ssize_t nProfile;
- if (!PyArg_ParseTuple(args, "y#:profile_frombytes", &pProfile, &nProfile))
+ if (!PyArg_ParseTuple(args, "y#:profile_frombytes", &pProfile, &nProfile)) {
return NULL;
+ }
hProfile = cmsOpenProfileFromMem(pProfile, nProfile);
if (!hProfile) {
- PyErr_SetString(PyExc_IOError, "cannot open profile from string");
+ PyErr_SetString(PyExc_OSError, "cannot open profile from string");
return NULL;
}
@@ -150,18 +153,18 @@ cms_profile_tobytes(PyObject* self, PyObject* args)
profile = ((CmsProfileObject*)CmsProfile)->profile;
if (!cmsSaveProfileToMem(profile, pProfile, &nProfile)) {
- PyErr_SetString(PyExc_IOError, "Could not determine profile size");
+ PyErr_SetString(PyExc_OSError, "Could not determine profile size");
return NULL;
}
pProfile = (char*)malloc(nProfile);
if (!pProfile) {
- PyErr_SetString(PyExc_IOError, "Out of Memory");
+ PyErr_SetString(PyExc_OSError, "Out of Memory");
return NULL;
}
if (!cmsSaveProfileToMem(profile, pProfile, &nProfile)) {
- PyErr_SetString(PyExc_IOError, "Could not get profile");
+ PyErr_SetString(PyExc_OSError, "Could not get profile");
free(pProfile);
return NULL;
}
@@ -198,8 +201,9 @@ cms_transform_new(cmsHTRANSFORM transform, char* mode_in, char* mode_out)
CmsTransformObject* self;
self = PyObject_New(CmsTransformObject, &CmsTransform_Type);
- if (!self)
+ if (!self) {
return NULL;
+ }
self->transform = transform;
@@ -292,17 +296,19 @@ pyCMSgetAuxChannelChannel (cmsUInt32Number format, int auxChannelNdx)
if (T_SWAPFIRST(format) && T_DOSWAP(format)) {
// reverse order, before anything but last extra is shifted last
- if (auxChannelNdx == numExtras - 1)
+ if (auxChannelNdx == numExtras - 1) {
return numColors + numExtras - 1;
- else
+ } else {
return numExtras - 2 - auxChannelNdx;
+ }
}
else if (T_SWAPFIRST(format)) {
// in order, after color channels, but last extra is shifted to first
- if (auxChannelNdx == numExtras - 1)
+ if (auxChannelNdx == numExtras - 1) {
return 0;
- else
+ } else {
return numColors + 1 + auxChannelNdx;
+ }
}
else if (T_DOSWAP(format)) {
// reverse order, before anything
@@ -330,23 +336,26 @@ pyCMScopyAux (cmsHTRANSFORM hTransform, Imaging imDst, const Imaging imSrc)
int e;
// trivially copied
- if (imDst == imSrc)
+ if (imDst == imSrc) {
return;
+ }
dstLCMSFormat = cmsGetTransformOutputFormat(hTransform);
srcLCMSFormat = cmsGetTransformInputFormat(hTransform);
// currently, all Pillow formats are chunky formats, but check it anyway
- if (T_PLANAR(dstLCMSFormat) || T_PLANAR(srcLCMSFormat))
+ if (T_PLANAR(dstLCMSFormat) || T_PLANAR(srcLCMSFormat)) {
return;
+ }
// copy only if channel format is identical, except OPTIMIZED is ignored as it
// does not affect the aux channel
if (T_FLOAT(dstLCMSFormat) != T_FLOAT(srcLCMSFormat)
|| T_FLAVOR(dstLCMSFormat) != T_FLAVOR(srcLCMSFormat)
|| T_ENDIAN16(dstLCMSFormat) != T_ENDIAN16(srcLCMSFormat)
- || T_BYTES(dstLCMSFormat) != T_BYTES(srcLCMSFormat))
+ || T_BYTES(dstLCMSFormat) != T_BYTES(srcLCMSFormat)) {
return;
+ }
numSrcExtras = T_EXTRA(srcLCMSFormat);
numDstExtras = T_EXTRA(dstLCMSFormat);
@@ -367,8 +376,9 @@ pyCMScopyAux (cmsHTRANSFORM hTransform, Imaging imDst, const Imaging imSrc)
char* pDstExtras = imDst->image[y] + dstChannel * channelSize;
const char* pSrcExtras = imSrc->image[y] + srcChannel * channelSize;
- for (x = 0; x < xSize; x++)
+ for (x = 0; x < xSize; x++) {
memcpy(pDstExtras + x * dstChunkSize, pSrcExtras + x * srcChunkSize, channelSize);
+ }
}
}
}
@@ -378,14 +388,16 @@ pyCMSdoTransform(Imaging im, Imaging imOut, cmsHTRANSFORM hTransform)
{
int i;
- if (im->xsize > imOut->xsize || im->ysize > imOut->ysize)
+ if (im->xsize > imOut->xsize || im->ysize > imOut->ysize) {
return -1;
+ }
Py_BEGIN_ALLOW_THREADS
// transform color channels only
- for (i = 0; i < im->ysize; i++)
+ for (i = 0; i < im->ysize; i++) {
cmsDoTransform(hTransform, im->image[i], imOut->image[i], im->xsize);
+ }
// lcms by default does nothing to the auxiliary channels leaving those
// unchanged. To do "the right thing" here, i.e. maintain identical results
@@ -417,8 +429,9 @@ _buildTransform(cmsHPROFILE hInputProfile, cmsHPROFILE hOutputProfile, char *sIn
Py_END_ALLOW_THREADS
- if (!hTransform)
+ if (!hTransform) {
PyErr_SetString(PyExc_ValueError, "cannot build transform");
+ }
return hTransform; /* if NULL, an exception is set */
}
@@ -442,8 +455,9 @@ _buildProofTransform(cmsHPROFILE hInputProfile, cmsHPROFILE hOutputProfile, cmsH
Py_END_ALLOW_THREADS
- if (!hTransform)
+ if (!hTransform) {
PyErr_SetString(PyExc_ValueError, "cannot build proof transform");
+ }
return hTransform; /* if NULL, an exception is set */
}
@@ -462,13 +476,15 @@ buildTransform(PyObject *self, PyObject *args) {
cmsHTRANSFORM transform = NULL;
- if (!PyArg_ParseTuple(args, "O!O!ss|ii:buildTransform", &CmsProfile_Type, &pInputProfile, &CmsProfile_Type, &pOutputProfile, &sInMode, &sOutMode, &iRenderingIntent, &cmsFLAGS))
+ if (!PyArg_ParseTuple(args, "O!O!ss|ii:buildTransform", &CmsProfile_Type, &pInputProfile, &CmsProfile_Type, &pOutputProfile, &sInMode, &sOutMode, &iRenderingIntent, &cmsFLAGS)) {
return NULL;
+ }
transform = _buildTransform(pInputProfile->profile, pOutputProfile->profile, sInMode, sOutMode, iRenderingIntent, cmsFLAGS);
- if (!transform)
+ if (!transform) {
return NULL;
+ }
return cms_transform_new(transform, sInMode, sOutMode);
}
@@ -487,13 +503,15 @@ buildProofTransform(PyObject *self, PyObject *args)
cmsHTRANSFORM transform = NULL;
- if (!PyArg_ParseTuple(args, "O!O!O!ss|iii:buildProofTransform", &CmsProfile_Type, &pInputProfile, &CmsProfile_Type, &pOutputProfile, &CmsProfile_Type, &pProofProfile, &sInMode, &sOutMode, &iRenderingIntent, &iProofIntent, &cmsFLAGS))
+ if (!PyArg_ParseTuple(args, "O!O!O!ss|iii:buildProofTransform", &CmsProfile_Type, &pInputProfile, &CmsProfile_Type, &pOutputProfile, &CmsProfile_Type, &pProofProfile, &sInMode, &sOutMode, &iRenderingIntent, &iProofIntent, &cmsFLAGS)) {
return NULL;
+ }
transform = _buildProofTransform(pInputProfile->profile, pOutputProfile->profile, pProofProfile->profile, sInMode, sOutMode, iRenderingIntent, iProofIntent, cmsFLAGS);
- if (!transform)
+ if (!transform) {
return NULL;
+ }
return cms_transform_new(transform, sInMode, sOutMode);
@@ -509,8 +527,9 @@ cms_transform_apply(CmsTransformObject *self, PyObject *args)
int result;
- if (!PyArg_ParseTuple(args, "nn:apply", &idIn, &idOut))
+ if (!PyArg_ParseTuple(args, "nn:apply", &idIn, &idOut)) {
return NULL;
+ }
im = (Imaging) idIn;
imOut = (Imaging) idOut;
@@ -532,8 +551,9 @@ createProfile(PyObject *self, PyObject *args)
cmsCIExyY whitePoint;
cmsBool result;
- if (!PyArg_ParseTuple(args, "s|d:createProfile", &sColorSpace, &dColorTemp))
+ if (!PyArg_ParseTuple(args, "s|d:createProfile", &sColorSpace, &dColorTemp)) {
return NULL;
+ }
if (strcmp(sColorSpace, "LAB") == 0) {
if (dColorTemp > 0.0) {
@@ -575,8 +595,9 @@ cms_profile_is_intent_supported(CmsProfileObject *self, PyObject *args)
int intent;
int direction;
- if (!PyArg_ParseTuple(args, "ii:is_intent_supported", &intent, &direction))
+ if (!PyArg_ParseTuple(args, "ii:is_intent_supported", &intent, &direction)) {
return NULL;
+ }
result = cmsIsIntentSupported(self->profile, intent, direction);
@@ -602,8 +623,9 @@ cms_get_display_profile_win32(PyObject* self, PyObject* args)
HANDLE handle = 0;
int is_dc = 0;
- if (!PyArg_ParseTuple(args, "|" F_HANDLE "i:get_display_profile", &handle, &is_dc))
+ if (!PyArg_ParseTuple(args, "|" F_HANDLE "i:get_display_profile", &handle, &is_dc)) {
return NULL;
+ }
filename_size = sizeof(filename);
@@ -615,8 +637,9 @@ cms_get_display_profile_win32(PyObject* self, PyObject* args)
ReleaseDC((HWND) handle, dc);
}
- if (ok)
+ if (ok) {
return PyUnicode_FromStringAndSize(filename, filename_size-1);
+ }
Py_INCREF(Py_None);
return Py_None;
@@ -655,7 +678,7 @@ _profile_read_mlu(CmsProfileObject* self, cmsTagSignature info)
buf = malloc(len);
if (!buf) {
- PyErr_SetString(PyExc_IOError, "Out of Memory");
+ PyErr_SetString(PyExc_OSError, "Out of Memory");
return NULL;
}
/* Just in case the next call fails. */
@@ -745,10 +768,11 @@ _profile_read_ciexyz(CmsProfileObject* self, cmsTagSignature info, int multi)
Py_INCREF(Py_None);
return Py_None;
}
- if (multi)
+ if (multi) {
return _xyz3_py(XYZ);
- else
+ } else {
return _xyz_py(XYZ);
+ }
}
static PyObject*
@@ -826,8 +850,9 @@ static cmsBool _calculate_rgb_primaries(CmsProfileObject* self, cmsCIEXYZTRIPLE*
// double array of RGB values with max on each identity
hXYZ = cmsCreateXYZProfile();
- if (hXYZ == NULL)
+ if (hXYZ == NULL) {
return 0;
+ }
// transform from our profile to XYZ using doubles for highest precision
hTransform = cmsCreateTransform(self->profile, TYPE_RGB_DBL,
@@ -835,8 +860,9 @@ static cmsBool _calculate_rgb_primaries(CmsProfileObject* self, cmsCIEXYZTRIPLE*
INTENT_RELATIVE_COLORIMETRIC,
cmsFLAGS_NOCACHE | cmsFLAGS_NOOPTIMIZE);
cmsCloseProfile(hXYZ);
- if (hTransform == NULL)
+ if (hTransform == NULL) {
return 0;
+ }
cmsDoTransform(hTransform, (void*) input, result, 3);
cmsDeleteTransform(hTransform);
@@ -881,8 +907,9 @@ _is_intent_supported(CmsProfileObject* self, int clut)
/* Only valid for ICC Intents (otherwise we read invalid memory in lcms cmsio1.c). */
if (!(intent == INTENT_PERCEPTUAL || intent == INTENT_RELATIVE_COLORIMETRIC
- || intent == INTENT_SATURATION || intent == INTENT_ABSOLUTE_COLORIMETRIC))
+ || intent == INTENT_SATURATION || intent == INTENT_ABSOLUTE_COLORIMETRIC)) {
continue;
+ }
id = PyLong_FromLong((long) intent);
entry = Py_BuildValue("(OOO)",
@@ -1276,8 +1303,9 @@ cms_profile_getattr_red_primary(CmsProfileObject* self, void* closure)
cmsBool result = 0;
cmsCIEXYZTRIPLE primaries;
- if (cmsIsMatrixShaper(self->profile))
+ if (cmsIsMatrixShaper(self->profile)) {
result = _calculate_rgb_primaries(self, &primaries);
+ }
if (! result) {
Py_INCREF(Py_None);
return Py_None;
@@ -1292,8 +1320,9 @@ cms_profile_getattr_green_primary(CmsProfileObject* self, void* closure)
cmsBool result = 0;
cmsCIEXYZTRIPLE primaries;
- if (cmsIsMatrixShaper(self->profile))
+ if (cmsIsMatrixShaper(self->profile)) {
result = _calculate_rgb_primaries(self, &primaries);
+ }
if (! result) {
Py_INCREF(Py_None);
return Py_None;
@@ -1308,8 +1337,9 @@ cms_profile_getattr_blue_primary(CmsProfileObject* self, void* closure)
cmsBool result = 0;
cmsCIEXYZTRIPLE primaries;
- if (cmsIsMatrixShaper(self->profile))
+ if (cmsIsMatrixShaper(self->profile)) {
result = _calculate_rgb_primaries(self, &primaries);
+ }
if (! result) {
Py_INCREF(Py_None);
return Py_None;
@@ -1387,12 +1417,13 @@ cms_profile_getattr_icc_measurement_condition (CmsProfileObject* self, void* clo
return Py_None;
}
- if (mc->Geometry == 1)
+ if (mc->Geometry == 1) {
geo = "45/0, 0/45";
- else if (mc->Geometry == 2)
+ } else if (mc->Geometry == 2) {
geo = "0d, d/0";
- else
+ } else {
geo = "unknown";
+ }
return Py_BuildValue("{s:i,s:(ddd),s:s,s:d,s:s}",
"observer", mc->Observer,
@@ -1611,8 +1642,9 @@ PyInit__imagingcms(void) {
m = PyModule_Create(&module_def);
- if (setup_module(m) < 0)
+ if (setup_module(m) < 0) {
return NULL;
+ }
PyDateTime_IMPORT;
diff --git a/src/_imagingft.c b/src/_imagingft.c
index f6a5b7d59..e0ff7521c 100644
--- a/src/_imagingft.c
+++ b/src/_imagingft.c
@@ -31,7 +31,7 @@
#define KEEP_PY_UNICODE
-#if !defined(_MSC_VER)
+#ifndef _WIN32
#include
#endif
@@ -137,13 +137,14 @@ geterror(int code)
{
int i;
- for (i = 0; ft_errors[i].message; i++)
+ for (i = 0; ft_errors[i].message; i++) {
if (ft_errors[i].code == code) {
- PyErr_SetString(PyExc_IOError, ft_errors[i].message);
+ PyErr_SetString(PyExc_OSError, ft_errors[i].message);
return NULL;
}
+ }
- PyErr_SetString(PyExc_IOError, "unknown freetype error");
+ PyErr_SetString(PyExc_OSError, "unknown freetype error");
return NULL;
}
@@ -154,20 +155,24 @@ setraqm(void)
p_raqm.raqm = NULL;
/* Microsoft needs a totally different system */
-#if !defined(_MSC_VER)
+#ifndef _WIN32
p_raqm.raqm = dlopen("libraqm.so.0", RTLD_LAZY);
if (!p_raqm.raqm) {
p_raqm.raqm = dlopen("libraqm.dylib", RTLD_LAZY);
}
#else
p_raqm.raqm = LoadLibrary("libraqm");
+ /* MSYS */
+ if (!p_raqm.raqm) {
+ p_raqm.raqm = LoadLibrary("libraqm-0");
+ }
#endif
if (!p_raqm.raqm) {
return 1;
}
-#if !defined(_MSC_VER)
+#ifndef _WIN32
p_raqm.version_atleast = (t_raqm_version_atleast)dlsym(p_raqm.raqm, "raqm_version_atleast");
p_raqm.create = (t_raqm_create)dlsym(p_raqm.raqm, "raqm_create");
p_raqm.set_text = (t_raqm_set_text)dlsym(p_raqm.raqm, "raqm_set_text");
@@ -259,7 +264,7 @@ getfont(PyObject* self_, PyObject* args, PyObject* kw)
if (!library) {
PyErr_SetString(
- PyExc_IOError,
+ PyExc_OSError,
"failed to initialize FreeType library"
);
return NULL;
@@ -274,8 +279,9 @@ getfont(PyObject* self_, PyObject* args, PyObject* kw)
self = PyObject_New(FontObject, &Font_Type);
if (!self) {
- if (filename)
+ if (filename) {
PyMem_Free(filename);
+ }
return NULL;
}
@@ -299,8 +305,9 @@ getfont(PyObject* self_, PyObject* args, PyObject* kw)
}
}
- if (!error)
+ if (!error) {
error = FT_Set_Pixel_Sizes(self->face, 0, size);
+ }
if (!error && encoding && strlen((char*) encoding) == 4) {
FT_Encoding encoding_tag = FT_MAKE_TAG(
@@ -308,8 +315,9 @@ getfont(PyObject* self_, PyObject* args, PyObject* kw)
);
error = FT_Select_Charmap(self->face, encoding_tag);
}
- if (filename)
+ if (filename) {
PyMem_Free(filename);
+ }
if (error) {
if (self->font_bytes) {
@@ -327,8 +335,9 @@ static int
font_getchar(PyObject* string, int index, FT_ULong* char_out)
{
if (PyUnicode_Check(string)) {
- if (index >= PyUnicode_GET_LENGTH(string))
+ if (index >= PyUnicode_GET_LENGTH(string)) {
return 0;
+ }
*char_out = PyUnicode_READ_CHAR(string, index);
return 1;
}
@@ -401,11 +410,11 @@ text_layout_raqm(PyObject* string, FontObject* self, const char* dir, PyObject *
direction = RAQM_DIRECTION_DEFAULT;
if (dir) {
- if (strcmp(dir, "rtl") == 0)
+ if (strcmp(dir, "rtl") == 0) {
direction = RAQM_DIRECTION_RTL;
- else if (strcmp(dir, "ltr") == 0)
+ } else if (strcmp(dir, "ltr") == 0) {
direction = RAQM_DIRECTION_LTR;
- else if (strcmp(dir, "ttb") == 0) {
+ } else if (strcmp(dir, "ttb") == 0) {
direction = RAQM_DIRECTION_TTB;
if (p_raqm.version_atleast == NULL || !(*p_raqm.version_atleast)(0, 7, 0)) {
PyErr_SetString(PyExc_ValueError, "libraqm 0.7 or greater required for 'ttb' direction");
@@ -443,8 +452,9 @@ text_layout_raqm(PyObject* string, FontObject* self, const char* dir, PyObject *
if (PyUnicode_Check(item)) {
bytes = PyUnicode_AsUTF8String(item);
- if (bytes == NULL)
+ if (bytes == NULL) {
goto failed;
+ }
feature = PyBytes_AS_STRING(bytes);
size = PyBytes_GET_SIZE(bytes);
}
@@ -547,7 +557,7 @@ text_layout_fallback(PyObject* string, FontObject* self, const char* dir, PyObje
return 0;
}
- load_flags = FT_LOAD_RENDER|FT_LOAD_NO_BITMAP;
+ load_flags = FT_LOAD_NO_BITMAP;
if (mask) {
load_flags |= FT_LOAD_TARGET_MONO;
}
@@ -608,8 +618,9 @@ font_getsize(FontObject* self, PyObject* args)
/* calculate size and bearing for a given string */
PyObject* string;
- if (!PyArg_ParseTuple(args, "O|zOz:getsize", &string, &dir, &features, &lang))
+ if (!PyArg_ParseTuple(args, "O|zOz:getsize", &string, &dir, &features, &lang)) {
return NULL;
+ }
count = text_layout(string, self, dir, features, lang, &glyph_info, 0);
if (PyErr_Occurred()) {
@@ -631,8 +642,9 @@ font_getsize(FontObject* self, PyObject* args)
* Yifu Yu, 2014-10-15
*/
error = FT_Load_Glyph(face, index, FT_LOAD_DEFAULT|FT_LOAD_NO_BITMAP);
- if (error)
+ if (error) {
return geterror(error);
+ }
if (i == 0) {
if (horizontal_dir) {
@@ -657,21 +669,26 @@ font_getsize(FontObject* self, PyObject* args)
offset = glyph_info[i].x_advance -
face->glyph->metrics.width -
face->glyph->metrics.horiBearingX;
- if (offset < 0)
+ if (offset < 0) {
x_advanced -= offset;
- if (x_advanced > x_max)
+ }
+ if (x_advanced > x_max) {
x_max = x_advanced;
+ }
bbox.yMax += glyph_info[i].y_offset;
bbox.yMin += glyph_info[i].y_offset;
- if (bbox.yMax > y_max)
+ if (bbox.yMax > y_max) {
y_max = bbox.yMax;
- if (bbox.yMin < y_min)
+ }
+ if (bbox.yMin < y_min) {
y_min = bbox.yMin;
+ }
// find max distance of baseline from top
- if (face->glyph->metrics.horiBearingY > yoffset)
+ if (face->glyph->metrics.horiBearingY > yoffset) {
yoffset = face->glyph->metrics.horiBearingY;
+ }
} else {
y_max -= glyph_info[i].y_advance;
@@ -681,14 +698,17 @@ font_getsize(FontObject* self, PyObject* args)
offset = -glyph_info[i].y_advance -
face->glyph->metrics.height -
face->glyph->metrics.vertBearingY;
- if (offset < 0)
+ if (offset < 0) {
y_max -= offset;
+ }
}
- if (bbox.xMax > x_max)
+ if (bbox.xMax > x_max) {
x_max = bbox.xMax;
- if (i == 0 || bbox.xMin < x_min)
+ }
+ if (i == 0 || bbox.xMin < x_min) {
x_min = bbox.xMin;
+ }
}
FT_Done_Glyph(glyph);
@@ -702,20 +722,22 @@ font_getsize(FontObject* self, PyObject* args)
if (face) {
if (horizontal_dir) {
// left bearing
- if (xoffset < 0)
+ if (xoffset < 0) {
x_max -= xoffset;
- else
+ } else {
xoffset = 0;
+ }
/* difference between the font ascender and the distance of
* the baseline from the top */
yoffset = PIXEL(self->face->size->metrics.ascender - yoffset);
} else {
// top bearing
- if (yoffset < 0)
+ if (yoffset < 0) {
y_max -= yoffset;
- else
+ } else {
yoffset = 0;
+ }
}
}
@@ -800,8 +822,9 @@ font_render(FontObject* self, PyObject* args)
temp = bitmap.rows - glyph_slot->bitmap_top;
temp -= PIXEL(glyph_info[i].y_offset);
- if (temp > ascender)
+ if (temp > ascender) {
ascender = temp;
+ }
}
if (stroker == NULL) {
@@ -855,10 +878,12 @@ font_render(FontObject* self, PyObject* args)
x0 = 0;
x1 = bitmap.width;
- if (xx < 0)
+ if (xx < 0) {
x0 = -xx;
- if (xx + x1 > im->xsize)
+ }
+ if (xx + x1 > im->xsize) {
x1 = im->xsize - xx;
+ }
source = (unsigned char*) bitmap.buffer;
for (bitmap_y = 0; bitmap_y < bitmap.rows; bitmap_y++) {
@@ -876,8 +901,9 @@ font_render(FontObject* self, PyObject* args)
// use monochrome mask (on palette images, etc)
int j, k, m = 128;
for (j = k = 0; j < x1; j++) {
- if (j >= x0 && (source[k] & m))
+ if (j >= x0 && (source[k] & m)) {
target[j] = 255;
+ }
if (!(m >>= 1)) {
m = 128;
k++;
@@ -887,8 +913,9 @@ font_render(FontObject* self, PyObject* args)
// use antialiased rendering
int k;
for (k = x0; k < x1; k++) {
- if (target[k] < source[k])
+ if (target[k] < source[k]) {
target[k] = source[k];
+ }
}
}
}
@@ -919,8 +946,9 @@ font_render(FontObject* self, PyObject* args)
PyObject *list_names, *list_name;
error = FT_Get_MM_Var(self->face, &master);
- if (error)
+ if (error) {
return geterror(error);
+ }
num_namedstyles = master->num_namedstyles;
list_names = PyList_New(num_namedstyles);
@@ -928,12 +956,14 @@ font_render(FontObject* self, PyObject* args)
name_count = FT_Get_Sfnt_Name_Count(self->face);
for (i = 0; i < name_count; i++) {
error = FT_Get_Sfnt_Name(self->face, i, &name);
- if (error)
+ if (error) {
return geterror(error);
+ }
for (j = 0; j < num_namedstyles; j++) {
- if (PyList_GetItem(list_names, j) != NULL)
+ if (PyList_GetItem(list_names, j) != NULL) {
continue;
+ }
if (master->namedstyle[j].strid == name.name_id) {
list_name = Py_BuildValue("y#", name.string, name.string_len);
@@ -958,8 +988,9 @@ font_render(FontObject* self, PyObject* args)
FT_SfntName name;
PyObject *list_axes, *list_axis, *axis_name;
error = FT_Get_MM_Var(self->face, &master);
- if (error)
+ if (error) {
return geterror(error);
+ }
num_axis = master->num_axis;
name_count = FT_Get_Sfnt_Name_Count(self->face);
@@ -978,8 +1009,9 @@ font_render(FontObject* self, PyObject* args)
for (j = 0; j < name_count; j++) {
error = FT_Get_Sfnt_Name(self->face, j, &name);
- if (error)
+ if (error) {
return geterror(error);
+ }
if (name.name_id == axis.strid) {
axis_name = Py_BuildValue("y#", name.string, name.string_len);
@@ -1002,12 +1034,14 @@ font_render(FontObject* self, PyObject* args)
int error;
int instance_index;
- if (!PyArg_ParseTuple(args, "i", &instance_index))
+ if (!PyArg_ParseTuple(args, "i", &instance_index)) {
return NULL;
+ }
error = FT_Set_Named_Instance(self->face, instance_index);
- if (error)
+ if (error) {
return geterror(error);
+ }
Py_INCREF(Py_None);
return Py_None;
@@ -1022,8 +1056,9 @@ font_render(FontObject* self, PyObject* args)
Py_ssize_t i, num_coords;
FT_Fixed *coords;
FT_Fixed coord;
- if (!PyArg_ParseTuple(args, "O", &axes))
+ if (!PyArg_ParseTuple(args, "O", &axes)) {
return NULL;
+ }
if (!PyList_Check(axes)) {
PyErr_SetString(PyExc_TypeError, "argument must be a list");
@@ -1037,13 +1072,13 @@ font_render(FontObject* self, PyObject* args)
}
for (i = 0; i < num_coords; i++) {
item = PyList_GET_ITEM(axes, i);
- if (PyFloat_Check(item))
+ if (PyFloat_Check(item)) {
coord = PyFloat_AS_DOUBLE(item);
- else if (PyLong_Check(item))
+ } else if (PyLong_Check(item)) {
coord = (float) PyLong_AS_LONG(item);
- else if (PyNumber_Check(item))
+ } else if (PyNumber_Check(item)) {
coord = PyFloat_AsDouble(item);
- else {
+ } else {
free(coords);
PyErr_SetString(PyExc_TypeError, "list must contain numbers");
return NULL;
@@ -1053,8 +1088,9 @@ font_render(FontObject* self, PyObject* args)
error = FT_Set_Var_Design_Coordinates(self->face, num_coords, coords);
free(coords);
- if (error)
+ if (error) {
return geterror(error);
+ }
Py_INCREF(Py_None);
return Py_None;
@@ -1090,16 +1126,18 @@ static PyMethodDef font_methods[] = {
static PyObject*
font_getattr_family(FontObject* self, void* closure)
{
- if (self->face->family_name)
+ if (self->face->family_name) {
return PyUnicode_FromString(self->face->family_name);
+ }
Py_RETURN_NONE;
}
static PyObject*
font_getattr_style(FontObject* self, void* closure)
{
- if (self->face->style_name)
+ if (self->face->style_name) {
return PyUnicode_FromString(self->face->style_name);
+ }
Py_RETURN_NONE;
}
@@ -1200,8 +1238,9 @@ setup_module(PyObject* m) {
/* Ready object type */
PyType_Ready(&Font_Type);
- if (FT_Init_FreeType(&library))
+ if (FT_Init_FreeType(&library)) {
return 0; /* leave it uninitialized */
+ }
FT_Library_Version(library, &major, &minor, &patch);
@@ -1230,8 +1269,9 @@ PyInit__imagingft(void) {
m = PyModule_Create(&module_def);
- if (setup_module(m) < 0)
+ if (setup_module(m) < 0) {
return NULL;
+ }
return m;
}
diff --git a/src/_imagingmath.c b/src/_imagingmath.c
index bc66a581a..959859a1d 100644
--- a/src/_imagingmath.c
+++ b/src/_imagingmath.c
@@ -88,12 +88,14 @@ void name(Imaging out, Imaging im1, Imaging im2)\
static int powi(int x, int y)
{
double v = pow(x, y) + 0.5;
- if (errno == EDOM)
+ if (errno == EDOM) {
return 0;
- if (v < MIN_INT32)
+ }
+ if (v < MIN_INT32) {
v = MIN_INT32;
- else if (v > MAX_INT32)
+ } else if (v > MAX_INT32) {
v = MAX_INT32;
+ }
return (int) v;
}
@@ -167,8 +169,9 @@ _unop(PyObject* self, PyObject* args)
void (*unop)(Imaging, Imaging);
Py_ssize_t op, i0, i1;
- if (!PyArg_ParseTuple(args, "nnn", &op, &i0, &i1))
+ if (!PyArg_ParseTuple(args, "nnn", &op, &i0, &i1)) {
return NULL;
+ }
out = (Imaging) i0;
im1 = (Imaging) i1;
@@ -190,8 +193,9 @@ _binop(PyObject* self, PyObject* args)
void (*binop)(Imaging, Imaging, Imaging);
Py_ssize_t op, i0, i1, i2;
- if (!PyArg_ParseTuple(args, "nnnn", &op, &i0, &i1, &i2))
+ if (!PyArg_ParseTuple(args, "nnnn", &op, &i0, &i1, &i2)) {
return NULL;
+ }
out = (Imaging) i0;
im1 = (Imaging) i1;
@@ -215,8 +219,9 @@ static void
install(PyObject *d, char* name, void* value)
{
PyObject *v = PyLong_FromSsize_t((Py_ssize_t) value);
- if (!v || PyDict_SetItemString(d, name, v))
+ if (!v || PyDict_SetItemString(d, name, v)) {
PyErr_Clear();
+ }
Py_XDECREF(v);
}
@@ -286,8 +291,9 @@ PyInit__imagingmath(void) {
m = PyModule_Create(&module_def);
- if (setup_module(m) < 0)
+ if (setup_module(m) < 0) {
return NULL;
+ }
return m;
}
diff --git a/src/_imagingmorph.c b/src/_imagingmorph.c
index 050ae9f02..4f7844604 100644
--- a/src/_imagingmorph.c
+++ b/src/_imagingmorph.c
@@ -85,8 +85,9 @@ apply(PyObject *self, PyObject* args)
/* zero boundary conditions. TBD support other modes */
outrow[0] = outrow[width-1] = 0;
if (row_idx==0 || row_idx == height-1) {
- for(col_idx=0; col_idxinterp;
}
diff --git a/src/_webp.c b/src/_webp.c
index 93cf7ae85..a4138ad0f 100644
--- a/src/_webp.c
+++ b/src/_webp.c
@@ -70,7 +70,7 @@ PyObject* HandleMuxError(WebPMuxError err, char* chunk) {
case WEBP_MUX_BAD_DATA:
case WEBP_MUX_NOT_ENOUGH_DATA:
- PyErr_SetString(PyExc_IOError, message);
+ PyErr_SetString(PyExc_OSError, message);
break;
default:
@@ -423,7 +423,7 @@ PyObject* _anim_decoder_get_next(PyObject* self)
WebPAnimDecoderObject* decp = (WebPAnimDecoderObject*)self;
if (!WebPAnimDecoderGetNext(decp->dec, &buf, ×tamp)) {
- PyErr_SetString(PyExc_IOError, "failed to read next frame");
+ PyErr_SetString(PyExc_OSError, "failed to read next frame");
return NULL;
}
@@ -724,8 +724,9 @@ PyObject* WebPDecode_wrapper(PyObject* self, PyObject* args)
WebPData exif_data = {0};
WebPMux* mux = WebPMuxCreate(&data, copy_data);
- if (NULL == mux)
+ if (NULL == mux) {
goto end;
+ }
if (WEBP_MUX_OK != WebPMuxGetFrame(mux, 1, &image))
{
@@ -738,11 +739,13 @@ PyObject* WebPDecode_wrapper(PyObject* self, PyObject* args)
vp8_status_code = WebPDecode(webp, size, &config);
- if (WEBP_MUX_OK == WebPMuxGetChunk(mux, "ICCP", &icc_profile_data))
+ if (WEBP_MUX_OK == WebPMuxGetChunk(mux, "ICCP", &icc_profile_data)) {
icc_profile = PyBytes_FromStringAndSize((const char*)icc_profile_data.bytes, icc_profile_data.size);
+ }
- if (WEBP_MUX_OK == WebPMuxGetChunk(mux, "EXIF", &exif_data))
+ if (WEBP_MUX_OK == WebPMuxGetChunk(mux, "EXIF", &exif_data)) {
exif = PyBytes_FromStringAndSize((const char*)exif_data.bytes, exif_data.size);
+ }
WebPDataClear(&image.bitstream);
WebPMuxDelete(mux);
@@ -750,8 +753,9 @@ PyObject* WebPDecode_wrapper(PyObject* self, PyObject* args)
#endif
}
- if (vp8_status_code != VP8_STATUS_OK)
+ if (vp8_status_code != VP8_STATUS_OK) {
goto end;
+ }
if (config.output.colorspace < MODE_YUV) {
bytes = PyBytes_FromStringAndSize((char*)config.output.u.RGBA.rgba,
@@ -777,8 +781,9 @@ end:
Py_XDECREF(icc_profile);
Py_XDECREF(exif);
- if (Py_None == ret)
+ if (Py_None == ret) {
Py_RETURN_NONE;
+ }
return ret;
}
@@ -836,7 +841,7 @@ void addAnimFlagToModule(PyObject* m) {
void addTransparencyFlagToModule(PyObject* m) {
PyModule_AddObject(m, "HAVE_TRANSPARENCY",
- PyBool_FromLong(!WebPDecoderBuggyAlpha()));
+ PyBool_FromLong(!WebPDecoderBuggyAlpha()));
}
static int setup_module(PyObject* m) {
@@ -847,8 +852,9 @@ static int setup_module(PyObject* m) {
#ifdef HAVE_WEBPANIM
/* Ready object types */
if (PyType_Ready(&WebPAnimDecoder_Type) < 0 ||
- PyType_Ready(&WebPAnimEncoder_Type) < 0)
+ PyType_Ready(&WebPAnimEncoder_Type) < 0) {
return -1;
+ }
#endif
return 0;
}
@@ -866,8 +872,9 @@ PyInit__webp(void) {
};
m = PyModule_Create(&module_def);
- if (setup_module(m) < 0)
+ if (setup_module(m) < 0) {
return NULL;
+ }
return m;
}
diff --git a/src/decode.c b/src/decode.c
index 5ab6ca9d1..25ce7316b 100644
--- a/src/decode.c
+++ b/src/decode.c
@@ -63,12 +63,14 @@ PyImaging_DecoderNew(int contextsize)
ImagingDecoderObject *decoder;
void *context;
- if(PyType_Ready(&ImagingDecoderType) < 0)
+ if(PyType_Ready(&ImagingDecoderType) < 0) {
return NULL;
+ }
decoder = PyObject_New(ImagingDecoderObject, &ImagingDecoderType);
- if (decoder == NULL)
+ if (decoder == NULL) {
return NULL;
+ }
/* Clear the decoder state */
memset(&decoder->state, 0, sizeof(decoder->state));
@@ -81,8 +83,9 @@ PyImaging_DecoderNew(int contextsize)
(void) PyErr_NoMemory();
return NULL;
}
- } else
+ } else {
context = 0;
+ }
/* Initialize decoder context */
decoder->state.context = context;
@@ -104,8 +107,9 @@ PyImaging_DecoderNew(int contextsize)
static void
_dealloc(ImagingDecoderObject* decoder)
{
- if (decoder->cleanup)
+ if (decoder->cleanup) {
decoder->cleanup(&decoder->state);
+ }
free(decoder->state.buffer);
free(decoder->state.context);
Py_XDECREF(decoder->lock);
@@ -121,8 +125,9 @@ _decode(ImagingDecoderObject* decoder, PyObject* args)
int status;
ImagingSectionCookie cookie;
- if (!PyArg_ParseTuple(args, "y#", &buffer, &bufsize))
+ if (!PyArg_ParseTuple(args, "y#", &buffer, &bufsize)) {
return NULL;
+ }
if (!decoder->pulls_fd) {
ImagingSectionEnter(&cookie);
@@ -164,11 +169,13 @@ _setimage(ImagingDecoderObject* decoder, PyObject* args)
x0 = y0 = x1 = y1 = 0;
/* FIXME: should publish the ImagingType descriptor */
- if (!PyArg_ParseTuple(args, "O|(iiii)", &op, &x0, &y0, &x1, &y1))
+ if (!PyArg_ParseTuple(args, "O|(iiii)", &op, &x0, &y0, &x1, &y1)) {
return NULL;
+ }
im = PyImaging_AsImaging(op);
- if (!im)
+ if (!im) {
return NULL;
+ }
decoder->im = im;
@@ -203,8 +210,9 @@ _setimage(ImagingDecoderObject* decoder, PyObject* args)
}
/* malloc check ok, overflow checked above */
state->buffer = (UINT8*) malloc(state->bytes);
- if (!state->buffer)
+ if (!state->buffer) {
return PyErr_NoMemory();
+ }
}
/* Keep a reference to the image object, to make sure it doesn't
@@ -223,8 +231,9 @@ _setfd(ImagingDecoderObject* decoder, PyObject* args)
PyObject* fd;
ImagingCodecState state;
- if (!PyArg_ParseTuple(args, "O", &fd))
+ if (!PyArg_ParseTuple(args, "O", &fd)) {
return NULL;
+ }
state = &decoder->state;
@@ -330,8 +339,9 @@ PyImaging_BitDecoderNew(PyObject* self, PyObject* args)
int sign = 0;
int ystep = 1;
if (!PyArg_ParseTuple(args, "s|iiiii", &mode, &bits, &pad, &fill,
- &sign, &ystep))
+ &sign, &ystep)) {
return NULL;
+ }
if (strcmp(mode, "F") != 0) {
PyErr_SetString(PyExc_ValueError, "bad image mode");
@@ -339,8 +349,9 @@ PyImaging_BitDecoderNew(PyObject* self, PyObject* args)
}
decoder = PyImaging_DecoderNew(sizeof(BITSTATE));
- if (decoder == NULL)
+ if (decoder == NULL) {
return NULL;
+ }
decoder->decode = ImagingBitDecode;
@@ -368,8 +379,9 @@ PyImaging_BcnDecoderNew(PyObject* self, PyObject* args)
char* actual;
int n = 0;
int ystep = 1;
- if (!PyArg_ParseTuple(args, "s|ii", &mode, &n, &ystep))
+ if (!PyArg_ParseTuple(args, "s|ii", &mode, &n, &ystep)) {
return NULL;
+ }
switch (n) {
case 1: /* BC1: 565 color, 1-bit alpha */
@@ -394,8 +406,9 @@ PyImaging_BcnDecoderNew(PyObject* self, PyObject* args)
}
decoder = PyImaging_DecoderNew(0);
- if (decoder == NULL)
+ if (decoder == NULL) {
return NULL;
+ }
decoder->decode = ImagingBcnDecode;
decoder->state.state = n;
@@ -415,8 +428,9 @@ PyImaging_FliDecoderNew(PyObject* self, PyObject* args)
ImagingDecoderObject* decoder;
decoder = PyImaging_DecoderNew(0);
- if (decoder == NULL)
+ if (decoder == NULL) {
return NULL;
+ }
decoder->decode = ImagingFliDecode;
@@ -436,8 +450,9 @@ PyImaging_GifDecoderNew(PyObject* self, PyObject* args)
char* mode;
int bits = 8;
int interlace = 0;
- if (!PyArg_ParseTuple(args, "s|ii", &mode, &bits, &interlace))
+ if (!PyArg_ParseTuple(args, "s|ii", &mode, &bits, &interlace)) {
return NULL;
+ }
if (strcmp(mode, "L") != 0 && strcmp(mode, "P") != 0) {
PyErr_SetString(PyExc_ValueError, "bad image mode");
@@ -445,8 +460,9 @@ PyImaging_GifDecoderNew(PyObject* self, PyObject* args)
}
decoder = PyImaging_DecoderNew(sizeof(GIFDECODERSTATE));
- if (decoder == NULL)
+ if (decoder == NULL) {
return NULL;
+ }
decoder->decode = ImagingGifDecode;
@@ -468,15 +484,18 @@ PyImaging_HexDecoderNew(PyObject* self, PyObject* args)
char* mode;
char* rawmode;
- if (!PyArg_ParseTuple(args, "ss", &mode, &rawmode))
+ if (!PyArg_ParseTuple(args, "ss", &mode, &rawmode)) {
return NULL;
+ }
decoder = PyImaging_DecoderNew(0);
- if (decoder == NULL)
+ if (decoder == NULL) {
return NULL;
+ }
- if (get_unpacker(decoder, mode, rawmode) < 0)
+ if (get_unpacker(decoder, mode, rawmode) < 0) {
return NULL;
+ }
decoder->decode = ImagingHexDecode;
@@ -504,17 +523,20 @@ PyImaging_LibTiffDecoderNew(PyObject* self, PyObject* args)
int fp;
uint32 ifdoffset;
- if (! PyArg_ParseTuple(args, "sssiI", &mode, &rawmode, &compname, &fp, &ifdoffset))
+ if (! PyArg_ParseTuple(args, "sssiI", &mode, &rawmode, &compname, &fp, &ifdoffset)) {
return NULL;
+ }
TRACE(("new tiff decoder %s\n", compname));
decoder = PyImaging_DecoderNew(sizeof(TIFFSTATE));
- if (decoder == NULL)
+ if (decoder == NULL) {
return NULL;
+ }
- if (get_unpacker(decoder, mode, rawmode) < 0)
+ if (get_unpacker(decoder, mode, rawmode) < 0) {
return NULL;
+ }
if (! ImagingLibTiffInit(&decoder->state, fp, ifdoffset)) {
Py_DECREF(decoder);
@@ -541,15 +563,18 @@ PyImaging_PackbitsDecoderNew(PyObject* self, PyObject* args)
char* mode;
char* rawmode;
- if (!PyArg_ParseTuple(args, "ss", &mode, &rawmode))
+ if (!PyArg_ParseTuple(args, "ss", &mode, &rawmode)) {
return NULL;
+ }
decoder = PyImaging_DecoderNew(0);
- if (decoder == NULL)
+ if (decoder == NULL) {
return NULL;
+ }
- if (get_unpacker(decoder, mode, rawmode) < 0)
+ if (get_unpacker(decoder, mode, rawmode) < 0) {
return NULL;
+ }
decoder->decode = ImagingPackbitsDecode;
@@ -567,12 +592,14 @@ PyImaging_PcdDecoderNew(PyObject* self, PyObject* args)
ImagingDecoderObject* decoder;
decoder = PyImaging_DecoderNew(0);
- if (decoder == NULL)
+ if (decoder == NULL) {
return NULL;
+ }
/* Unpack from PhotoYCC to RGB */
- if (get_unpacker(decoder, "RGB", "YCC;P") < 0)
+ if (get_unpacker(decoder, "RGB", "YCC;P") < 0) {
return NULL;
+ }
decoder->decode = ImagingPcdDecode;
@@ -592,15 +619,18 @@ PyImaging_PcxDecoderNew(PyObject* self, PyObject* args)
char* mode;
char* rawmode;
int stride;
- if (!PyArg_ParseTuple(args, "ssi", &mode, &rawmode, &stride))
+ if (!PyArg_ParseTuple(args, "ssi", &mode, &rawmode, &stride)) {
return NULL;
+ }
decoder = PyImaging_DecoderNew(0);
- if (decoder == NULL)
+ if (decoder == NULL) {
return NULL;
+ }
- if (get_unpacker(decoder, mode, rawmode) < 0)
+ if (get_unpacker(decoder, mode, rawmode) < 0) {
return NULL;
+ }
decoder->state.bytes = stride;
@@ -623,15 +653,18 @@ PyImaging_RawDecoderNew(PyObject* self, PyObject* args)
char* rawmode;
int stride = 0;
int ystep = 1;
- if (!PyArg_ParseTuple(args, "ss|ii", &mode, &rawmode, &stride, &ystep))
+ if (!PyArg_ParseTuple(args, "ss|ii", &mode, &rawmode, &stride, &ystep)) {
return NULL;
+ }
decoder = PyImaging_DecoderNew(sizeof(RAWSTATE));
- if (decoder == NULL)
+ if (decoder == NULL) {
return NULL;
+ }
- if (get_unpacker(decoder, mode, rawmode) < 0)
+ if (get_unpacker(decoder, mode, rawmode) < 0) {
return NULL;
+ }
decoder->decode = ImagingRawDecode;
@@ -656,15 +689,18 @@ PyImaging_SgiRleDecoderNew(PyObject* self, PyObject* args)
char* rawmode;
int ystep = 1;
int bpc = 1;
- if (!PyArg_ParseTuple(args, "ss|ii", &mode, &rawmode, &ystep, &bpc))
+ if (!PyArg_ParseTuple(args, "ss|ii", &mode, &rawmode, &ystep, &bpc)) {
return NULL;
+ }
decoder = PyImaging_DecoderNew(sizeof(SGISTATE));
- if (decoder == NULL)
+ if (decoder == NULL) {
return NULL;
+ }
- if (get_unpacker(decoder, mode, rawmode) < 0)
+ if (get_unpacker(decoder, mode, rawmode) < 0) {
return NULL;
+ }
decoder->pulls_fd = 1;
decoder->decode = ImagingSgiRleDecode;
@@ -687,15 +723,18 @@ PyImaging_SunRleDecoderNew(PyObject* self, PyObject* args)
char* mode;
char* rawmode;
- if (!PyArg_ParseTuple(args, "ss", &mode, &rawmode))
+ if (!PyArg_ParseTuple(args, "ss", &mode, &rawmode)) {
return NULL;
+ }
decoder = PyImaging_DecoderNew(0);
- if (decoder == NULL)
+ if (decoder == NULL) {
return NULL;
+ }
- if (get_unpacker(decoder, mode, rawmode) < 0)
+ if (get_unpacker(decoder, mode, rawmode) < 0) {
return NULL;
+ }
decoder->decode = ImagingSunRleDecode;
@@ -716,15 +755,18 @@ PyImaging_TgaRleDecoderNew(PyObject* self, PyObject* args)
char* rawmode;
int ystep = 1;
int depth = 8;
- if (!PyArg_ParseTuple(args, "ss|ii", &mode, &rawmode, &ystep, &depth))
+ if (!PyArg_ParseTuple(args, "ss|ii", &mode, &rawmode, &ystep, &depth)) {
return NULL;
+ }
decoder = PyImaging_DecoderNew(0);
- if (decoder == NULL)
+ if (decoder == NULL) {
return NULL;
+ }
- if (get_unpacker(decoder, mode, rawmode) < 0)
+ if (get_unpacker(decoder, mode, rawmode) < 0) {
return NULL;
+ }
decoder->decode = ImagingTgaRleDecode;
@@ -745,11 +787,13 @@ PyImaging_XbmDecoderNew(PyObject* self, PyObject* args)
ImagingDecoderObject* decoder;
decoder = PyImaging_DecoderNew(0);
- if (decoder == NULL)
+ if (decoder == NULL) {
return NULL;
+ }
- if (get_unpacker(decoder, "1", "1;R") < 0)
+ if (get_unpacker(decoder, "1", "1;R") < 0) {
return NULL;
+ }
decoder->decode = ImagingXbmDecode;
@@ -773,15 +817,18 @@ PyImaging_ZipDecoderNew(PyObject* self, PyObject* args)
char* mode;
char* rawmode;
int interlaced = 0;
- if (!PyArg_ParseTuple(args, "ss|i", &mode, &rawmode, &interlaced))
+ if (!PyArg_ParseTuple(args, "ss|i", &mode, &rawmode, &interlaced)) {
return NULL;
+ }
decoder = PyImaging_DecoderNew(sizeof(ZIPSTATE));
- if (decoder == NULL)
+ if (decoder == NULL) {
return NULL;
+ }
- if (get_unpacker(decoder, mode, rawmode) < 0)
+ if (get_unpacker(decoder, mode, rawmode) < 0) {
return NULL;
+ }
decoder->decode = ImagingZipDecode;
decoder->cleanup = ImagingZipDecodeCleanup;
@@ -826,15 +873,18 @@ PyImaging_JpegDecoderNew(PyObject* self, PyObject* args)
int draft = 0;
if (!PyArg_ParseTuple(args, "ssz|ii", &mode, &rawmode, &jpegmode,
- &scale, &draft))
+ &scale, &draft)) {
return NULL;
+ }
- if (!jpegmode)
+ if (!jpegmode) {
jpegmode = "";
+ }
decoder = PyImaging_DecoderNew(sizeof(JPEGSTATE));
- if (decoder == NULL)
+ if (decoder == NULL) {
return NULL;
+ }
// libjpeg-turbo supports different output formats.
// We are choosing Pillow's native format (3 color bytes + 1 padding)
@@ -843,8 +893,9 @@ PyImaging_JpegDecoderNew(PyObject* self, PyObject* args)
rawmode = "RGBX";
}
- if (get_unpacker(decoder, mode, rawmode) < 0)
+ if (get_unpacker(decoder, mode, rawmode) < 0) {
return NULL;
+ }
decoder->decode = ImagingJpegDecode;
decoder->cleanup = ImagingJpegDecodeCleanup;
@@ -882,21 +933,24 @@ PyImaging_Jpeg2KDecoderNew(PyObject* self, PyObject* args)
PY_LONG_LONG length = -1;
if (!PyArg_ParseTuple(args, "ss|iiiL", &mode, &format,
- &reduce, &layers, &fd, &length))
+ &reduce, &layers, &fd, &length)) {
return NULL;
+ }
- if (strcmp(format, "j2k") == 0)
+ if (strcmp(format, "j2k") == 0) {
codec_format = OPJ_CODEC_J2K;
- else if (strcmp(format, "jpt") == 0)
+ } else if (strcmp(format, "jpt") == 0) {
codec_format = OPJ_CODEC_JPT;
- else if (strcmp(format, "jp2") == 0)
+ } else if (strcmp(format, "jp2") == 0) {
codec_format = OPJ_CODEC_JP2;
- else
+ } else {
return NULL;
+ }
decoder = PyImaging_DecoderNew(sizeof(JPEG2KDECODESTATE));
- if (decoder == NULL)
+ if (decoder == NULL) {
return NULL;
+ }
decoder->pulls_fd = 1;
decoder->decode = ImagingJpeg2KDecode;
diff --git a/src/display.c b/src/display.c
index 21869b26e..ce2cf7e98 100644
--- a/src/display.c
+++ b/src/display.c
@@ -28,7 +28,7 @@
#include "Imaging.h"
/* -------------------------------------------------------------------- */
-/* Windows DIB support */
+/* Windows DIB support */
#ifdef _WIN32
@@ -52,17 +52,19 @@ _new(const char* mode, int xsize, int ysize)
{
ImagingDisplayObject *display;
- if (PyType_Ready(&ImagingDisplayType) < 0)
+ if (PyType_Ready(&ImagingDisplayType) < 0) {
return NULL;
+ }
display = PyObject_New(ImagingDisplayObject, &ImagingDisplayType);
- if (display == NULL)
- return NULL;
+ if (display == NULL) {
+ return NULL;
+ }
display->dib = ImagingNewDIB(mode, xsize, ysize);
if (!display->dib) {
- Py_DECREF(display);
- return NULL;
+ Py_DECREF(display);
+ return NULL;
}
return display;
@@ -71,8 +73,9 @@ _new(const char* mode, int xsize, int ysize)
static void
_delete(ImagingDisplayObject* display)
{
- if (display->dib)
- ImagingDeleteDIB(display->dib);
+ if (display->dib) {
+ ImagingDeleteDIB(display->dib);
+ }
PyObject_Del(display);
}
@@ -80,8 +83,9 @@ static PyObject*
_expose(ImagingDisplayObject* display, PyObject* args)
{
HDC hdc;
- if (!PyArg_ParseTuple(args, F_HANDLE, &hdc))
- return NULL;
+ if (!PyArg_ParseTuple(args, F_HANDLE, &hdc)) {
+ return NULL;
+ }
ImagingExposeDIB(display->dib, hdc);
@@ -97,8 +101,9 @@ _draw(ImagingDisplayObject* display, PyObject* args)
int src[4];
if (!PyArg_ParseTuple(args, F_HANDLE "(iiii)(iiii)", &hdc,
dst+0, dst+1, dst+2, dst+3,
- src+0, src+1, src+2, src+3))
- return NULL;
+ src+0, src+1, src+2, src+3)) {
+ return NULL;
+ }
ImagingDrawDIB(display->dib, hdc, dst, src);
@@ -116,16 +121,20 @@ _paste(ImagingDisplayObject* display, PyObject* args)
PyObject* op;
int xy[4];
xy[0] = xy[1] = xy[2] = xy[3] = 0;
- if (!PyArg_ParseTuple(args, "O|(iiii)", &op, xy+0, xy+1, xy+2, xy+3))
- return NULL;
+ if (!PyArg_ParseTuple(args, "O|(iiii)", &op, xy+0, xy+1, xy+2, xy+3)) {
+ return NULL;
+ }
im = PyImaging_AsImaging(op);
- if (!im)
- return NULL;
+ if (!im) {
+ return NULL;
+ }
- if (xy[2] <= xy[0])
- xy[2] = xy[0] + im->xsize;
- if (xy[3] <= xy[1])
- xy[3] = xy[1] + im->ysize;
+ if (xy[2] <= xy[0]) {
+ xy[2] = xy[0] + im->xsize;
+ }
+ if (xy[3] <= xy[1]) {
+ xy[3] = xy[1] + im->ysize;
+ }
ImagingPasteDIB(display->dib, im, xy);
@@ -139,8 +148,9 @@ _query_palette(ImagingDisplayObject* display, PyObject* args)
HDC hdc;
int status;
- if (!PyArg_ParseTuple(args, F_HANDLE, &hdc))
- return NULL;
+ if (!PyArg_ParseTuple(args, F_HANDLE, &hdc)) {
+ return NULL;
+ }
status = ImagingQueryPaletteDIB(display->dib, hdc);
@@ -153,12 +163,13 @@ _getdc(ImagingDisplayObject* display, PyObject* args)
HWND window;
HDC dc;
- if (!PyArg_ParseTuple(args, F_HANDLE, &window))
- return NULL;
+ if (!PyArg_ParseTuple(args, F_HANDLE, &window)) {
+ return NULL;
+ }
dc = GetDC(window);
if (!dc) {
- PyErr_SetString(PyExc_IOError, "cannot create dc");
+ PyErr_SetString(PyExc_OSError, "cannot create dc");
return NULL;
}
@@ -171,8 +182,9 @@ _releasedc(ImagingDisplayObject* display, PyObject* args)
HWND window;
HDC dc;
- if (!PyArg_ParseTuple(args, F_HANDLE F_HANDLE, &window, &dc))
- return NULL;
+ if (!PyArg_ParseTuple(args, F_HANDLE F_HANDLE, &window, &dc)) {
+ return NULL;
+ }
ReleaseDC(window, dc);
@@ -186,8 +198,9 @@ _frombytes(ImagingDisplayObject* display, PyObject* args)
char* ptr;
int bytes;
- if (!PyArg_ParseTuple(args, "y#:frombytes", &ptr, &bytes))
+ if (!PyArg_ParseTuple(args, "y#:frombytes", &ptr, &bytes)) {
return NULL;
+ }
if (display->dib->ysize * display->dib->linesize != bytes) {
PyErr_SetString(PyExc_ValueError, "wrong size");
@@ -203,8 +216,9 @@ _frombytes(ImagingDisplayObject* display, PyObject* args)
static PyObject*
_tobytes(ImagingDisplayObject* display, PyObject* args)
{
- if (!PyArg_ParseTuple(args, ":tobytes"))
+ if (!PyArg_ParseTuple(args, ":tobytes")) {
return NULL;
+ }
return PyBytes_FromStringAndSize(
display->dib->bits, display->dib->ysize * display->dib->linesize
@@ -228,13 +242,13 @@ static struct PyMethodDef methods[] = {
static PyObject*
_getattr_mode(ImagingDisplayObject* self, void* closure)
{
- return Py_BuildValue("s", self->dib->mode);
+ return Py_BuildValue("s", self->dib->mode);
}
static PyObject*
_getattr_size(ImagingDisplayObject* self, void* closure)
{
- return Py_BuildValue("ii", self->dib->xsize, self->dib->ysize);
+ return Py_BuildValue("ii", self->dib->xsize, self->dib->ysize);
}
static struct PyGetSetDef getsetters[] = {
@@ -244,13 +258,13 @@ static struct PyGetSetDef getsetters[] = {
};
static PyTypeObject ImagingDisplayType = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "ImagingDisplay", /*tp_name*/
- sizeof(ImagingDisplayObject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)_delete, /*tp_dealloc*/
- 0, /*tp_print*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "ImagingDisplay", /*tp_name*/
+ sizeof(ImagingDisplayObject),/*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)_delete, /*tp_dealloc*/
+ 0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
@@ -284,12 +298,14 @@ PyImaging_DisplayWin32(PyObject* self, PyObject* args)
char *mode;
int xsize, ysize;
- if (!PyArg_ParseTuple(args, "s(ii)", &mode, &xsize, &ysize))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s(ii)", &mode, &xsize, &ysize)) {
+ return NULL;
+ }
display = _new(mode, xsize, ysize);
- if (display == NULL)
- return NULL;
+ if (display == NULL) {
+ return NULL;
+ }
return (PyObject*) display;
}
@@ -324,8 +340,9 @@ PyImaging_GrabScreenWin32(PyObject* self, PyObject* args)
HMODULE user32;
Func_SetThreadDpiAwarenessContext SetThreadDpiAwarenessContext_function;
- if (!PyArg_ParseTuple(args, "|ii", &includeLayeredWindows, &all_screens))
+ if (!PyArg_ParseTuple(args, "|ii", &includeLayeredWindows, &all_screens)) {
return NULL;
+ }
/* step 1: create a memory DC large enough to hold the
entire screen */
@@ -361,25 +378,30 @@ PyImaging_GrabScreenWin32(PyObject* self, PyObject* args)
FreeLibrary(user32);
bitmap = CreateCompatibleBitmap(screen, width, height);
- if (!bitmap)
+ if (!bitmap) {
goto error;
+ }
- if (!SelectObject(screen_copy, bitmap))
+ if (!SelectObject(screen_copy, bitmap)) {
goto error;
+ }
/* step 2: copy bits into memory DC bitmap */
rop = SRCCOPY;
- if (includeLayeredWindows)
+ if (includeLayeredWindows) {
rop |= CAPTUREBLT;
- if (!BitBlt(screen_copy, 0, 0, width, height, screen, x, y, rop))
+ }
+ if (!BitBlt(screen_copy, 0, 0, width, height, screen, x, y, rop)) {
goto error;
+ }
/* step 3: extract bits from bitmap */
buffer = PyBytes_FromStringAndSize(NULL, height * ((width*3 + 3) & -4));
- if (!buffer)
+ if (!buffer) {
return NULL;
+ }
core.bcSize = sizeof(core);
core.bcWidth = width;
@@ -387,8 +409,9 @@ PyImaging_GrabScreenWin32(PyObject* self, PyObject* args)
core.bcPlanes = 1;
core.bcBitCount = 24;
if (!GetDIBits(screen_copy, bitmap, 0, height, PyBytes_AS_STRING(buffer),
- (BITMAPINFO*) &core, DIB_RGB_COLORS))
+ (BITMAPINFO*) &core, DIB_RGB_COLORS)) {
goto error;
+ }
DeleteObject(bitmap);
DeleteDC(screen_copy);
@@ -397,7 +420,7 @@ PyImaging_GrabScreenWin32(PyObject* self, PyObject* args)
return Py_BuildValue("(ii)(ii)N", x, y, width, height, buffer);
error:
- PyErr_SetString(PyExc_IOError, "screen grab failed");
+ PyErr_SetString(PyExc_OSError, "screen grab failed");
DeleteDC(screen_copy);
DeleteDC(screen);
@@ -418,12 +441,15 @@ static BOOL CALLBACK list_windows_callback(HWND hwnd, LPARAM lParam)
title_size = GetWindowTextLength(hwnd);
if (title_size > 0) {
title = PyUnicode_FromStringAndSize(NULL, title_size);
- if (title)
+ if (title) {
GetWindowTextW(hwnd, PyUnicode_AS_UNICODE(title), title_size+1);
- } else
+ }
+ } else {
title = PyUnicode_FromString("");
- if (!title)
+ }
+ if (!title) {
return 0;
+ }
/* get bounding boxes */
GetClientRect(hwnd, &inner);
@@ -434,15 +460,17 @@ static BOOL CALLBACK list_windows_callback(HWND hwnd, LPARAM lParam)
inner.left, inner.top, inner.right, inner.bottom,
outer.left, outer.top, outer.right, outer.bottom
);
- if (!item)
+ if (!item) {
return 0;
+ }
status = PyList_Append(window_list, item);
Py_DECREF(item);
- if (status < 0)
+ if (status < 0) {
return 0;
+ }
return 1;
}
@@ -453,8 +481,9 @@ PyImaging_ListWindowsWin32(PyObject* self, PyObject* args)
PyObject* window_list;
window_list = PyList_New(0);
- if (!window_list)
+ if (!window_list) {
return NULL;
+ }
EnumWindows(list_windows_callback, (LPARAM) window_list);
@@ -556,8 +585,9 @@ windowCallback(HWND wnd, UINT message, WPARAM wParam, LPARAM lParam)
GetWindowLongPtr(wnd, sizeof(PyObject*));
current_threadstate = PyThreadState_Swap(NULL);
PyEval_RestoreThread(threadstate);
- } else
+ } else {
return DefWindowProc(wnd, message, wParam, lParam);
+ }
}
/* process message */
@@ -575,28 +605,31 @@ windowCallback(HWND wnd, UINT message, WPARAM wParam, LPARAM lParam)
ps.rcPaint.left, ps.rcPaint.top,
ps.rcPaint.right, ps.rcPaint.bottom
);
- if (result)
+ if (result) {
Py_DECREF(result);
- else
+ } else {
callback_error("window damage callback");
+ }
result = PyObject_CallFunction(
callback, "s" F_HANDLE "iiii", "clear", dc,
0, 0, rect.right-rect.left, rect.bottom-rect.top
);
- if (result)
+ if (result) {
Py_DECREF(result);
- else
+ } else {
callback_error("window clear callback");
+ }
result = PyObject_CallFunction(
callback, "s" F_HANDLE "iiii", "repair", dc,
0, 0, rect.right-rect.left, rect.bottom-rect.top
);
- if (result)
+ if (result) {
Py_DECREF(result);
- else
+ } else {
callback_error("window repair callback");
+ }
ReleaseDC(wnd, dc);
EndPaint(wnd, &ps);
@@ -610,17 +643,19 @@ windowCallback(HWND wnd, UINT message, WPARAM wParam, LPARAM lParam)
if (result) {
InvalidateRect(wnd, NULL, 1);
Py_DECREF(result);
- } else
+ } else {
callback_error("window resize callback");
+ }
break;
case WM_DESTROY:
/* destroy window */
result = PyObject_CallFunction(callback, "s", "destroy");
- if (result)
+ if (result) {
Py_DECREF(result);
- else
+ } else {
callback_error("window destroy callback");
+ }
Py_DECREF(callback);
break;
@@ -646,13 +681,16 @@ PyImaging_CreateWindowWin32(PyObject* self, PyObject* args)
char* title;
PyObject* callback;
int width = 0, height = 0;
- if (!PyArg_ParseTuple(args, "sO|ii", &title, &callback, &width, &height))
- return NULL;
+ if (!PyArg_ParseTuple(args, "sO|ii", &title, &callback, &width, &height)) {
+ return NULL;
+ }
- if (width <= 0)
+ if (width <= 0) {
width = CW_USEDEFAULT;
- if (height <= 0)
+ }
+ if (height <= 0) {
height = CW_USEDEFAULT;
+ }
/* register toplevel window class */
windowClass.style = CS_CLASSDC;
@@ -677,7 +715,7 @@ PyImaging_CreateWindowWin32(PyObject* self, PyObject* args)
);
if (!wnd) {
- PyErr_SetString(PyExc_IOError, "failed to create window");
+ PyErr_SetString(PyExc_OSError, "failed to create window");
return NULL;
}
@@ -731,8 +769,9 @@ PyImaging_DrawWmf(PyObject* self, PyObject* args)
int width, height;
int x0, y0, x1, y1;
if (!PyArg_ParseTuple(args, "y#(ii)(iiii):_load", &data, &datasize,
- &width, &height, &x0, &x1, &y0, &y1))
+ &width, &height, &x0, &x1, &y0, &y1)) {
return NULL;
+ }
/* step 1: copy metafile contents into METAFILE object */
@@ -755,7 +794,7 @@ PyImaging_DrawWmf(PyObject* self, PyObject* args)
}
if (!meta) {
- PyErr_SetString(PyExc_IOError, "cannot load metafile");
+ PyErr_SetString(PyExc_OSError, "cannot load metafile");
return NULL;
}
@@ -774,12 +813,12 @@ PyImaging_DrawWmf(PyObject* self, PyObject* args)
);
if (!bitmap) {
- PyErr_SetString(PyExc_IOError, "cannot create bitmap");
+ PyErr_SetString(PyExc_OSError, "cannot create bitmap");
goto error;
}
if (!SelectObject(dc, bitmap)) {
- PyErr_SetString(PyExc_IOError, "cannot select bitmap");
+ PyErr_SetString(PyExc_OSError, "cannot select bitmap");
goto error;
}
@@ -793,7 +832,7 @@ PyImaging_DrawWmf(PyObject* self, PyObject* args)
FillRect(dc, &rect, GetStockObject(WHITE_BRUSH));
if (!PlayEnhMetaFile(dc, meta, &rect)) {
- PyErr_SetString(PyExc_IOError, "cannot render metafile");
+ PyErr_SetString(PyExc_OSError, "cannot render metafile");
goto error;
}
@@ -806,8 +845,9 @@ PyImaging_DrawWmf(PyObject* self, PyObject* args)
error:
DeleteEnhMetaFile(meta);
- if (bitmap)
+ if (bitmap) {
DeleteObject(bitmap);
+ }
DeleteDC(dc);
@@ -817,7 +857,7 @@ error:
#endif /* _WIN32 */
/* -------------------------------------------------------------------- */
-/* X11 support */
+/* X11 support */
#ifdef HAVE_XCB
#include
@@ -838,14 +878,15 @@ PyImaging_GrabScreenX11(PyObject* self, PyObject* args)
xcb_generic_error_t* error;
PyObject* buffer = NULL;
- if (!PyArg_ParseTuple(args, "|z", &display_name))
+ if (!PyArg_ParseTuple(args, "|z", &display_name)) {
return NULL;
+ }
/* connect to X and get screen data */
connection = xcb_connect(display_name, &screen_number);
if (xcb_connection_has_error(connection)) {
- PyErr_Format(PyExc_IOError, "X connection failed: error %i", xcb_connection_has_error(connection));
+ PyErr_Format(PyExc_OSError, "X connection failed: error %i", xcb_connection_has_error(connection));
xcb_disconnect(connection);
return NULL;
}
@@ -860,7 +901,7 @@ PyImaging_GrabScreenX11(PyObject* self, PyObject* args)
if (screen == NULL || screen->root == 0) {
// this case is usually caught with "X connection failed: error 6" above
xcb_disconnect(connection);
- PyErr_SetString(PyExc_IOError, "X screen not found");
+ PyErr_SetString(PyExc_OSError, "X screen not found");
return NULL;
}
@@ -874,7 +915,7 @@ PyImaging_GrabScreenX11(PyObject* self, PyObject* args)
0, 0, width, height, 0x00ffffff),
&error);
if (reply == NULL) {
- PyErr_Format(PyExc_IOError, "X get_image failed: error %i (%i, %i, %i)",
+ PyErr_Format(PyExc_OSError, "X get_image failed: error %i (%i, %i, %i)",
error->error_code, error->major_code, error->minor_code, error->resource_id);
free(error);
xcb_disconnect(connection);
@@ -887,14 +928,15 @@ PyImaging_GrabScreenX11(PyObject* self, PyObject* args)
buffer = PyBytes_FromStringAndSize((char*)xcb_get_image_data(reply),
xcb_get_image_data_length(reply));
} else {
- PyErr_Format(PyExc_IOError, "unsupported bit depth: %i", reply->depth);
+ PyErr_Format(PyExc_OSError, "unsupported bit depth: %i", reply->depth);
}
free(reply);
xcb_disconnect(connection);
- if (!buffer)
+ if (!buffer) {
return NULL;
+ }
return Py_BuildValue("(ii)N", width, height, buffer);
}
diff --git a/src/encode.c b/src/encode.c
index 41ba124c4..1d463e9c4 100644
--- a/src/encode.c
+++ b/src/encode.c
@@ -55,12 +55,14 @@ PyImaging_EncoderNew(int contextsize)
ImagingEncoderObject *encoder;
void *context;
- if(PyType_Ready(&ImagingEncoderType) < 0)
+ if(PyType_Ready(&ImagingEncoderType) < 0) {
return NULL;
+ }
encoder = PyObject_New(ImagingEncoderObject, &ImagingEncoderType);
- if (encoder == NULL)
+ if (encoder == NULL) {
return NULL;
+ }
/* Clear the encoder state */
memset(&encoder->state, 0, sizeof(encoder->state));
@@ -73,8 +75,9 @@ PyImaging_EncoderNew(int contextsize)
(void) PyErr_NoMemory();
return NULL;
}
- } else
+ } else {
context = 0;
+ }
/* Initialize encoder context */
encoder->state.context = context;
@@ -93,8 +96,9 @@ PyImaging_EncoderNew(int contextsize)
static void
_dealloc(ImagingEncoderObject* encoder)
{
- if (encoder->cleanup)
+ if (encoder->cleanup) {
encoder->cleanup(&encoder->state);
+ }
free(encoder->state.buffer);
free(encoder->state.context);
Py_XDECREF(encoder->lock);
@@ -125,19 +129,22 @@ _encode(ImagingEncoderObject* encoder, PyObject* args)
Py_ssize_t bufsize = 16384;
- if (!PyArg_ParseTuple(args, "|n", &bufsize))
+ if (!PyArg_ParseTuple(args, "|n", &bufsize)) {
return NULL;
+ }
buf = PyBytes_FromStringAndSize(NULL, bufsize);
- if (!buf)
+ if (!buf) {
return NULL;
+ }
status = encoder->encode(encoder->im, &encoder->state,
(UINT8*) PyBytes_AsString(buf), bufsize);
/* adjust string length to avoid slicing in encoder */
- if (_PyBytes_Resize(&buf, (status > 0) ? status : 0) < 0)
+ if (_PyBytes_Resize(&buf, (status > 0) ? status : 0) < 0) {
return NULL;
+ }
result = Py_BuildValue("iiO", status, encoder->state.errcode, buf);
@@ -179,14 +186,16 @@ _encode_to_file(ImagingEncoderObject* encoder, PyObject* args)
Py_ssize_t fh;
Py_ssize_t bufsize = 16384;
- if (!PyArg_ParseTuple(args, "n|n", &fh, &bufsize))
+ if (!PyArg_ParseTuple(args, "n|n", &fh, &bufsize)) {
return NULL;
+ }
/* Allocate an encoder buffer */
/* malloc check ok, either constant int, or checked by PyArg_ParseTuple */
buf = (UINT8*) malloc(bufsize);
- if (!buf)
+ if (!buf) {
return PyErr_NoMemory();
+ }
ImagingSectionEnter(&cookie);
@@ -197,12 +206,13 @@ _encode_to_file(ImagingEncoderObject* encoder, PyObject* args)
status = encoder->encode(encoder->im, &encoder->state, buf, bufsize);
- if (status > 0)
+ if (status > 0) {
if (write(fh, buf, status) < 0) {
ImagingSectionLeave(&cookie);
free(buf);
- return PyErr_SetFromErrno(PyExc_IOError);
+ return PyErr_SetFromErrno(PyExc_OSError);
}
+ }
} while (encoder->state.errcode == 0);
@@ -228,11 +238,13 @@ _setimage(ImagingEncoderObject* encoder, PyObject* args)
x0 = y0 = x1 = y1 = 0;
/* FIXME: should publish the ImagingType descriptor */
- if (!PyArg_ParseTuple(args, "O|(nnnn)", &op, &x0, &y0, &x1, &y1))
+ if (!PyArg_ParseTuple(args, "O|(nnnn)", &op, &x0, &y0, &x1, &y1)) {
return NULL;
+ }
im = PyImaging_AsImaging(op);
- if (!im)
+ if (!im) {
return NULL;
+ }
encoder->im = im;
@@ -264,8 +276,9 @@ _setimage(ImagingEncoderObject* encoder, PyObject* args)
state->bytes = (state->bits * state->xsize+7)/8;
/* malloc check ok, overflow checked above */
state->buffer = (UINT8*) malloc(state->bytes);
- if (!state->buffer)
+ if (!state->buffer) {
return PyErr_NoMemory();
+ }
}
/* Keep a reference to the image object, to make sure it doesn't
@@ -284,8 +297,9 @@ _setfd(ImagingEncoderObject* encoder, PyObject* args)
PyObject* fd;
ImagingCodecState state;
- if (!PyArg_ParseTuple(args, "O", &fd))
+ if (!PyArg_ParseTuple(args, "O", &fd)) {
return NULL;
+ }
state = &encoder->state;
@@ -386,8 +400,9 @@ PyImaging_EpsEncoderNew(PyObject* self, PyObject* args)
ImagingEncoderObject* encoder;
encoder = PyImaging_EncoderNew(0);
- if (encoder == NULL)
+ if (encoder == NULL) {
return NULL;
+ }
encoder->encode = ImagingEpsEncode;
@@ -408,15 +423,18 @@ PyImaging_GifEncoderNew(PyObject* self, PyObject* args)
char *rawmode;
Py_ssize_t bits = 8;
Py_ssize_t interlace = 0;
- if (!PyArg_ParseTuple(args, "ss|nn", &mode, &rawmode, &bits, &interlace))
+ if (!PyArg_ParseTuple(args, "ss|nn", &mode, &rawmode, &bits, &interlace)) {
return NULL;
+ }
encoder = PyImaging_EncoderNew(sizeof(GIFENCODERSTATE));
- if (encoder == NULL)
+ if (encoder == NULL) {
return NULL;
+ }
- if (get_packer(encoder, mode, rawmode) < 0)
+ if (get_packer(encoder, mode, rawmode) < 0) {
return NULL;
+ }
encoder->encode = ImagingGifEncode;
@@ -473,15 +491,18 @@ PyImaging_RawEncoderNew(PyObject* self, PyObject* args)
Py_ssize_t stride = 0;
Py_ssize_t ystep = 1;
- if (!PyArg_ParseTuple(args, "ss|nn", &mode, &rawmode, &stride, &ystep))
+ if (!PyArg_ParseTuple(args, "ss|nn", &mode, &rawmode, &stride, &ystep)) {
return NULL;
+ }
encoder = PyImaging_EncoderNew(0);
- if (encoder == NULL)
+ if (encoder == NULL) {
return NULL;
+ }
- if (get_packer(encoder, mode, rawmode) < 0)
+ if (get_packer(encoder, mode, rawmode) < 0) {
return NULL;
+ }
encoder->encode = ImagingRawEncode;
@@ -505,15 +526,18 @@ PyImaging_TgaRleEncoderNew(PyObject* self, PyObject* args)
char *rawmode;
Py_ssize_t ystep = 1;
- if (!PyArg_ParseTuple(args, "ss|n", &mode, &rawmode, &ystep))
+ if (!PyArg_ParseTuple(args, "ss|n", &mode, &rawmode, &ystep)) {
return NULL;
+ }
encoder = PyImaging_EncoderNew(0);
- if (encoder == NULL)
+ if (encoder == NULL) {
return NULL;
+ }
- if (get_packer(encoder, mode, rawmode) < 0)
+ if (get_packer(encoder, mode, rawmode) < 0) {
return NULL;
+ }
encoder->encode = ImagingTgaRleEncode;
@@ -534,11 +558,13 @@ PyImaging_XbmEncoderNew(PyObject* self, PyObject* args)
ImagingEncoderObject* encoder;
encoder = PyImaging_EncoderNew(0);
- if (encoder == NULL)
+ if (encoder == NULL) {
return NULL;
+ }
- if (get_packer(encoder, "1", "1;R") < 0)
+ if (get_packer(encoder, "1", "1;R") < 0) {
return NULL;
+ }
encoder->encode = ImagingXbmEncode;
@@ -569,19 +595,22 @@ PyImaging_ZipEncoderNew(PyObject* self, PyObject* args)
if (!PyArg_ParseTuple(args, "ss|nnny#", &mode, &rawmode,
&optimize,
&compress_level, &compress_type,
- &dictionary, &dictionary_size))
+ &dictionary, &dictionary_size)) {
return NULL;
+ }
/* Copy to avoid referencing Python's memory */
if (dictionary && dictionary_size > 0) {
/* malloc check ok, size comes from PyArg_ParseTuple */
char* p = malloc(dictionary_size);
- if (!p)
+ if (!p) {
return PyErr_NoMemory();
+ }
memcpy(p, dictionary, dictionary_size);
dictionary = p;
- } else
+ } else {
dictionary = NULL;
+ }
encoder = PyImaging_EncoderNew(sizeof(ZIPSTATE));
if (encoder == NULL) {
@@ -597,9 +626,10 @@ PyImaging_ZipEncoderNew(PyObject* self, PyObject* args)
encoder->encode = ImagingZipEncode;
encoder->cleanup = ImagingZipEncodeCleanup;
- if (rawmode[0] == 'P')
+ if (rawmode[0] == 'P') {
/* disable filtering */
((ZIPSTATE*)encoder->state.context)->mode = ZIP_PNG_PALETTE;
+ }
((ZIPSTATE*)encoder->state.context)->optimize = optimize;
((ZIPSTATE*)encoder->state.context)->compress_level = compress_level;
@@ -675,11 +705,13 @@ PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args)
TRACE(("new tiff encoder %s fp: %d, filename: %s \n", compname, fp, filename));
encoder = PyImaging_EncoderNew(sizeof(TIFFSTATE));
- if (encoder == NULL)
+ if (encoder == NULL) {
return NULL;
+ }
- if (get_packer(encoder, mode, rawmode) < 0)
+ if (get_packer(encoder, mode, rawmode) < 0) {
return NULL;
+ }
if (! ImagingLibTiffEncodeInit(&encoder->state, filename, fp)) {
Py_DECREF(encoder);
@@ -1027,12 +1059,14 @@ PyImaging_JpegEncoderNew(PyObject* self, PyObject* args)
&mode, &rawmode, &quality,
&progressive, &smooth, &optimize, &streamtype,
&xdpi, &ydpi, &subsampling, &qtables, &extra, &extra_size,
- &rawExif, &rawExifLen))
+ &rawExif, &rawExifLen)) {
return NULL;
+ }
encoder = PyImaging_EncoderNew(sizeof(JPEGENCODERSTATE));
- if (encoder == NULL)
+ if (encoder == NULL) {
return NULL;
+ }
// libjpeg-turbo supports different output formats.
// We are choosing Pillow's native format (3 color bytes + 1 padding)
@@ -1041,8 +1075,9 @@ PyImaging_JpegEncoderNew(PyObject* self, PyObject* args)
rawmode = "RGBX";
}
- if (get_packer(encoder, mode, rawmode) < 0)
+ if (get_packer(encoder, mode, rawmode) < 0) {
return NULL;
+ }
// Freed in JpegEncode, Case 5
qarrays = get_qtables_arrays(qtables, &qtablesLen);
@@ -1050,24 +1085,29 @@ PyImaging_JpegEncoderNew(PyObject* self, PyObject* args)
if (extra && extra_size > 0) {
/* malloc check ok, length is from python parsearg */
char* p = malloc(extra_size); // Freed in JpegEncode, Case 5
- if (!p)
+ if (!p) {
return PyErr_NoMemory();
+ }
memcpy(p, extra, extra_size);
extra = p;
- } else
+ } else {
extra = NULL;
+ }
if (rawExif && rawExifLen > 0) {
/* malloc check ok, length is from python parsearg */
char* pp = malloc(rawExifLen); // Freed in JpegEncode, Case 5
if (!pp) {
- if (extra) free(extra);
+ if (extra) {
+ free(extra);
+ }
return PyErr_NoMemory();
}
memcpy(pp, rawExif, rawExifLen);
rawExif = pp;
- } else
+ } else {
rawExif = NULL;
+ }
encoder->encode = ImagingJpegEncode;
@@ -1095,7 +1135,7 @@ PyImaging_JpegEncoderNew(PyObject* self, PyObject* args)
/* -------------------------------------------------------------------- */
-/* JPEG 2000 */
+/* JPEG 2000 */
/* -------------------------------------------------------------------- */
#ifdef HAVE_OPENJPEG
@@ -1111,10 +1151,12 @@ j2k_decode_coord_tuple(PyObject *tuple, int *x, int *y)
*x = (int)PyLong_AsLong(PyTuple_GET_ITEM(tuple, 0));
*y = (int)PyLong_AsLong(PyTuple_GET_ITEM(tuple, 1));
- if (*x < 0)
+ if (*x < 0) {
*x = 0;
- if (*y < 0)
+ }
+ if (*y < 0) {
*y = 0;
+ }
}
}
@@ -1144,45 +1186,50 @@ PyImaging_Jpeg2KEncoderNew(PyObject *self, PyObject *args)
&quality_mode, &quality_layers, &num_resolutions,
&cblk_size, &precinct_size,
&irreversible, &progression, &cinema_mode,
- &fd))
+ &fd)) {
return NULL;
+ }
- if (strcmp (format, "j2k") == 0)
+ if (strcmp (format, "j2k") == 0) {
codec_format = OPJ_CODEC_J2K;
- else if (strcmp (format, "jpt") == 0)
+ } else if (strcmp (format, "jpt") == 0) {
codec_format = OPJ_CODEC_JPT;
- else if (strcmp (format, "jp2") == 0)
+ } else if (strcmp (format, "jp2") == 0) {
codec_format = OPJ_CODEC_JP2;
- else
+ } else {
return NULL;
+ }
- if (strcmp(progression, "LRCP") == 0)
+ if (strcmp(progression, "LRCP") == 0) {
prog_order = OPJ_LRCP;
- else if (strcmp(progression, "RLCP") == 0)
+ } else if (strcmp(progression, "RLCP") == 0) {
prog_order = OPJ_RLCP;
- else if (strcmp(progression, "RPCL") == 0)
+ } else if (strcmp(progression, "RPCL") == 0) {
prog_order = OPJ_RPCL;
- else if (strcmp(progression, "PCRL") == 0)
+ } else if (strcmp(progression, "PCRL") == 0) {
prog_order = OPJ_PCRL;
- else if (strcmp(progression, "CPRL") == 0)
+ } else if (strcmp(progression, "CPRL") == 0) {
prog_order = OPJ_CPRL;
- else
+ } else {
return NULL;
+ }
- if (strcmp(cinema_mode, "no") == 0)
+ if (strcmp(cinema_mode, "no") == 0) {
cine_mode = OPJ_OFF;
- else if (strcmp(cinema_mode, "cinema2k-24") == 0)
+ } else if (strcmp(cinema_mode, "cinema2k-24") == 0) {
cine_mode = OPJ_CINEMA2K_24;
- else if (strcmp(cinema_mode, "cinema2k-48") == 0)
+ } else if (strcmp(cinema_mode, "cinema2k-48") == 0) {
cine_mode = OPJ_CINEMA2K_48;
- else if (strcmp(cinema_mode, "cinema4k-24") == 0)
+ } else if (strcmp(cinema_mode, "cinema4k-24") == 0) {
cine_mode = OPJ_CINEMA4K_24;
- else
+ } else {
return NULL;
+ }
encoder = PyImaging_EncoderNew(sizeof(JPEG2KENCODESTATE));
- if (!encoder)
+ if (!encoder) {
return NULL;
+ }
encoder->encode = ImagingJpeg2KEncode;
encoder->cleanup = ImagingJpeg2KEncodeCleanup;
diff --git a/src/libImaging/Access.c b/src/libImaging/Access.c
index 15ffa11fc..755e2639a 100644
--- a/src/libImaging/Access.c
+++ b/src/libImaging/Access.c
@@ -22,8 +22,9 @@ static inline UINT32
hash(const char* mode)
{
UINT32 i = ACCESS_TABLE_HASH;
- while (*mode)
+ while (*mode) {
i = ((i<<5) + i) ^ (UINT8) *mode++;
+ }
return i % ACCESS_TABLE_SIZE;
}
@@ -149,10 +150,11 @@ get_pixel_32B(Imaging im, int x, int y, void* color)
static void
put_pixel(Imaging im, int x, int y, const void* color)
{
- if (im->image8)
+ if (im->image8) {
im->image8[y][x] = *((UINT8*) color);
- else
+ } else {
memcpy(&im->image32[y][x], color, sizeof(INT32));
+ }
}
static void
@@ -237,8 +239,9 @@ ImagingAccess
ImagingAccessNew(Imaging im)
{
ImagingAccess access = &access_table[hash(im->mode)];
- if (im->mode[0] != access->mode[0] || strcmp(im->mode, access->mode) != 0)
+ if (im->mode[0] != access->mode[0] || strcmp(im->mode, access->mode) != 0) {
return NULL;
+ }
return access;
}
diff --git a/src/libImaging/AlphaComposite.c b/src/libImaging/AlphaComposite.c
index a074334aa..20b1df9e5 100644
--- a/src/libImaging/AlphaComposite.c
+++ b/src/libImaging/AlphaComposite.c
@@ -33,19 +33,22 @@ ImagingAlphaComposite(Imaging imDst, Imaging imSrc)
if (!imDst || !imSrc ||
strcmp(imDst->mode, "RGBA") ||
imDst->type != IMAGING_TYPE_UINT8 ||
- imDst->bands != 4)
+ imDst->bands != 4) {
return ImagingError_ModeError();
+ }
if (strcmp(imDst->mode, imSrc->mode) ||
imDst->type != imSrc->type ||
imDst->bands != imSrc->bands ||
imDst->xsize != imSrc->xsize ||
- imDst->ysize != imSrc->ysize)
+ imDst->ysize != imSrc->ysize) {
return ImagingError_Mismatch();
+ }
imOut = ImagingNewDirty(imDst->mode, imDst->xsize, imDst->ysize);
- if (!imOut)
+ if (!imOut) {
return NULL;
+ }
for (y = 0; y < imDst->ysize; y++) {
rgba8* dst = (rgba8*) imDst->image[y];
diff --git a/src/libImaging/Bands.c b/src/libImaging/Bands.c
index 7fff04486..39ce5c49c 100644
--- a/src/libImaging/Bands.c
+++ b/src/libImaging/Bands.c
@@ -26,23 +26,28 @@ ImagingGetBand(Imaging imIn, int band)
int x, y;
/* Check arguments */
- if (!imIn || imIn->type != IMAGING_TYPE_UINT8)
+ if (!imIn || imIn->type != IMAGING_TYPE_UINT8) {
return (Imaging) ImagingError_ModeError();
+ }
- if (band < 0 || band >= imIn->bands)
+ if (band < 0 || band >= imIn->bands) {
return (Imaging) ImagingError_ValueError("band index out of range");
+ }
/* Shortcuts */
- if (imIn->bands == 1)
+ if (imIn->bands == 1) {
return ImagingCopy(imIn);
+ }
/* Special case for LXXA etc */
- if (imIn->bands == 2 && band == 1)
+ if (imIn->bands == 2 && band == 1) {
band = 3;
+ }
imOut = ImagingNewDirty("L", imIn->xsize, imIn->ysize);
- if (!imOut)
+ if (!imOut) {
return NULL;
+ }
/* Extract band from image */
for (y = 0; y < imIn->ysize; y++) {
@@ -173,24 +178,29 @@ ImagingPutBand(Imaging imOut, Imaging imIn, int band)
int x, y;
/* Check arguments */
- if (!imIn || imIn->bands != 1 || !imOut)
+ if (!imIn || imIn->bands != 1 || !imOut) {
return (Imaging) ImagingError_ModeError();
+ }
- if (band < 0 || band >= imOut->bands)
+ if (band < 0 || band >= imOut->bands) {
return (Imaging) ImagingError_ValueError("band index out of range");
+ }
if (imIn->type != imOut->type ||
imIn->xsize != imOut->xsize ||
- imIn->ysize != imOut->ysize)
+ imIn->ysize != imOut->ysize) {
return (Imaging) ImagingError_Mismatch();
+ }
/* Shortcuts */
- if (imOut->bands == 1)
+ if (imOut->bands == 1) {
return ImagingCopy2(imOut, imIn);
+ }
/* Special case for LXXA etc */
- if (imOut->bands == 2 && band == 1)
+ if (imOut->bands == 2 && band == 1) {
band = 3;
+ }
/* Insert band into image */
for (y = 0; y < imIn->ysize; y++) {
@@ -211,15 +221,18 @@ ImagingFillBand(Imaging imOut, int band, int color)
int x, y;
/* Check arguments */
- if (!imOut || imOut->type != IMAGING_TYPE_UINT8)
+ if (!imOut || imOut->type != IMAGING_TYPE_UINT8) {
return (Imaging) ImagingError_ModeError();
+ }
- if (band < 0 || band >= imOut->bands)
+ if (band < 0 || band >= imOut->bands) {
return (Imaging) ImagingError_ValueError("band index out of range");
+ }
/* Special case for LXXA etc */
- if (imOut->bands == 2 && band == 1)
+ if (imOut->bands == 2 && band == 1) {
band = 3;
+ }
color = CLIP8(color);
@@ -263,16 +276,18 @@ ImagingMerge(const char* mode, Imaging bands[4])
bandsCount = i;
imOut = ImagingNewDirty(mode, firstBand->xsize, firstBand->ysize);
- if ( ! imOut)
+ if ( ! imOut) {
return NULL;
+ }
if (imOut->bands != bandsCount) {
ImagingDelete(imOut);
return (Imaging) ImagingError_ValueError("wrong number of bands");
}
- if (imOut->bands == 1)
+ if (imOut->bands == 1) {
return ImagingCopy2(imOut, firstBand);
+ }
if (imOut->bands == 2) {
for (y = 0; y < imOut->ysize; y++) {
diff --git a/src/libImaging/BcnDecode.c b/src/libImaging/BcnDecode.c
index c2c4f21e7..f908a03ad 100644
--- a/src/libImaging/BcnDecode.c
+++ b/src/libImaging/BcnDecode.c
@@ -16,841 +16,852 @@
typedef struct {
- UINT8 r, g, b, a;
+ UINT8 r, g, b, a;
} rgba;
typedef struct {
- UINT8 l;
+ UINT8 l;
} lum;
typedef struct {
- FLOAT32 r, g, b;
+ FLOAT32 r, g, b;
} rgb32f;
typedef struct {
- UINT16 c0, c1;
- UINT32 lut;
+ UINT16 c0, c1;
+ UINT32 lut;
} bc1_color;
typedef struct {
- UINT8 a0, a1;
- UINT8 lut[6];
+ UINT8 a0, a1;
+ UINT8 lut[6];
} bc3_alpha;
#define LOAD16(p) \
- (p)[0] | ((p)[1] << 8)
+ (p)[0] | ((p)[1] << 8)
#define LOAD32(p) \
- (p)[0] | ((p)[1] << 8) | ((p)[2] << 16) | ((p)[3] << 24)
+ (p)[0] | ((p)[1] << 8) | ((p)[2] << 16) | ((p)[3] << 24)
static void bc1_color_load(bc1_color *dst, const UINT8 *src) {
- dst->c0 = LOAD16(src);
- dst->c1 = LOAD16(src + 2);
- dst->lut = LOAD32(src + 4);
+ dst->c0 = LOAD16(src);
+ dst->c1 = LOAD16(src + 2);
+ dst->lut = LOAD32(src + 4);
}
static void bc3_alpha_load(bc3_alpha *dst, const UINT8 *src) {
- memcpy(dst, src, sizeof(bc3_alpha));
+ memcpy(dst, src, sizeof(bc3_alpha));
}
static rgba decode_565(UINT16 x) {
- rgba c;
- int r, g, b;
- r = (x & 0xf800) >> 8;
- r |= r >> 5;
- c.r = r;
- g = (x & 0x7e0) >> 3;
- g |= g >> 6;
- c.g = g;
- b = (x & 0x1f) << 3;
- b |= b >> 5;
- c.b = b;
- c.a = 0xff;
- return c;
+ rgba c;
+ int r, g, b;
+ r = (x & 0xf800) >> 8;
+ r |= r >> 5;
+ c.r = r;
+ g = (x & 0x7e0) >> 3;
+ g |= g >> 6;
+ c.g = g;
+ b = (x & 0x1f) << 3;
+ b |= b >> 5;
+ c.b = b;
+ c.a = 0xff;
+ return c;
}
static void decode_bc1_color(rgba *dst, const UINT8 *src) {
- bc1_color col;
- rgba p[4];
- int n, cw;
- UINT16 r0, g0, b0, r1, g1, b1;
- bc1_color_load(&col, src);
+ bc1_color col;
+ rgba p[4];
+ int n, cw;
+ UINT16 r0, g0, b0, r1, g1, b1;
+ bc1_color_load(&col, src);
- p[0] = decode_565(col.c0);
- r0 = p[0].r;
- g0 = p[0].g;
- b0 = p[0].b;
- p[1] = decode_565(col.c1);
- r1 = p[1].r;
- g1 = p[1].g;
- b1 = p[1].b;
- if (col.c0 > col.c1) {
- p[2].r = (2*r0 + 1*r1) / 3;
- p[2].g = (2*g0 + 1*g1) / 3;
- p[2].b = (2*b0 + 1*b1) / 3;
- p[2].a = 0xff;
- p[3].r = (1*r0 + 2*r1) / 3;
- p[3].g = (1*g0 + 2*g1) / 3;
- p[3].b = (1*b0 + 2*b1) / 3;
- p[3].a = 0xff;
- } else {
- p[2].r = (r0 + r1) / 2;
- p[2].g = (g0 + g1) / 2;
- p[2].b = (b0 + b1) / 2;
- p[2].a = 0xff;
- p[3].r = 0;
- p[3].g = 0;
- p[3].b = 0;
- p[3].a = 0;
- }
- for (n = 0; n < 16; n++) {
- cw = 3 & (col.lut >> (2 * n));
- dst[n] = p[cw];
- }
+ p[0] = decode_565(col.c0);
+ r0 = p[0].r;
+ g0 = p[0].g;
+ b0 = p[0].b;
+ p[1] = decode_565(col.c1);
+ r1 = p[1].r;
+ g1 = p[1].g;
+ b1 = p[1].b;
+ if (col.c0 > col.c1) {
+ p[2].r = (2*r0 + 1*r1) / 3;
+ p[2].g = (2*g0 + 1*g1) / 3;
+ p[2].b = (2*b0 + 1*b1) / 3;
+ p[2].a = 0xff;
+ p[3].r = (1*r0 + 2*r1) / 3;
+ p[3].g = (1*g0 + 2*g1) / 3;
+ p[3].b = (1*b0 + 2*b1) / 3;
+ p[3].a = 0xff;
+ } else {
+ p[2].r = (r0 + r1) / 2;
+ p[2].g = (g0 + g1) / 2;
+ p[2].b = (b0 + b1) / 2;
+ p[2].a = 0xff;
+ p[3].r = 0;
+ p[3].g = 0;
+ p[3].b = 0;
+ p[3].a = 0;
+ }
+ for (n = 0; n < 16; n++) {
+ cw = 3 & (col.lut >> (2 * n));
+ dst[n] = p[cw];
+ }
}
static void decode_bc3_alpha(char *dst, const UINT8 *src, int stride, int o) {
- bc3_alpha b;
- UINT16 a0, a1;
- UINT8 a[8];
- int n, lut, aw;
- bc3_alpha_load(&b, src);
+ bc3_alpha b;
+ UINT16 a0, a1;
+ UINT8 a[8];
+ int n, lut, aw;
+ bc3_alpha_load(&b, src);
- a0 = b.a0;
- a1 = b.a1;
- a[0] = (UINT8)a0;
- a[1] = (UINT8)a1;
- if (a0 > a1) {
- a[2] = (6*a0 + 1*a1) / 7;
- a[3] = (5*a0 + 2*a1) / 7;
- a[4] = (4*a0 + 3*a1) / 7;
- a[5] = (3*a0 + 4*a1) / 7;
- a[6] = (2*a0 + 5*a1) / 7;
- a[7] = (1*a0 + 6*a1) / 7;
- } else {
- a[2] = (4*a0 + 1*a1) / 5;
- a[3] = (3*a0 + 2*a1) / 5;
- a[4] = (2*a0 + 3*a1) / 5;
- a[5] = (1*a0 + 4*a1) / 5;
- a[6] = 0;
- a[7] = 0xff;
- }
- lut = b.lut[0] | (b.lut[1] << 8) | (b.lut[2] << 16);
- for (n = 0; n < 8; n++) {
- aw = 7 & (lut >> (3 * n));
- dst[stride * n + o] = a[aw];
- }
- lut = b.lut[3] | (b.lut[4] << 8) | (b.lut[5] << 16);
- for (n = 0; n < 8; n++) {
- aw = 7 & (lut >> (3 * n));
- dst[stride * (8+n) + o] = a[aw];
- }
+ a0 = b.a0;
+ a1 = b.a1;
+ a[0] = (UINT8)a0;
+ a[1] = (UINT8)a1;
+ if (a0 > a1) {
+ a[2] = (6*a0 + 1*a1) / 7;
+ a[3] = (5*a0 + 2*a1) / 7;
+ a[4] = (4*a0 + 3*a1) / 7;
+ a[5] = (3*a0 + 4*a1) / 7;
+ a[6] = (2*a0 + 5*a1) / 7;
+ a[7] = (1*a0 + 6*a1) / 7;
+ } else {
+ a[2] = (4*a0 + 1*a1) / 5;
+ a[3] = (3*a0 + 2*a1) / 5;
+ a[4] = (2*a0 + 3*a1) / 5;
+ a[5] = (1*a0 + 4*a1) / 5;
+ a[6] = 0;
+ a[7] = 0xff;
+ }
+ lut = b.lut[0] | (b.lut[1] << 8) | (b.lut[2] << 16);
+ for (n = 0; n < 8; n++) {
+ aw = 7 & (lut >> (3 * n));
+ dst[stride * n + o] = a[aw];
+ }
+ lut = b.lut[3] | (b.lut[4] << 8) | (b.lut[5] << 16);
+ for (n = 0; n < 8; n++) {
+ aw = 7 & (lut >> (3 * n));
+ dst[stride * (8+n) + o] = a[aw];
+ }
}
static void decode_bc1_block(rgba *col, const UINT8* src) {
- decode_bc1_color(col, src);
+ decode_bc1_color(col, src);
}
static void decode_bc2_block(rgba *col, const UINT8* src) {
- int n, bitI, byI, av;
- decode_bc1_color(col, src + 8);
- for (n = 0; n < 16; n++) {
- bitI = n * 4;
- byI = bitI >> 3;
- av = 0xf & (src[byI] >> (bitI & 7));
- av = (av << 4) | av;
- col[n].a = av;
- }
+ int n, bitI, byI, av;
+ decode_bc1_color(col, src + 8);
+ for (n = 0; n < 16; n++) {
+ bitI = n * 4;
+ byI = bitI >> 3;
+ av = 0xf & (src[byI] >> (bitI & 7));
+ av = (av << 4) | av;
+ col[n].a = av;
+ }
}
static void decode_bc3_block(rgba *col, const UINT8* src) {
- decode_bc1_color(col, src + 8);
- decode_bc3_alpha((char *)col, src, sizeof(col[0]), 3);
+ decode_bc1_color(col, src + 8);
+ decode_bc3_alpha((char *)col, src, sizeof(col[0]), 3);
}
static void decode_bc4_block(lum *col, const UINT8* src) {
- decode_bc3_alpha((char *)col, src, sizeof(col[0]), 0);
+ decode_bc3_alpha((char *)col, src, sizeof(col[0]), 0);
}
static void decode_bc5_block(rgba *col, const UINT8* src) {
- decode_bc3_alpha((char *)col, src, sizeof(col[0]), 0);
- decode_bc3_alpha((char *)col, src + 8, sizeof(col[0]), 1);
+ decode_bc3_alpha((char *)col, src, sizeof(col[0]), 0);
+ decode_bc3_alpha((char *)col, src + 8, sizeof(col[0]), 1);
}
/* BC6 and BC7 are described here:
https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_texture_compression_bptc.txt */
static UINT8 get_bit(const UINT8* src, int bit) {
- int by = bit >> 3;
- bit &= 7;
- return (src[by] >> bit) & 1;
+ int by = bit >> 3;
+ bit &= 7;
+ return (src[by] >> bit) & 1;
}
static UINT8 get_bits(const UINT8* src, int bit, int count) {
- UINT8 v;
- int x;
- int by = bit >> 3;
- bit &= 7;
- if (!count) {
- return 0;
- }
- if (bit + count <= 8) {
- v = (src[by] >> bit) & ((1 << count) - 1);
- } else {
- x = src[by] | (src[by+1] << 8);
- v = (x >> bit) & ((1 << count) - 1);
- }
- return v;
+ UINT8 v;
+ int x;
+ int by = bit >> 3;
+ bit &= 7;
+ if (!count) {
+ return 0;
+ }
+ if (bit + count <= 8) {
+ v = (src[by] >> bit) & ((1 << count) - 1);
+ } else {
+ x = src[by] | (src[by+1] << 8);
+ v = (x >> bit) & ((1 << count) - 1);
+ }
+ return v;
}
/* BC7 */
typedef struct {
- char ns;
- char pb;
- char rb;
- char isb;
- char cb;
- char ab;
- char epb;
- char spb;
- char ib;
- char ib2;
+ char ns;
+ char pb;
+ char rb;
+ char isb;
+ char cb;
+ char ab;
+ char epb;
+ char spb;
+ char ib;
+ char ib2;
} bc7_mode_info;
static const bc7_mode_info bc7_modes[] = {
- {3, 4, 0, 0, 4, 0, 1, 0, 3, 0},
- {2, 6, 0, 0, 6, 0, 0, 1, 3, 0},
- {3, 6, 0, 0, 5, 0, 0, 0, 2, 0},
- {2, 6, 0, 0, 7, 0, 1, 0, 2, 0},
- {1, 0, 2, 1, 5, 6, 0, 0, 2, 3},
- {1, 0, 2, 0, 7, 8, 0, 0, 2, 2},
- {1, 0, 0, 0, 7, 7, 1, 0, 4, 0},
- {2, 6, 0, 0, 5, 5, 1, 0, 2, 0}
+ {3, 4, 0, 0, 4, 0, 1, 0, 3, 0},
+ {2, 6, 0, 0, 6, 0, 0, 1, 3, 0},
+ {3, 6, 0, 0, 5, 0, 0, 0, 2, 0},
+ {2, 6, 0, 0, 7, 0, 1, 0, 2, 0},
+ {1, 0, 2, 1, 5, 6, 0, 0, 2, 3},
+ {1, 0, 2, 0, 7, 8, 0, 0, 2, 2},
+ {1, 0, 0, 0, 7, 7, 1, 0, 4, 0},
+ {2, 6, 0, 0, 5, 5, 1, 0, 2, 0}
};
/* Subset indices:
Table.P2, 1 bit per index */
static const UINT16 bc7_si2[] = {
- 0xcccc, 0x8888, 0xeeee, 0xecc8, 0xc880, 0xfeec, 0xfec8, 0xec80,
- 0xc800, 0xffec, 0xfe80, 0xe800, 0xffe8, 0xff00, 0xfff0, 0xf000,
- 0xf710, 0x008e, 0x7100, 0x08ce, 0x008c, 0x7310, 0x3100, 0x8cce,
- 0x088c, 0x3110, 0x6666, 0x366c, 0x17e8, 0x0ff0, 0x718e, 0x399c,
- 0xaaaa, 0xf0f0, 0x5a5a, 0x33cc, 0x3c3c, 0x55aa, 0x9696, 0xa55a,
- 0x73ce, 0x13c8, 0x324c, 0x3bdc, 0x6996, 0xc33c, 0x9966, 0x0660,
- 0x0272, 0x04e4, 0x4e40, 0x2720, 0xc936, 0x936c, 0x39c6, 0x639c,
- 0x9336, 0x9cc6, 0x817e, 0xe718, 0xccf0, 0x0fcc, 0x7744, 0xee22};
+ 0xcccc, 0x8888, 0xeeee, 0xecc8, 0xc880, 0xfeec, 0xfec8, 0xec80,
+ 0xc800, 0xffec, 0xfe80, 0xe800, 0xffe8, 0xff00, 0xfff0, 0xf000,
+ 0xf710, 0x008e, 0x7100, 0x08ce, 0x008c, 0x7310, 0x3100, 0x8cce,
+ 0x088c, 0x3110, 0x6666, 0x366c, 0x17e8, 0x0ff0, 0x718e, 0x399c,
+ 0xaaaa, 0xf0f0, 0x5a5a, 0x33cc, 0x3c3c, 0x55aa, 0x9696, 0xa55a,
+ 0x73ce, 0x13c8, 0x324c, 0x3bdc, 0x6996, 0xc33c, 0x9966, 0x0660,
+ 0x0272, 0x04e4, 0x4e40, 0x2720, 0xc936, 0x936c, 0x39c6, 0x639c,
+ 0x9336, 0x9cc6, 0x817e, 0xe718, 0xccf0, 0x0fcc, 0x7744, 0xee22};
/* Table.P3, 2 bits per index */
static const UINT32 bc7_si3[] = {
- 0xaa685050, 0x6a5a5040, 0x5a5a4200, 0x5450a0a8,
- 0xa5a50000, 0xa0a05050, 0x5555a0a0, 0x5a5a5050,
- 0xaa550000, 0xaa555500, 0xaaaa5500, 0x90909090,
- 0x94949494, 0xa4a4a4a4, 0xa9a59450, 0x2a0a4250,
- 0xa5945040, 0x0a425054, 0xa5a5a500, 0x55a0a0a0,
- 0xa8a85454, 0x6a6a4040, 0xa4a45000, 0x1a1a0500,
- 0x0050a4a4, 0xaaa59090, 0x14696914, 0x69691400,
- 0xa08585a0, 0xaa821414, 0x50a4a450, 0x6a5a0200,
- 0xa9a58000, 0x5090a0a8, 0xa8a09050, 0x24242424,
- 0x00aa5500, 0x24924924, 0x24499224, 0x50a50a50,
- 0x500aa550, 0xaaaa4444, 0x66660000, 0xa5a0a5a0,
- 0x50a050a0, 0x69286928, 0x44aaaa44, 0x66666600,
- 0xaa444444, 0x54a854a8, 0x95809580, 0x96969600,
- 0xa85454a8, 0x80959580, 0xaa141414, 0x96960000,
- 0xaaaa1414, 0xa05050a0, 0xa0a5a5a0, 0x96000000,
- 0x40804080, 0xa9a8a9a8, 0xaaaaaa44, 0x2a4a5254};
+ 0xaa685050, 0x6a5a5040, 0x5a5a4200, 0x5450a0a8,
+ 0xa5a50000, 0xa0a05050, 0x5555a0a0, 0x5a5a5050,
+ 0xaa550000, 0xaa555500, 0xaaaa5500, 0x90909090,
+ 0x94949494, 0xa4a4a4a4, 0xa9a59450, 0x2a0a4250,
+ 0xa5945040, 0x0a425054, 0xa5a5a500, 0x55a0a0a0,
+ 0xa8a85454, 0x6a6a4040, 0xa4a45000, 0x1a1a0500,
+ 0x0050a4a4, 0xaaa59090, 0x14696914, 0x69691400,
+ 0xa08585a0, 0xaa821414, 0x50a4a450, 0x6a5a0200,
+ 0xa9a58000, 0x5090a0a8, 0xa8a09050, 0x24242424,
+ 0x00aa5500, 0x24924924, 0x24499224, 0x50a50a50,
+ 0x500aa550, 0xaaaa4444, 0x66660000, 0xa5a0a5a0,
+ 0x50a050a0, 0x69286928, 0x44aaaa44, 0x66666600,
+ 0xaa444444, 0x54a854a8, 0x95809580, 0x96969600,
+ 0xa85454a8, 0x80959580, 0xaa141414, 0x96960000,
+ 0xaaaa1414, 0xa05050a0, 0xa0a5a5a0, 0x96000000,
+ 0x40804080, 0xa9a8a9a8, 0xaaaaaa44, 0x2a4a5254};
/* Anchor indices:
Table.A2 */
static const char bc7_ai0[] = {
- 15,15,15,15,15,15,15,15,
- 15,15,15,15,15,15,15,15,
- 15, 2, 8, 2, 2, 8, 8,15,
- 2, 8, 2, 2, 8, 8, 2, 2,
- 15,15, 6, 8, 2, 8,15,15,
- 2, 8, 2, 2, 2,15,15, 6,
- 6, 2, 6, 8,15,15, 2, 2,
- 15,15,15,15,15, 2, 2,15};
+ 15,15,15,15,15,15,15,15,
+ 15,15,15,15,15,15,15,15,
+ 15, 2, 8, 2, 2, 8, 8,15,
+ 2, 8, 2, 2, 8, 8, 2, 2,
+ 15,15, 6, 8, 2, 8,15,15,
+ 2, 8, 2, 2, 2,15,15, 6,
+ 6, 2, 6, 8,15,15, 2, 2,
+ 15,15,15,15,15, 2, 2,15};
/* Table.A3a */
static const char bc7_ai1[] = {
- 3, 3,15,15, 8, 3,15,15,
- 8, 8, 6, 6, 6, 5, 3, 3,
- 3, 3, 8,15, 3, 3, 6,10,
- 5, 8, 8, 6, 8, 5,15,15,
- 8,15, 3, 5, 6,10, 8,15,
- 15, 3,15, 5,15,15,15,15,
- 3,15, 5, 5, 5, 8, 5,10,
- 5,10, 8,13,15,12, 3, 3};
+ 3, 3,15,15, 8, 3,15,15,
+ 8, 8, 6, 6, 6, 5, 3, 3,
+ 3, 3, 8,15, 3, 3, 6,10,
+ 5, 8, 8, 6, 8, 5,15,15,
+ 8,15, 3, 5, 6,10, 8,15,
+ 15, 3,15, 5,15,15,15,15,
+ 3,15, 5, 5, 5, 8, 5,10,
+ 5,10, 8,13,15,12, 3, 3};
/* Table.A3b */
static const char bc7_ai2[] = {
- 15, 8, 8, 3,15,15, 3, 8,
- 15,15,15,15,15,15,15, 8,
- 15, 8,15, 3,15, 8,15, 8,
- 3,15, 6,10,15,15,10, 8,
- 15, 3,15,10,10, 8, 9,10,
- 6,15, 8,15, 3, 6, 6, 8,
- 15, 3,15,15,15,15,15,15,
- 15,15,15,15, 3,15,15, 8};
+ 15, 8, 8, 3,15,15, 3, 8,
+ 15,15,15,15,15,15,15, 8,
+ 15, 8,15, 3,15, 8,15, 8,
+ 3,15, 6,10,15,15,10, 8,
+ 15, 3,15,10,10, 8, 9,10,
+ 6,15, 8,15, 3, 6, 6, 8,
+ 15, 3,15,15,15,15,15,15,
+ 15,15,15,15, 3,15,15, 8};
/* Interpolation weights */
static const char bc7_weights2[] = {0, 21, 43, 64};
static const char bc7_weights3[] = {0, 9, 18, 27, 37, 46, 55, 64};
static const char bc7_weights4[] = {
- 0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64};
+ 0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64};
static const char *bc7_get_weights(int n) {
- if (n == 2) {
- return bc7_weights2;
- }
- if (n == 3) {
- return bc7_weights3;
- }
- return bc7_weights4;
+ if (n == 2) {
+ return bc7_weights2;
+ }
+ if (n == 3) {
+ return bc7_weights3;
+ }
+ return bc7_weights4;
}
static int bc7_get_subset(int ns, int partition, int n) {
- if (ns == 2) {
- return 1 & (bc7_si2[partition] >> n);
- }
- if (ns == 3) {
- return 3 & (bc7_si3[partition] >> (2 * n));
- }
- return 0;
+ if (ns == 2) {
+ return 1 & (bc7_si2[partition] >> n);
+ }
+ if (ns == 3) {
+ return 3 & (bc7_si3[partition] >> (2 * n));
+ }
+ return 0;
}
static UINT8 expand_quantized(UINT8 v, int bits) {
- v = v << (8 - bits);
- return v | (v >> bits);
+ v = v << (8 - bits);
+ return v | (v >> bits);
}
static void bc7_lerp(rgba *dst, const rgba *e, int s0, int s1) {
- int t0 = 64 - s0;
- int t1 = 64 - s1;
- dst->r = (UINT8)((t0 * e[0].r + s0 * e[1].r + 32) >> 6);
- dst->g = (UINT8)((t0 * e[0].g + s0 * e[1].g + 32) >> 6);
- dst->b = (UINT8)((t0 * e[0].b + s0 * e[1].b + 32) >> 6);
- dst->a = (UINT8)((t1 * e[0].a + s1 * e[1].a + 32) >> 6);
+ int t0 = 64 - s0;
+ int t1 = 64 - s1;
+ dst->r = (UINT8)((t0 * e[0].r + s0 * e[1].r + 32) >> 6);
+ dst->g = (UINT8)((t0 * e[0].g + s0 * e[1].g + 32) >> 6);
+ dst->b = (UINT8)((t0 * e[0].b + s0 * e[1].b + 32) >> 6);
+ dst->a = (UINT8)((t1 * e[0].a + s1 * e[1].a + 32) >> 6);
}
static void decode_bc7_block(rgba *col, const UINT8* src) {
- rgba endpoints[6];
- int bit = 0, cibit, aibit;
- int mode = src[0];
- int i, j;
- int numep, cb, ab, ib, ib2, i0, i1, s;
- UINT8 index_sel, partition, rotation, val;
- const char *cw, *aw;
- const bc7_mode_info *info;
+ rgba endpoints[6];
+ int bit = 0, cibit, aibit;
+ int mode = src[0];
+ int i, j;
+ int numep, cb, ab, ib, ib2, i0, i1, s;
+ UINT8 index_sel, partition, rotation, val;
+ const char *cw, *aw;
+ const bc7_mode_info *info;
- /* mode is the number of unset bits before the first set bit: */
- if (!mode) {
- /* degenerate case when no bits set */
- for (i = 0; i < 16; i++) {
- col[i].r = col[i].g = col[i].b = 0;
- col[i].a = 255;
- }
- return;
- }
- while (!(mode & (1 << bit++))) ;
- mode = bit - 1;
- info = &bc7_modes[mode];
- /* color selection bits: {subset}{endpoint} */
- cb = info->cb;
- ab = info->ab;
- cw = bc7_get_weights(info->ib);
- aw = bc7_get_weights((ab && info->ib2) ? info->ib2 : info->ib);
+ /* mode is the number of unset bits before the first set bit: */
+ if (!mode) {
+ /* degenerate case when no bits set */
+ for (i = 0; i < 16; i++) {
+ col[i].r = col[i].g = col[i].b = 0;
+ col[i].a = 255;
+ }
+ return;
+ }
+ while (!(mode & (1 << bit++))) ;
+ mode = bit - 1;
+ info = &bc7_modes[mode];
+ /* color selection bits: {subset}{endpoint} */
+ cb = info->cb;
+ ab = info->ab;
+ cw = bc7_get_weights(info->ib);
+ aw = bc7_get_weights((ab && info->ib2) ? info->ib2 : info->ib);
#define LOAD(DST, N) \
- DST = get_bits(src, bit, N); \
- bit += N;
- LOAD(partition, info->pb);
- LOAD(rotation, info->rb);
- LOAD(index_sel, info->isb);
- numep = info->ns << 1;
+ DST = get_bits(src, bit, N); \
+ bit += N;
+ LOAD(partition, info->pb);
+ LOAD(rotation, info->rb);
+ LOAD(index_sel, info->isb);
+ numep = info->ns << 1;
- /* red */
- for (i = 0; i < numep; i++) {
- LOAD(val, cb);
- endpoints[i].r = val;
- }
+ /* red */
+ for (i = 0; i < numep; i++) {
+ LOAD(val, cb);
+ endpoints[i].r = val;
+ }
- /* green */
- for (i = 0; i < numep; i++) {
- LOAD(val, cb);
- endpoints[i].g = val;
- }
+ /* green */
+ for (i = 0; i < numep; i++) {
+ LOAD(val, cb);
+ endpoints[i].g = val;
+ }
- /* blue */
- for (i = 0; i < numep; i++) {
- LOAD(val, cb);
- endpoints[i].b = val;
- }
+ /* blue */
+ for (i = 0; i < numep; i++) {
+ LOAD(val, cb);
+ endpoints[i].b = val;
+ }
- /* alpha */
- for (i = 0; i < numep; i++) {
- if (ab) {
- LOAD(val, ab);
- } else {
- val = 255;
- }
- endpoints[i].a = val;
- }
+ /* alpha */
+ for (i = 0; i < numep; i++) {
+ if (ab) {
+ LOAD(val, ab);
+ } else {
+ val = 255;
+ }
+ endpoints[i].a = val;
+ }
- /* p-bits */
+ /* p-bits */
#define ASSIGN_P(x) x = (x << 1) | val
- if (info->epb) {
- /* per endpoint */
- cb++;
- if (ab) {
- ab++;
- }
- for (i = 0; i < numep; i++) {
- LOAD(val, 1);
- ASSIGN_P(endpoints[i].r);
- ASSIGN_P(endpoints[i].g);
- ASSIGN_P(endpoints[i].b);
- if (ab) {
- ASSIGN_P(endpoints[i].a);
- }
- }
- }
- if (info->spb) {
- /* per subset */
- cb++;
- if (ab) {
- ab++;
- }
- for (i = 0; i < numep; i+=2) {
- LOAD(val, 1);
- for (j = 0; j < 2; j++) {
- ASSIGN_P(endpoints[i+j].r);
- ASSIGN_P(endpoints[i+j].g);
- ASSIGN_P(endpoints[i+j].b);
- if (ab) {
- ASSIGN_P(endpoints[i+j].a);
- }
- }
- }
- }
+ if (info->epb) {
+ /* per endpoint */
+ cb++;
+ if (ab) {
+ ab++;
+ }
+ for (i = 0; i < numep; i++) {
+ LOAD(val, 1);
+ ASSIGN_P(endpoints[i].r);
+ ASSIGN_P(endpoints[i].g);
+ ASSIGN_P(endpoints[i].b);
+ if (ab) {
+ ASSIGN_P(endpoints[i].a);
+ }
+ }
+ }
+ if (info->spb) {
+ /* per subset */
+ cb++;
+ if (ab) {
+ ab++;
+ }
+ for (i = 0; i < numep; i+=2) {
+ LOAD(val, 1);
+ for (j = 0; j < 2; j++) {
+ ASSIGN_P(endpoints[i+j].r);
+ ASSIGN_P(endpoints[i+j].g);
+ ASSIGN_P(endpoints[i+j].b);
+ if (ab) {
+ ASSIGN_P(endpoints[i+j].a);
+ }
+ }
+ }
+ }
#undef ASSIGN_P
#define EXPAND(x, b) x = expand_quantized(x, b)
- for (i = 0; i < numep; i++) {
- EXPAND(endpoints[i].r, cb);
- EXPAND(endpoints[i].g, cb);
- EXPAND(endpoints[i].b, cb);
- if (ab) {
- EXPAND(endpoints[i].a, ab);
- }
- }
+ for (i = 0; i < numep; i++) {
+ EXPAND(endpoints[i].r, cb);
+ EXPAND(endpoints[i].g, cb);
+ EXPAND(endpoints[i].b, cb);
+ if (ab) {
+ EXPAND(endpoints[i].a, ab);
+ }
+ }
#undef EXPAND
#undef LOAD
- cibit = bit;
- aibit = cibit + 16 * info->ib - info->ns;
- for (i = 0; i < 16; i++) {
- s = bc7_get_subset(info->ns, partition, i) << 1;
- ib = info->ib;
- if (i == 0) {
- ib--;
- } else if (info->ns == 2) {
- if (i == bc7_ai0[partition]) {
- ib--;
- }
- } else if (info->ns == 3) {
- if (i == bc7_ai1[partition]) {
- ib--;
- } else if (i == bc7_ai2[partition]) {
- ib--;
- }
- }
- i0 = get_bits(src, cibit, ib);
- cibit += ib;
+ cibit = bit;
+ aibit = cibit + 16 * info->ib - info->ns;
+ for (i = 0; i < 16; i++) {
+ s = bc7_get_subset(info->ns, partition, i) << 1;
+ ib = info->ib;
+ if (i == 0) {
+ ib--;
+ } else if (info->ns == 2) {
+ if (i == bc7_ai0[partition]) {
+ ib--;
+ }
+ } else if (info->ns == 3) {
+ if (i == bc7_ai1[partition]) {
+ ib--;
+ } else if (i == bc7_ai2[partition]) {
+ ib--;
+ }
+ }
+ i0 = get_bits(src, cibit, ib);
+ cibit += ib;
- if (ab && info->ib2) {
- ib2 = info->ib2;
- if (ib2 && i == 0) {
- ib2--;
- }
- i1 = get_bits(src, aibit, ib2);
- aibit += ib2;
- if (index_sel) {
- bc7_lerp(&col[i], &endpoints[s], aw[i1], cw[i0]);
- } else {
- bc7_lerp(&col[i], &endpoints[s], cw[i0], aw[i1]);
- }
- } else {
- bc7_lerp(&col[i], &endpoints[s], cw[i0], cw[i0]);
- }
+ if (ab && info->ib2) {
+ ib2 = info->ib2;
+ if (ib2 && i == 0) {
+ ib2--;
+ }
+ i1 = get_bits(src, aibit, ib2);
+ aibit += ib2;
+ if (index_sel) {
+ bc7_lerp(&col[i], &endpoints[s], aw[i1], cw[i0]);
+ } else {
+ bc7_lerp(&col[i], &endpoints[s], cw[i0], aw[i1]);
+ }
+ } else {
+ bc7_lerp(&col[i], &endpoints[s], cw[i0], cw[i0]);
+ }
#define ROTATE(x, y) \
- val = x; \
- x = y; \
- y = val
- if (rotation == 1) {
- ROTATE(col[i].r, col[i].a);
- } else if (rotation == 2) {
- ROTATE(col[i].g, col[i].a);
- } else if (rotation == 3) {
- ROTATE(col[i].b, col[i].a);
- }
+ val = x; \
+ x = y; \
+ y = val
+ if (rotation == 1) {
+ ROTATE(col[i].r, col[i].a);
+ } else if (rotation == 2) {
+ ROTATE(col[i].g, col[i].a);
+ } else if (rotation == 3) {
+ ROTATE(col[i].b, col[i].a);
+ }
#undef ROTATE
- }
+ }
}
/* BC6 */
typedef struct {
- char ns; /* number of subsets (also called regions) */
- char tr; /* whether endpoints are delta-compressed */
- char pb; /* partition bits */
- char epb; /* endpoint bits */
- char rb; /* red bits (delta) */
- char gb; /* green bits (delta) */
- char bb; /* blue bits (delta) */
+ char ns; /* number of subsets (also called regions) */
+ char tr; /* whether endpoints are delta-compressed */
+ char pb; /* partition bits */
+ char epb; /* endpoint bits */
+ char rb; /* red bits (delta) */
+ char gb; /* green bits (delta) */
+ char bb; /* blue bits (delta) */
} bc6_mode_info;
static const bc6_mode_info bc6_modes[] = {
- // 00
- {2, 1, 5, 10, 5, 5, 5},
- // 01
- {2, 1, 5, 7, 6, 6, 6},
- // 10
- {2, 1, 5, 11, 5, 4, 4},
- {2, 1, 5, 11, 4, 5, 4},
- {2, 1, 5, 11, 4, 4, 5},
- {2, 1, 5, 9, 5, 5, 5},
- {2, 1, 5, 8, 6, 5, 5},
- {2, 1, 5, 8, 5, 6, 5},
- {2, 1, 5, 8, 5, 5, 6},
- {2, 0, 5, 6, 6, 6, 6},
- // 11
- {1, 0, 0, 10, 10, 10, 10},
- {1, 1, 0, 11, 9, 9, 9},
- {1, 1, 0, 12, 8, 8, 8},
- {1, 1, 0, 16, 4, 4, 4}
+ // 00
+ {2, 1, 5, 10, 5, 5, 5},
+ // 01
+ {2, 1, 5, 7, 6, 6, 6},
+ // 10
+ {2, 1, 5, 11, 5, 4, 4},
+ {2, 1, 5, 11, 4, 5, 4},
+ {2, 1, 5, 11, 4, 4, 5},
+ {2, 1, 5, 9, 5, 5, 5},
+ {2, 1, 5, 8, 6, 5, 5},
+ {2, 1, 5, 8, 5, 6, 5},
+ {2, 1, 5, 8, 5, 5, 6},
+ {2, 0, 5, 6, 6, 6, 6},
+ // 11
+ {1, 0, 0, 10, 10, 10, 10},
+ {1, 1, 0, 11, 9, 9, 9},
+ {1, 1, 0, 12, 8, 8, 8},
+ {1, 1, 0, 16, 4, 4, 4}
};
/* Table.F, encoded as a sequence of bit indices */
static const UINT8 bc6_bit_packings[][75] = {
- {116, 132, 176, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22,
- 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52,
- 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 172, 160, 161, 162, 163, 80,
- 81, 82, 83, 84, 173, 128, 129, 130, 131, 96, 97, 98, 99, 100, 174, 144,
- 145, 146, 147, 148, 175},
- {117, 164, 165, 0, 1, 2, 3, 4, 5, 6, 172, 173, 132, 16, 17, 18, 19, 20, 21,
- 22, 133, 174, 116, 32, 33, 34, 35, 36, 37, 38, 175, 177, 176, 48, 49, 50,
- 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163,
- 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144,
- 145, 146, 147, 148, 149},
- {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32,
- 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 10, 112, 113, 114,
- 115, 64, 65, 66, 67, 26, 172, 160, 161, 162, 163, 80, 81, 82, 83, 42, 173,
- 128, 129, 130, 131, 96, 97, 98, 99, 100, 174, 144, 145, 146, 147, 148,
- 175},
- {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32,
- 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 164, 112, 113, 114,
- 115, 64, 65, 66, 67, 68, 26, 160, 161, 162, 163, 80, 81, 82, 83, 42, 173,
- 128, 129, 130, 131, 96, 97, 98, 99, 172, 174, 144, 145, 146, 147, 116,
- 175},
- {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32,
- 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 132, 112, 113, 114,
- 115, 64, 65, 66, 67, 26, 172, 160, 161, 162, 163, 80, 81, 82, 83, 84, 42,
- 128, 129, 130, 131, 96, 97, 98, 99, 173, 174, 144, 145, 146, 147, 176,
- 175},
- {0, 1, 2, 3, 4, 5, 6, 7, 8, 132, 16, 17, 18, 19, 20, 21, 22, 23, 24, 116,
- 32, 33, 34, 35, 36, 37, 38, 39, 40, 176, 48, 49, 50, 51, 52, 164, 112, 113,
- 114, 115, 64, 65, 66, 67, 68, 172, 160, 161, 162, 163, 80, 81, 82, 83, 84,
- 173, 128, 129, 130, 131, 96, 97, 98, 99, 100, 174, 144, 145, 146, 147, 148,
- 175},
- {0, 1, 2, 3, 4, 5, 6, 7, 164, 132, 16, 17, 18, 19, 20, 21, 22, 23, 174, 116,
- 32, 33, 34, 35, 36, 37, 38, 39, 175, 176, 48, 49, 50, 51, 52, 53, 112, 113,
- 114, 115, 64, 65, 66, 67, 68, 172, 160, 161, 162, 163, 80, 81, 82, 83, 84,
- 173, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148,
- 149},
- {0, 1, 2, 3, 4, 5, 6, 7, 172, 132, 16, 17, 18, 19, 20, 21, 22, 23, 117, 116,
- 32, 33, 34, 35, 36, 37, 38, 39, 165, 176, 48, 49, 50, 51, 52, 164, 112,
- 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83,
- 84, 173, 128, 129, 130, 131, 96, 97, 98, 99, 100, 174, 144, 145, 146, 147,
- 148, 175},
- {0, 1, 2, 3, 4, 5, 6, 7, 173, 132, 16, 17, 18, 19, 20, 21, 22, 23, 133, 116,
- 32, 33, 34, 35, 36, 37, 38, 39, 177, 176, 48, 49, 50, 51, 52, 164, 112,
- 113, 114, 115, 64, 65, 66, 67, 68, 172, 160, 161, 162, 163, 80, 81, 82, 83,
- 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 174, 144, 145, 146, 147,
- 148, 175},
- {0, 1, 2, 3, 4, 5, 164, 172, 173, 132, 16, 17, 18, 19, 20, 21, 117, 133,
- 174, 116, 32, 33, 34, 35, 36, 37, 165, 175, 177, 176, 48, 49, 50, 51, 52,
- 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81,
- 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145,
- 146, 147, 148, 149},
- {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32,
- 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
- 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 80, 81, 82, 83, 84, 85, 86, 87, 88,
- 89},
- {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32,
- 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 10,
- 64, 65, 66, 67, 68, 69, 70, 71, 72, 26, 80, 81, 82, 83, 84, 85, 86, 87, 88,
- 42},
- {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32,
- 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 11, 10,
- 64, 65, 66, 67, 68, 69, 70, 71, 27, 26, 80, 81, 82, 83, 84, 85, 86, 87, 43,
- 42},
- {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32,
- 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 15, 14, 13, 12, 11, 10,
- 64, 65, 66, 67, 31, 30, 29, 28, 27, 26, 80, 81, 82, 83, 47, 46, 45, 44, 43,
- 42}};
+ {116, 132, 176, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22,
+ 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52,
+ 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 172, 160, 161, 162, 163, 80,
+ 81, 82, 83, 84, 173, 128, 129, 130, 131, 96, 97, 98, 99, 100, 174, 144,
+ 145, 146, 147, 148, 175},
+ {117, 164, 165, 0, 1, 2, 3, 4, 5, 6, 172, 173, 132, 16, 17, 18, 19, 20, 21,
+ 22, 133, 174, 116, 32, 33, 34, 35, 36, 37, 38, 175, 177, 176, 48, 49, 50,
+ 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163,
+ 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144,
+ 145, 146, 147, 148, 149},
+ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32,
+ 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 10, 112, 113, 114,
+ 115, 64, 65, 66, 67, 26, 172, 160, 161, 162, 163, 80, 81, 82, 83, 42, 173,
+ 128, 129, 130, 131, 96, 97, 98, 99, 100, 174, 144, 145, 146, 147, 148,
+ 175},
+ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32,
+ 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 164, 112, 113, 114,
+ 115, 64, 65, 66, 67, 68, 26, 160, 161, 162, 163, 80, 81, 82, 83, 42, 173,
+ 128, 129, 130, 131, 96, 97, 98, 99, 172, 174, 144, 145, 146, 147, 116,
+ 175},
+ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32,
+ 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 132, 112, 113, 114,
+ 115, 64, 65, 66, 67, 26, 172, 160, 161, 162, 163, 80, 81, 82, 83, 84, 42,
+ 128, 129, 130, 131, 96, 97, 98, 99, 173, 174, 144, 145, 146, 147, 176,
+ 175},
+ {0, 1, 2, 3, 4, 5, 6, 7, 8, 132, 16, 17, 18, 19, 20, 21, 22, 23, 24, 116,
+ 32, 33, 34, 35, 36, 37, 38, 39, 40, 176, 48, 49, 50, 51, 52, 164, 112, 113,
+ 114, 115, 64, 65, 66, 67, 68, 172, 160, 161, 162, 163, 80, 81, 82, 83, 84,
+ 173, 128, 129, 130, 131, 96, 97, 98, 99, 100, 174, 144, 145, 146, 147, 148,
+ 175},
+ {0, 1, 2, 3, 4, 5, 6, 7, 164, 132, 16, 17, 18, 19, 20, 21, 22, 23, 174, 116,
+ 32, 33, 34, 35, 36, 37, 38, 39, 175, 176, 48, 49, 50, 51, 52, 53, 112, 113,
+ 114, 115, 64, 65, 66, 67, 68, 172, 160, 161, 162, 163, 80, 81, 82, 83, 84,
+ 173, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148,
+ 149},
+ {0, 1, 2, 3, 4, 5, 6, 7, 172, 132, 16, 17, 18, 19, 20, 21, 22, 23, 117, 116,
+ 32, 33, 34, 35, 36, 37, 38, 39, 165, 176, 48, 49, 50, 51, 52, 164, 112,
+ 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83,
+ 84, 173, 128, 129, 130, 131, 96, 97, 98, 99, 100, 174, 144, 145, 146, 147,
+ 148, 175},
+ {0, 1, 2, 3, 4, 5, 6, 7, 173, 132, 16, 17, 18, 19, 20, 21, 22, 23, 133, 116,
+ 32, 33, 34, 35, 36, 37, 38, 39, 177, 176, 48, 49, 50, 51, 52, 164, 112,
+ 113, 114, 115, 64, 65, 66, 67, 68, 172, 160, 161, 162, 163, 80, 81, 82, 83,
+ 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 174, 144, 145, 146, 147,
+ 148, 175},
+ {0, 1, 2, 3, 4, 5, 164, 172, 173, 132, 16, 17, 18, 19, 20, 21, 117, 133,
+ 174, 116, 32, 33, 34, 35, 36, 37, 165, 175, 177, 176, 48, 49, 50, 51, 52,
+ 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81,
+ 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145,
+ 146, 147, 148, 149},
+ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32,
+ 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
+ 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 80, 81, 82, 83, 84, 85, 86, 87, 88,
+ 89},
+ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32,
+ 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 10,
+ 64, 65, 66, 67, 68, 69, 70, 71, 72, 26, 80, 81, 82, 83, 84, 85, 86, 87, 88,
+ 42},
+ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32,
+ 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 11, 10,
+ 64, 65, 66, 67, 68, 69, 70, 71, 27, 26, 80, 81, 82, 83, 84, 85, 86, 87, 43,
+ 42},
+ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32,
+ 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 15, 14, 13, 12, 11, 10,
+ 64, 65, 66, 67, 31, 30, 29, 28, 27, 26, 80, 81, 82, 83, 47, 46, 45, 44, 43,
+ 42}};
static void bc6_sign_extend(UINT16 *v, int prec) {
- int x = *v;
- if (x & (1 << (prec - 1))) {
- x |= -1 << prec;
- }
- *v = (UINT16)x;
+ int x = *v;
+ if (x & (1 << (prec - 1))) {
+ x |= -1 << prec;
+ }
+ *v = (UINT16)x;
}
static int bc6_unquantize(UINT16 v, int prec, int sign) {
- int s = 0;
- int x;
- if (!sign) {
- x = v;
- if (prec >= 15) return x;
- if (x == 0) return 0;
- if (x == ((1 << prec) - 1)) {
- return 0xffff;
- }
- return ((x << 15) + 0x4000) >> (prec - 1);
- } else {
- x = (INT16)v;
- if (prec >= 16) return x;
- if (x < 0) {
- s = 1;
- x = -x;
- }
+ int s = 0;
+ int x;
+ if (!sign) {
+ x = v;
+ if (prec >= 15) {
+ return x;
+ }
+ if (x == 0) {
+ return 0;
+ }
+ if (x == ((1 << prec) - 1)) {
+ return 0xffff;
+ }
+ return ((x << 15) + 0x4000) >> (prec - 1);
+ } else {
+ x = (INT16)v;
+ if (prec >= 16) {
+ return x;
+ }
+ if (x < 0) {
+ s = 1;
+ x = -x;
+ }
- if (x != 0) {
- if (x >= ((1 << (prec - 1)) - 1)) {
- x = 0x7fff;
- } else {
- x = ((x << 15) + 0x4000) >> (prec - 1);
- }
- }
+ if (x != 0) {
+ if (x >= ((1 << (prec - 1)) - 1)) {
+ x = 0x7fff;
+ } else {
+ x = ((x << 15) + 0x4000) >> (prec - 1);
+ }
+ }
- if (s) {
- return -x;
- }
- return x;
- }
+ if (s) {
+ return -x;
+ }
+ return x;
+ }
}
static float half_to_float(UINT16 h) {
- /* https://gist.github.com/rygorous/2144712 */
- union {
- UINT32 u;
- float f;
- } o, m;
- m.u = 0x77800000;
- o.u = (h & 0x7fff) << 13;
- o.f *= m.f;
- m.u = 0x47800000;
- if (o.f >= m.f) {
- o.u |= 255 << 23;
- }
- o.u |= (h & 0x8000) << 16;
- return o.f;
+ /* https://gist.github.com/rygorous/2144712 */
+ union {
+ UINT32 u;
+ float f;
+ } o, m;
+ m.u = 0x77800000;
+ o.u = (h & 0x7fff) << 13;
+ o.f *= m.f;
+ m.u = 0x47800000;
+ if (o.f >= m.f) {
+ o.u |= 255 << 23;
+ }
+ o.u |= (h & 0x8000) << 16;
+ return o.f;
}
static float bc6_finalize(int v, int sign) {
- if (sign) {
- if (v < 0) {
- v = ((-v) * 31) / 32;
- return half_to_float((UINT16)(0x8000 | v));
- } else {
- return half_to_float((UINT16)((v * 31) / 32));
- }
- } else {
- return half_to_float((UINT16)((v * 31) / 64));
- }
+ if (sign) {
+ if (v < 0) {
+ v = ((-v) * 31) / 32;
+ return half_to_float((UINT16)(0x8000 | v));
+ } else {
+ return half_to_float((UINT16)((v * 31) / 32));
+ }
+ } else {
+ return half_to_float((UINT16)((v * 31) / 64));
+ }
}
static void bc6_lerp(rgb32f *col, int *e0, int *e1, int s, int sign) {
- int r, g, b;
- int t = 64 - s;
- r = (e0[0] * t + e1[0] * s) >> 6;
- g = (e0[1] * t + e1[1] * s) >> 6;
- b = (e0[2] * t + e1[2] * s) >> 6;
- col->r = bc6_finalize(r, sign);
- col->g = bc6_finalize(g, sign);
- col->b = bc6_finalize(b, sign);
+ int r, g, b;
+ int t = 64 - s;
+ r = (e0[0] * t + e1[0] * s) >> 6;
+ g = (e0[1] * t + e1[1] * s) >> 6;
+ b = (e0[2] * t + e1[2] * s) >> 6;
+ col->r = bc6_finalize(r, sign);
+ col->g = bc6_finalize(g, sign);
+ col->b = bc6_finalize(b, sign);
}
static void decode_bc6_block(rgb32f *col, const UINT8* src, int sign) {
- UINT16 endpoints[12]; /* storage for r0, g0, b0, r1, ... */
- int ueps[12];
- int i, i0, ib2, di, dw, mask, numep, s;
- UINT8 partition;
- const bc6_mode_info *info;
- const char *cw;
- int bit = 5;
- int epbits = 75;
- int ib = 3;
- int mode = src[0] & 0x1f;
- if ((mode & 3) == 0 || (mode & 3) == 1) {
- mode &= 3;
- bit = 2;
- } else if ((mode & 3) == 2) {
- mode = 2 + (mode >> 2);
- epbits = 72;
- } else {
- mode = 10 + (mode >> 2);
- epbits = 60;
- ib = 4;
- }
- if (mode >= 14) {
- /* invalid block */
- memset(col, 0, 16 * sizeof(col[0]));
- return;
- }
- info = &bc6_modes[mode];
- cw = bc7_get_weights(ib);
- numep = info->ns == 2 ? 12 : 6;
- for (i = 0; i < 12; i++) {
- endpoints[i] = 0;
- }
- for (i = 0; i < epbits; i++) {
- di = bc6_bit_packings[mode][i];
- dw = di >> 4;
- di &= 15;
- endpoints[dw] |= (UINT16)get_bit(src, bit + i) << di;
- }
- bit += epbits;
- partition = get_bits(src, bit, info->pb);
- bit += info->pb;
- mask = (1 << info->epb) - 1;
- if (sign) { /* sign-extend e0 if signed */
- bc6_sign_extend(&endpoints[0], info->epb);
- bc6_sign_extend(&endpoints[1], info->epb);
- bc6_sign_extend(&endpoints[2], info->epb);
- }
- if (sign || info->tr) { /* sign-extend e1,2,3 if signed or deltas */
- for (i = 3; i < numep; i += 3) {
- bc6_sign_extend(&endpoints[i+0], info->rb);
- bc6_sign_extend(&endpoints[i+1], info->gb);
- bc6_sign_extend(&endpoints[i+2], info->bb);
- }
- }
- if (info->tr) { /* apply deltas */
- for (i = 3; i < numep; i++) {
- endpoints[i] = (endpoints[i] + endpoints[0]) & mask;
- }
- if (sign) {
- for (i = 3; i < numep; i += 3) {
- bc6_sign_extend(&endpoints[i+0], info->rb);
- bc6_sign_extend(&endpoints[i+1], info->gb);
- bc6_sign_extend(&endpoints[i+2], info->bb);
- }
- }
- }
- for (i = 0; i < numep; i++) {
- ueps[i] = bc6_unquantize(endpoints[i], info->epb, sign);
- }
- for (i = 0; i < 16; i++) {
- s = bc7_get_subset(info->ns, partition, i) * 6;
- ib2 = ib;
- if (i == 0) {
- ib2--;
- } else if (info->ns == 2) {
- if (i == bc7_ai0[partition]) {
- ib2--;
- }
- }
- i0 = get_bits(src, bit, ib2);
- bit += ib2;
+ UINT16 endpoints[12]; /* storage for r0, g0, b0, r1, ... */
+ int ueps[12];
+ int i, i0, ib2, di, dw, mask, numep, s;
+ UINT8 partition;
+ const bc6_mode_info *info;
+ const char *cw;
+ int bit = 5;
+ int epbits = 75;
+ int ib = 3;
+ int mode = src[0] & 0x1f;
+ if ((mode & 3) == 0 || (mode & 3) == 1) {
+ mode &= 3;
+ bit = 2;
+ } else if ((mode & 3) == 2) {
+ mode = 2 + (mode >> 2);
+ epbits = 72;
+ } else {
+ mode = 10 + (mode >> 2);
+ epbits = 60;
+ ib = 4;
+ }
+ if (mode >= 14) {
+ /* invalid block */
+ memset(col, 0, 16 * sizeof(col[0]));
+ return;
+ }
+ info = &bc6_modes[mode];
+ cw = bc7_get_weights(ib);
+ numep = info->ns == 2 ? 12 : 6;
+ for (i = 0; i < 12; i++) {
+ endpoints[i] = 0;
+ }
+ for (i = 0; i < epbits; i++) {
+ di = bc6_bit_packings[mode][i];
+ dw = di >> 4;
+ di &= 15;
+ endpoints[dw] |= (UINT16)get_bit(src, bit + i) << di;
+ }
+ bit += epbits;
+ partition = get_bits(src, bit, info->pb);
+ bit += info->pb;
+ mask = (1 << info->epb) - 1;
+ if (sign) { /* sign-extend e0 if signed */
+ bc6_sign_extend(&endpoints[0], info->epb);
+ bc6_sign_extend(&endpoints[1], info->epb);
+ bc6_sign_extend(&endpoints[2], info->epb);
+ }
+ if (sign || info->tr) { /* sign-extend e1,2,3 if signed or deltas */
+ for (i = 3; i < numep; i += 3) {
+ bc6_sign_extend(&endpoints[i+0], info->rb);
+ bc6_sign_extend(&endpoints[i+1], info->gb);
+ bc6_sign_extend(&endpoints[i+2], info->bb);
+ }
+ }
+ if (info->tr) { /* apply deltas */
+ for (i = 3; i < numep; i++) {
+ endpoints[i] = (endpoints[i] + endpoints[0]) & mask;
+ }
+ if (sign) {
+ for (i = 3; i < numep; i += 3) {
+ bc6_sign_extend(&endpoints[i+0], info->rb);
+ bc6_sign_extend(&endpoints[i+1], info->gb);
+ bc6_sign_extend(&endpoints[i+2], info->bb);
+ }
+ }
+ }
+ for (i = 0; i < numep; i++) {
+ ueps[i] = bc6_unquantize(endpoints[i], info->epb, sign);
+ }
+ for (i = 0; i < 16; i++) {
+ s = bc7_get_subset(info->ns, partition, i) * 6;
+ ib2 = ib;
+ if (i == 0) {
+ ib2--;
+ } else if (info->ns == 2) {
+ if (i == bc7_ai0[partition]) {
+ ib2--;
+ }
+ }
+ i0 = get_bits(src, bit, ib2);
+ bit += ib2;
- bc6_lerp(&col[i], &ueps[s], &ueps[s+3], cw[i0], sign);
- }
+ bc6_lerp(&col[i], &ueps[s], &ueps[s+3], cw[i0], sign);
+ }
}
static void put_block(Imaging im, ImagingCodecState state, const char *col, int sz, int C) {
- int width = state->xsize;
- int height = state->ysize;
- int xmax = width + state->xoff;
- int ymax = height + state->yoff;
- int j, i, y, x;
- char *dst;
- for (j = 0; j < 4; j++) {
- y = state->y + j;
- if (C) {
- if (y >= height) {
- continue;
- }
- if (state->ystep < 0) {
- y = state->yoff + ymax - y - 1;
- }
- dst = im->image[y];
- for (i = 0; i < 4; i++) {
- x = state->x + i;
- if (x >= width) {
- continue;
- }
- memcpy(dst + sz*x, col + sz*(j*4 + i), sz);
- }
- } else {
- if (state->ystep < 0) {
- y = state->yoff + ymax - y - 1;
- }
- x = state->x;
- dst = im->image[y] + sz*x;
- memcpy(dst, col + sz*(j*4), 4 * sz);
- }
- }
- state->x += 4;
- if (state->x >= xmax) {
- state->y += 4;
- state->x = state->xoff;
- }
+ int width = state->xsize;
+ int height = state->ysize;
+ int xmax = width + state->xoff;
+ int ymax = height + state->yoff;
+ int j, i, y, x;
+ char *dst;
+ for (j = 0; j < 4; j++) {
+ y = state->y + j;
+ if (C) {
+ if (y >= height) {
+ continue;
+ }
+ if (state->ystep < 0) {
+ y = state->yoff + ymax - y - 1;
+ }
+ dst = im->image[y];
+ for (i = 0; i < 4; i++) {
+ x = state->x + i;
+ if (x >= width) {
+ continue;
+ }
+ memcpy(dst + sz*x, col + sz*(j*4 + i), sz);
+ }
+ } else {
+ if (state->ystep < 0) {
+ y = state->yoff + ymax - y - 1;
+ }
+ x = state->x;
+ dst = im->image[y] + sz*x;
+ memcpy(dst, col + sz*(j*4), 4 * sz);
+ }
+ }
+ state->x += 4;
+ if (state->x >= xmax) {
+ state->y += 4;
+ state->x = state->xoff;
+ }
}
static int decode_bcn(Imaging im, ImagingCodecState state, const UINT8* src, int bytes, int N, int C) {
- int ymax = state->ysize + state->yoff;
- const UINT8 *ptr = src;
- switch (N) {
+ int ymax = state->ysize + state->yoff;
+ const UINT8 *ptr = src;
+ switch (N) {
#define DECODE_LOOP(NN, SZ, TY, ...) \
- case NN: \
- while (bytes >= SZ) { \
- TY col[16]; \
- memset(col, 0, 16 * sizeof(col[0])); \
- decode_bc##NN##_block(col, ptr); \
- put_block(im, state, (const char *)col, sizeof(col[0]), C); \
- ptr += SZ; \
- bytes -= SZ; \
- if (state->y >= ymax) return -1; \
- } \
- break
- DECODE_LOOP(1, 8, rgba);
- DECODE_LOOP(2, 16, rgba);
- DECODE_LOOP(3, 16, rgba);
- DECODE_LOOP(4, 8, lum);
- DECODE_LOOP(5, 16, rgba);
- case 6:
- while (bytes >= 16) {
- rgb32f col[16];
- decode_bc6_block(col, ptr, (state->state >> 4) & 1);
- put_block(im, state, (const char *)col, sizeof(col[0]), C);
- ptr += 16;
- bytes -= 16;
- if (state->y >= ymax) return -1; \
- }
- break;
- DECODE_LOOP(7, 16, rgba);
+ case NN: \
+ while (bytes >= SZ) { \
+ TY col[16]; \
+ memset(col, 0, 16 * sizeof(col[0])); \
+ decode_bc##NN##_block(col, ptr); \
+ put_block(im, state, (const char *)col, sizeof(col[0]), C); \
+ ptr += SZ; \
+ bytes -= SZ; \
+ if (state->y >= ymax) {\
+ return -1; \
+ }\
+ } \
+ break
+
+ DECODE_LOOP(1, 8, rgba);
+ DECODE_LOOP(2, 16, rgba);
+ DECODE_LOOP(3, 16, rgba);
+ DECODE_LOOP(4, 8, lum);
+ DECODE_LOOP(5, 16, rgba);
+ case 6:
+ while (bytes >= 16) {
+ rgb32f col[16];
+ decode_bc6_block(col, ptr, (state->state >> 4) & 1);
+ put_block(im, state, (const char *)col, sizeof(col[0]), C);
+ ptr += 16;
+ bytes -= 16;
+ if (state->y >= ymax) {\
+ return -1; \
+ }\
+ }
+ break;
+ DECODE_LOOP(7, 16, rgba);
#undef DECODE_LOOP
- }
- return (int)(ptr - src);
+ }
+ return (int)(ptr - src);
}
int ImagingBcnDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) {
- int N = state->state & 0xf;
- int width = state->xsize;
- int height = state->ysize;
- if ((width & 3) | (height & 3)) {
- return decode_bcn(im, state, buf, bytes, N, 1);
- } else {
- return decode_bcn(im, state, buf, bytes, N, 0);
- }
+ int N = state->state & 0xf;
+ int width = state->xsize;
+ int height = state->ysize;
+ if ((width & 3) | (height & 3)) {
+ return decode_bcn(im, state, buf, bytes, N, 1);
+ } else {
+ return decode_bcn(im, state, buf, bytes, N, 0);
+ }
}
diff --git a/src/libImaging/BitDecode.c b/src/libImaging/BitDecode.c
index 7120b3321..92edd746f 100644
--- a/src/libImaging/BitDecode.c
+++ b/src/libImaging/BitDecode.c
@@ -5,7 +5,7 @@
* decoder for packed bitfields (converts to floating point)
*
* history:
- * 97-05-31 fl created (much more than originally intended)
+ * 97-05-31 fl created (much more than originally intended)
*
* Copyright (c) Fredrik Lundh 1997.
* Copyright (c) Secret Labs AB 1997.
@@ -27,33 +27,35 @@ ImagingBitDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt
if (state->state == 0) {
- /* Initialize context variables */
+ /* Initialize context variables */
/* this decoder only works for float32 image buffers */
if (im->type != IMAGING_TYPE_FLOAT32) {
- state->errcode = IMAGING_CODEC_CONFIG;
- return -1;
+ state->errcode = IMAGING_CODEC_CONFIG;
+ return -1;
}
/* sanity check */
if (bitstate->bits < 1 || bitstate->bits >= 32) {
- state->errcode = IMAGING_CODEC_CONFIG;
- return -1;
+ state->errcode = IMAGING_CODEC_CONFIG;
+ return -1;
}
bitstate->mask = (1<bits)-1;
- if (bitstate->sign)
+ if (bitstate->sign) {
bitstate->signmask = (1<<(bitstate->bits-1));
+ }
- /* check image orientation */
- if (state->ystep < 0) {
- state->y = state->ysize-1;
- state->ystep = -1;
- } else
- state->ystep = 1;
+ /* check image orientation */
+ if (state->ystep < 0) {
+ state->y = state->ysize-1;
+ state->ystep = -1;
+ } else {
+ state->ystep = 1;
+ }
- state->state = 1;
+ state->state = 1;
}
@@ -67,12 +69,13 @@ ImagingBitDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt
bytes--;
/* get a byte from the input stream and insert in the bit buffer */
- if (bitstate->fill&1)
+ if (bitstate->fill&1) {
/* fill MSB first */
bitstate->bitbuffer |= (unsigned long) byte << bitstate->bitcount;
- else
+ } else {
/* fill LSB first */
bitstate->bitbuffer = (bitstate->bitbuffer << 8) | byte;
+ }
bitstate->bitcount += 8;
@@ -85,41 +88,45 @@ ImagingBitDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt
if (bitstate->fill&2) {
/* store LSB first */
data = bitstate->bitbuffer & bitstate->mask;
- if (bitstate->bitcount > 32)
+ if (bitstate->bitcount > 32) {
/* bitbuffer overflow; restore it from last input byte */
bitstate->bitbuffer = byte >> (8 - (bitstate->bitcount -
bitstate->bits));
- else
+ } else {
bitstate->bitbuffer >>= bitstate->bits;
- } else
+ }
+ } else {
/* store MSB first */
data = (bitstate->bitbuffer >> (bitstate->bitcount -
bitstate->bits))
& bitstate->mask;
+ }
bitstate->bitcount -= bitstate->bits;
if (bitstate->lutsize > 0) {
/* map through lookup table */
- if (data <= 0)
+ if (data <= 0) {
pixel = bitstate->lut[0];
- else if (data >= bitstate->lutsize)
+ } else if (data >= bitstate->lutsize) {
pixel = bitstate->lut[bitstate->lutsize-1];
- else
+ } else {
pixel = bitstate->lut[data];
+ }
} else {
/* convert */
- if (data & bitstate->signmask)
+ if (data & bitstate->signmask) {
/* image memory contains signed data */
pixel = (FLOAT32) (INT32) (data | ~bitstate->mask);
- else
+ } else {
pixel = (FLOAT32) data;
+ }
}
*(FLOAT32*)(&im->image32[state->y][state->x]) = pixel;
/* step forward */
- if (++state->x >= state->xsize) {
+ if (++state->x >= state->xsize) {
/* new line */
state->y += state->ystep;
if (state->y < 0 || state->y >= state->ysize) {
@@ -128,8 +135,9 @@ ImagingBitDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt
}
state->x = 0;
/* reset bit buffer */
- if (bitstate->pad > 0)
+ if (bitstate->pad > 0) {
bitstate->bitcount = 0;
+ }
}
}
}
diff --git a/src/libImaging/Blend.c b/src/libImaging/Blend.c
index 19a080d6d..0bac4cda9 100644
--- a/src/libImaging/Blend.c
+++ b/src/libImaging/Blend.c
@@ -5,9 +5,9 @@
* interpolate between two existing images
*
* history:
- * 96-03-20 fl Created
- * 96-05-18 fl Simplified blend expression
- * 96-10-05 fl Fixed expression bug, special case for interpolation
+ * 96-03-20 fl Created
+ * 96-05-18 fl Simplified blend expression
+ * 96-10-05 fl Fixed expression bug, special case for interpolation
*
* Copyright (c) Fredrik Lundh 1996.
* Copyright (c) Secret Labs AB 1997.
@@ -28,52 +28,58 @@ ImagingBlend(Imaging imIn1, Imaging imIn2, float alpha)
/* Check arguments */
if (!imIn1 || !imIn2 || imIn1->type != IMAGING_TYPE_UINT8
|| imIn1->palette || strcmp(imIn1->mode, "1") == 0
- || imIn2->palette || strcmp(imIn2->mode, "1") == 0)
+ || imIn2->palette || strcmp(imIn2->mode, "1") == 0) {
return ImagingError_ModeError();
+ }
if (imIn1->type != imIn2->type ||
- imIn1->bands != imIn2->bands ||
- imIn1->xsize != imIn2->xsize ||
- imIn1->ysize != imIn2->ysize)
- return ImagingError_Mismatch();
+ imIn1->bands != imIn2->bands ||
+ imIn1->xsize != imIn2->xsize ||
+ imIn1->ysize != imIn2->ysize) {
+ return ImagingError_Mismatch();
+ }
/* Shortcuts */
- if (alpha == 0.0)
- return ImagingCopy(imIn1);
- else if (alpha == 1.0)
- return ImagingCopy(imIn2);
+ if (alpha == 0.0) {
+ return ImagingCopy(imIn1);
+ } else if (alpha == 1.0) {
+ return ImagingCopy(imIn2);
+ }
imOut = ImagingNewDirty(imIn1->mode, imIn1->xsize, imIn1->ysize);
- if (!imOut)
- return NULL;
+ if (!imOut) {
+ return NULL;
+ }
if (alpha >= 0 && alpha <= 1.0) {
- /* Interpolate between bands */
- for (y = 0; y < imIn1->ysize; y++) {
- UINT8* in1 = (UINT8*) imIn1->image[y];
- UINT8* in2 = (UINT8*) imIn2->image[y];
- UINT8* out = (UINT8*) imOut->image[y];
- for (x = 0; x < imIn1->linesize; x++)
- out[x] = (UINT8)
- ((int) in1[x] + alpha * ((int) in2[x] - (int) in1[x]));
- }
+ /* Interpolate between bands */
+ for (y = 0; y < imIn1->ysize; y++) {
+ UINT8* in1 = (UINT8*) imIn1->image[y];
+ UINT8* in2 = (UINT8*) imIn2->image[y];
+ UINT8* out = (UINT8*) imOut->image[y];
+ for (x = 0; x < imIn1->linesize; x++) {
+ out[x] = (UINT8)
+ ((int) in1[x] + alpha * ((int) in2[x] - (int) in1[x]));
+ }
+ }
} else {
- /* Extrapolation; must make sure to clip resulting values */
- for (y = 0; y < imIn1->ysize; y++) {
- UINT8* in1 = (UINT8*) imIn1->image[y];
- UINT8* in2 = (UINT8*) imIn2->image[y];
- UINT8* out = (UINT8*) imOut->image[y];
- for (x = 0; x < imIn1->linesize; x++) {
- float temp = (float)
- ((int) in1[x] + alpha * ((int) in2[x] - (int) in1[x]));
- if (temp <= 0.0)
- out[x] = 0;
- else if (temp >= 255.0)
- out[x] = 255;
- else
- out[x] = (UINT8) temp;
- }
- }
+ /* Extrapolation; must make sure to clip resulting values */
+ for (y = 0; y < imIn1->ysize; y++) {
+ UINT8* in1 = (UINT8*) imIn1->image[y];
+ UINT8* in2 = (UINT8*) imIn2->image[y];
+ UINT8* out = (UINT8*) imOut->image[y];
+ for (x = 0; x < imIn1->linesize; x++) {
+ float temp = (float)
+ ((int) in1[x] + alpha * ((int) in2[x] - (int) in1[x]));
+ if (temp <= 0.0) {
+ out[x] = 0;
+ } else if (temp >= 255.0) {
+ out[x] = 255;
+ } else {
+ out[x] = (UINT8) temp;
+ }
+ }
+ }
}
return imOut;
diff --git a/src/libImaging/BoxBlur.c b/src/libImaging/BoxBlur.c
index 9537c4f98..dcdc52cbc 100644
--- a/src/libImaging/BoxBlur.c
+++ b/src/libImaging/BoxBlur.c
@@ -184,8 +184,9 @@ ImagingHorizontalBoxBlur(Imaging imOut, Imaging imIn, float floatRadius)
int edgeB = MAX(imIn->xsize - radius - 1, 0);
UINT32 *lineOut = calloc(imIn->xsize, sizeof(UINT32));
- if (lineOut == NULL)
+ if (lineOut == NULL) {
return ImagingError_MemoryError();
+ }
// printf(">>> %d %d %d\n", radius, ww, fw);
@@ -248,11 +249,13 @@ ImagingBoxBlur(Imaging imOut, Imaging imIn, float radius, int n)
imIn->type != imOut->type ||
imIn->bands != imOut->bands ||
imIn->xsize != imOut->xsize ||
- imIn->ysize != imOut->ysize)
+ imIn->ysize != imOut->ysize) {
return ImagingError_Mismatch();
+ }
- if (imIn->type != IMAGING_TYPE_UINT8)
+ if (imIn->type != IMAGING_TYPE_UINT8) {
return ImagingError_ModeError();
+ }
if (!(strcmp(imIn->mode, "RGB") == 0 ||
strcmp(imIn->mode, "RGBA") == 0 ||
@@ -261,12 +264,14 @@ ImagingBoxBlur(Imaging imOut, Imaging imIn, float radius, int n)
strcmp(imIn->mode, "CMYK") == 0 ||
strcmp(imIn->mode, "L") == 0 ||
strcmp(imIn->mode, "LA") == 0 ||
- strcmp(imIn->mode, "La") == 0))
+ strcmp(imIn->mode, "La") == 0)) {
return ImagingError_ModeError();
+ }
imTransposed = ImagingNewDirty(imIn->mode, imIn->ysize, imIn->xsize);
- if (!imTransposed)
+ if (!imTransposed) {
return NULL;
+ }
/* Apply blur in one dimension.
Use imOut as a destination at first pass,
diff --git a/src/libImaging/Chops.c b/src/libImaging/Chops.c
index a1673dff6..a0a70abd9 100644
--- a/src/libImaging/Chops.c
+++ b/src/libImaging/Chops.c
@@ -19,24 +19,26 @@
#include "Imaging.h"
-#define CHOP(operation, mode)\
+#define CHOP(operation)\
int x, y;\
Imaging imOut;\
- imOut = create(imIn1, imIn2, mode);\
- if (!imOut)\
+ imOut = create(imIn1, imIn2, NULL);\
+ if (!imOut) {\
return NULL;\
+ }\
for (y = 0; y < imOut->ysize; y++) {\
UINT8* out = (UINT8*) imOut->image[y];\
UINT8* in1 = (UINT8*) imIn1->image[y];\
UINT8* in2 = (UINT8*) imIn2->image[y];\
for (x = 0; x < imOut->linesize; x++) {\
int temp = operation;\
- if (temp <= 0)\
+ if (temp <= 0) {\
out[x] = 0;\
- else if (temp >= 255)\
+ } else if (temp >= 255) {\
out[x] = 255;\
- else\
+ } else {\
out[x] = temp;\
+ }\
}\
}\
return imOut;
@@ -45,8 +47,9 @@
int x, y;\
Imaging imOut;\
imOut = create(imIn1, imIn2, mode);\
- if (!imOut)\
+ if (!imOut) {\
return NULL;\
+ }\
for (y = 0; y < imOut->ysize; y++) {\
UINT8* out = (UINT8*) imOut->image[y];\
UINT8* in1 = (UINT8*) imIn1->image[y];\
@@ -63,11 +66,13 @@ create(Imaging im1, Imaging im2, char* mode)
int xsize, ysize;
if (!im1 || !im2 || im1->type != IMAGING_TYPE_UINT8 ||
- (mode != NULL && (strcmp(im1->mode, "1") || strcmp(im2->mode, "1"))))
+ (mode != NULL && (strcmp(im1->mode, "1") || strcmp(im2->mode, "1")))) {
return (Imaging) ImagingError_ModeError();
+ }
if (im1->type != im2->type ||
- im1->bands != im2->bands)
+ im1->bands != im2->bands) {
return (Imaging) ImagingError_Mismatch();
+ }
xsize = (im1->xsize < im2->xsize) ? im1->xsize : im2->xsize;
ysize = (im1->ysize < im2->ysize) ? im1->ysize : im2->ysize;
@@ -78,43 +83,43 @@ create(Imaging im1, Imaging im2, char* mode)
Imaging
ImagingChopLighter(Imaging imIn1, Imaging imIn2)
{
- CHOP((in1[x] > in2[x]) ? in1[x] : in2[x], NULL);
+ CHOP((in1[x] > in2[x]) ? in1[x] : in2[x]);
}
Imaging
ImagingChopDarker(Imaging imIn1, Imaging imIn2)
{
- CHOP((in1[x] < in2[x]) ? in1[x] : in2[x], NULL);
+ CHOP((in1[x] < in2[x]) ? in1[x] : in2[x]);
}
Imaging
ImagingChopDifference(Imaging imIn1, Imaging imIn2)
{
- CHOP(abs((int) in1[x] - (int) in2[x]), NULL);
+ CHOP(abs((int) in1[x] - (int) in2[x]));
}
Imaging
ImagingChopMultiply(Imaging imIn1, Imaging imIn2)
{
- CHOP((int) in1[x] * (int) in2[x] / 255, NULL);
+ CHOP((int) in1[x] * (int) in2[x] / 255);
}
Imaging
ImagingChopScreen(Imaging imIn1, Imaging imIn2)
{
- CHOP(255 - ((int) (255 - in1[x]) * (int) (255 - in2[x])) / 255, NULL);
+ CHOP(255 - ((int) (255 - in1[x]) * (int) (255 - in2[x])) / 255);
}
Imaging
ImagingChopAdd(Imaging imIn1, Imaging imIn2, float scale, int offset)
{
- CHOP(((int) in1[x] + (int) in2[x]) / scale + offset, NULL);
+ CHOP(((int) in1[x] + (int) in2[x]) / scale + offset);
}
Imaging
ImagingChopSubtract(Imaging imIn1, Imaging imIn2, float scale, int offset)
{
- CHOP(((int) in1[x] - (int) in2[x]) / scale + offset, NULL);
+ CHOP(((int) in1[x] - (int) in2[x]) / scale + offset);
}
Imaging
diff --git a/src/libImaging/Convert.c b/src/libImaging/Convert.c
index 9f5722543..b0b794d72 100644
--- a/src/libImaging/Convert.c
+++ b/src/libImaging/Convert.c
@@ -123,8 +123,9 @@ static void
l2bit(UINT8* out, const UINT8* in, int xsize)
{
int x;
- for (x = 0; x < xsize; x++)
+ for (x = 0; x < xsize; x++) {
*out++ = (*in++ >= 128) ? 255 : 0;
+ }
}
static void
@@ -206,8 +207,9 @@ static void
la2l(UINT8* out, const UINT8* in, int xsize)
{
int x;
- for (x = 0; x < xsize; x++, in += 4)
+ for (x = 0; x < xsize; x++, in += 4) {
*out++ = in[0];
+ }
}
static void
@@ -240,18 +242,20 @@ static void
rgb2bit(UINT8* out, const UINT8* in, int xsize)
{
int x;
- for (x = 0; x < xsize; x++, in += 4)
+ for (x = 0; x < xsize; x++, in += 4) {
/* ITU-R Recommendation 601-2 (assuming nonlinear RGB) */
*out++ = (L(in) >= 128000) ? 255 : 0;
+ }
}
static void
rgb2l(UINT8* out, const UINT8* in, int xsize)
{
int x;
- for (x = 0; x < xsize; x++, in += 4)
+ for (x = 0; x < xsize; x++, in += 4) {
/* ITU-R Recommendation 601-2 (assuming nonlinear RGB) */
*out++ = L24(in) >> 16;
+ }
}
static void
@@ -653,12 +657,13 @@ i2l(UINT8* out, const UINT8* in_, int xsize)
for (x = 0; x < xsize; x++, out++, in_ += 4) {
INT32 v;
memcpy(&v, in_, sizeof(v));
- if (v <= 0)
+ if (v <= 0) {
*out = 0;
- else if (v >= 255)
+ } else if (v >= 255) {
*out = 255;
- else
+ } else {
*out = (UINT8) v;
+ }
}
}
@@ -681,12 +686,13 @@ i2rgb(UINT8* out, const UINT8* in_, int xsize)
int x;
INT32* in = (INT32*) in_;
for (x = 0; x < xsize; x++, in++, out+=4) {
- if (*in <= 0)
+ if (*in <= 0) {
out[0] = out[1] = out[2] = 0;
- else if (*in >= 255)
+ } else if (*in >= 255) {
out[0] = out[1] = out[2] = 255;
- else
+ } else {
out[0] = out[1] = out[2] = (UINT8) *in;
+ }
out[3] = 255;
}
}
@@ -741,12 +747,13 @@ f2l(UINT8* out, const UINT8* in_, int xsize)
for (x = 0; x < xsize; x++, out++, in_ += 4) {
FLOAT32 v;
memcpy(&v, in_, sizeof(v));
- if (v <= 0.0)
+ if (v <= 0.0) {
*out = 0;
- else if (v >= 255.0)
+ } else if (v >= 255.0) {
*out = 255;
- else
+ } else {
*out = (UINT8) v;
+ }
}
}
@@ -797,8 +804,9 @@ static void
ycbcr2l(UINT8* out, const UINT8* in, int xsize)
{
int x;
- for (x = 0; x < xsize; x++, in += 4)
+ for (x = 0; x < xsize; x++, in += 4) {
*out++ = in[0];
+ }
}
static void
@@ -908,22 +916,26 @@ static void
I16L_L(UINT8* out, const UINT8* in, int xsize)
{
int x;
- for (x = 0; x < xsize; x++, in += 2)
- if (in[1] != 0)
+ for (x = 0; x < xsize; x++, in += 2) {
+ if (in[1] != 0) {
*out++ = 255;
- else
+ } else {
*out++ = in[0];
+ }
+ }
}
static void
I16B_L(UINT8* out, const UINT8* in, int xsize)
{
int x;
- for (x = 0; x < xsize; x++, in += 2)
- if (in[0] != 0)
+ for (x = 0; x < xsize; x++, in += 2) {
+ if (in[0] != 0) {
*out++ = 255;
- else
+ } else {
*out++ = in[1];
+ }
+ }
}
static struct {
@@ -1056,8 +1068,9 @@ p2bit(UINT8* out, const UINT8* in, int xsize, const UINT8* palette)
{
int x;
/* FIXME: precalculate greyscale palette? */
- for (x = 0; x < xsize; x++)
+ for (x = 0; x < xsize; x++) {
*out++ = (L(&palette[in[x]*4]) >= 128000) ? 255 : 0;
+ }
}
static void
@@ -1065,8 +1078,9 @@ pa2bit(UINT8* out, const UINT8* in, int xsize, const UINT8* palette)
{
int x;
/* FIXME: precalculate greyscale palette? */
- for (x = 0; x < xsize; x++, in += 4)
+ for (x = 0; x < xsize; x++, in += 4) {
*out++ = (L(&palette[in[0]*4]) >= 128000) ? 255 : 0;
+ }
}
static void
@@ -1074,8 +1088,9 @@ p2l(UINT8* out, const UINT8* in, int xsize, const UINT8* palette)
{
int x;
/* FIXME: precalculate greyscale palette? */
- for (x = 0; x < xsize; x++)
+ for (x = 0; x < xsize; x++) {
*out++ = L(&palette[in[x]*4]) / 1000;
+ }
}
static void
@@ -1083,8 +1098,9 @@ pa2l(UINT8* out, const UINT8* in, int xsize, const UINT8* palette)
{
int x;
/* FIXME: precalculate greyscale palette? */
- for (x = 0; x < xsize; x++, in += 4)
+ for (x = 0; x < xsize; x++, in += 4) {
*out++ = L(&palette[in[0]*4]) / 1000;
+ }
}
static void
@@ -1138,8 +1154,9 @@ pa2i(UINT8* out_, const UINT8* in, int xsize, const UINT8* palette)
{
int x;
INT32* out = (INT32*) out_;
- for (x = 0; x < xsize; x++, in += 4)
+ for (x = 0; x < xsize; x++, in += 4) {
*out++ = L(&palette[in[0]*4]) / 1000;
+ }
}
static void
@@ -1157,8 +1174,9 @@ pa2f(UINT8* out_, const UINT8* in, int xsize, const UINT8* palette)
{
int x;
FLOAT32* out = (FLOAT32*) out_;
- for (x = 0; x < xsize; x++, in += 4)
+ for (x = 0; x < xsize; x++, in += 4) {
*out++ = (float) L(&palette[in[0]*4]) / 1000.0F;
+ }
}
static void
@@ -1273,46 +1291,50 @@ frompalette(Imaging imOut, Imaging imIn, const char *mode)
/* Map palette image to L, RGB, RGBA, or CMYK */
- if (!imIn->palette)
+ if (!imIn->palette) {
return (Imaging) ImagingError_ValueError("no palette");
+ }
alpha = !strcmp(imIn->mode, "PA");
- if (strcmp(mode, "1") == 0)
+ if (strcmp(mode, "1") == 0) {
convert = alpha ? pa2bit : p2bit;
- else if (strcmp(mode, "L") == 0)
+ } else if (strcmp(mode, "L") == 0) {
convert = alpha ? pa2l : p2l;
- else if (strcmp(mode, "LA") == 0)
+ } else if (strcmp(mode, "LA") == 0) {
convert = alpha ? pa2la : p2la;
- else if (strcmp(mode, "PA") == 0)
+ } else if (strcmp(mode, "PA") == 0) {
convert = p2pa;
- else if (strcmp(mode, "I") == 0)
+ } else if (strcmp(mode, "I") == 0) {
convert = alpha ? pa2i : p2i;
- else if (strcmp(mode, "F") == 0)
+ } else if (strcmp(mode, "F") == 0) {
convert = alpha ? pa2f : p2f;
- else if (strcmp(mode, "RGB") == 0)
+ } else if (strcmp(mode, "RGB") == 0) {
convert = alpha ? pa2rgb : p2rgb;
- else if (strcmp(mode, "RGBA") == 0)
+ } else if (strcmp(mode, "RGBA") == 0) {
convert = alpha ? pa2rgba : p2rgba;
- else if (strcmp(mode, "RGBX") == 0)
+ } else if (strcmp(mode, "RGBX") == 0) {
convert = alpha ? pa2rgba : p2rgba;
- else if (strcmp(mode, "CMYK") == 0)
+ } else if (strcmp(mode, "CMYK") == 0) {
convert = alpha ? pa2cmyk : p2cmyk;
- else if (strcmp(mode, "YCbCr") == 0)
+ } else if (strcmp(mode, "YCbCr") == 0) {
convert = alpha ? pa2ycbcr : p2ycbcr;
- else if (strcmp(mode, "HSV") == 0)
+ } else if (strcmp(mode, "HSV") == 0) {
convert = alpha ? pa2hsv : p2hsv;
- else
+ } else {
return (Imaging) ImagingError_ValueError("conversion not supported");
+ }
imOut = ImagingNew2Dirty(mode, imOut, imIn);
- if (!imOut)
+ if (!imOut) {
return NULL;
+ }
ImagingSectionEnter(&cookie);
- for (y = 0; y < imIn->ysize; y++)
+ for (y = 0; y < imIn->ysize; y++) {
(*convert)((UINT8*) imOut->image[y], (UINT8*) imIn->image[y],
imIn->xsize, imIn->palette->palette);
+ }
ImagingSectionLeave(&cookie);
return imOut;
@@ -1330,26 +1352,30 @@ topalette(Imaging imOut, Imaging imIn, const char *mode, ImagingPalette inpalett
ImagingPalette palette = inpalette;;
/* Map L or RGB/RGBX/RGBA to palette image */
- if (strcmp(imIn->mode, "L") != 0 && strncmp(imIn->mode, "RGB", 3) != 0)
+ if (strcmp(imIn->mode, "L") != 0 && strncmp(imIn->mode, "RGB", 3) != 0) {
return (Imaging) ImagingError_ValueError("conversion not supported");
+ }
alpha = !strcmp(mode, "PA");
if (palette == NULL) {
/* FIXME: make user configurable */
- if (imIn->bands == 1)
+ if (imIn->bands == 1) {
palette = ImagingPaletteNew("RGB"); /* Initialised to grey ramp */
- else
+ } else {
palette = ImagingPaletteNewBrowser(); /* Standard colour cube */
+ }
}
- if (!palette)
+ if (!palette) {
return (Imaging) ImagingError_ValueError("no palette");
+ }
imOut = ImagingNew2Dirty(mode, imOut, imIn);
if (!imOut) {
- if (palette != inpalette)
+ if (palette != inpalette) {
ImagingPaletteDelete(palette);
+ }
return NULL;
}
@@ -1376,8 +1402,9 @@ topalette(Imaging imOut, Imaging imIn, const char *mode, ImagingPalette inpalett
/* Create mapping cache */
if (ImagingPaletteCachePrepare(palette) < 0) {
ImagingDelete(imOut);
- if (palette != inpalette)
+ if (palette != inpalette) {
ImagingPaletteDelete(palette);
+ }
return NULL;
}
@@ -1415,8 +1442,9 @@ topalette(Imaging imOut, Imaging imIn, const char *mode, ImagingPalette inpalett
/* get closest colour */
cache = &ImagingPaletteCache(palette, r, g, b);
- if (cache[0] == 0x100)
+ if (cache[0] == 0x100) {
ImagingPaletteCacheUpdate(palette, r, g, b);
+ }
if (alpha) {
out[x*4] = out[x*4+1] = out[x*4+2] = (UINT8) cache[0];
out[x*4+3] = 255;
@@ -1464,8 +1492,9 @@ topalette(Imaging imOut, Imaging imIn, const char *mode, ImagingPalette inpalett
/* get closest colour */
cache = &ImagingPaletteCache(palette, r, g, b);
- if (cache[0] == 0x100)
+ if (cache[0] == 0x100) {
ImagingPaletteCacheUpdate(palette, r, g, b);
+ }
if (alpha) {
out[x*4] = out[x*4+1] = out[x*4+2] = (UINT8) cache[0];
out[x*4+3] = 255;
@@ -1477,12 +1506,14 @@ topalette(Imaging imOut, Imaging imIn, const char *mode, ImagingPalette inpalett
ImagingSectionLeave(&cookie);
}
- if (inpalette != palette)
+ if (inpalette != palette) {
ImagingPaletteCacheDelete(palette);
+ }
}
- if (inpalette != palette)
+ if (inpalette != palette) {
ImagingPaletteDelete(palette);
+ }
return imOut;
}
@@ -1495,12 +1526,14 @@ tobilevel(Imaging imOut, Imaging imIn, int dither)
int* errors;
/* Map L or RGB to dithered 1 image */
- if (strcmp(imIn->mode, "L") != 0 && strcmp(imIn->mode, "RGB") != 0)
+ if (strcmp(imIn->mode, "L") != 0 && strcmp(imIn->mode, "RGB") != 0) {
return (Imaging) ImagingError_ValueError("conversion not supported");
+ }
imOut = ImagingNew2Dirty("1", imOut, imIn);
- if (!imOut)
+ if (!imOut) {
return NULL;
+ }
errors = calloc(imIn->xsize + 1, sizeof(int));
if (!errors) {
@@ -1582,63 +1615,72 @@ convert(Imaging imOut, Imaging imIn, const char *mode,
ImagingShuffler convert;
int y;
- if (!imIn)
+ if (!imIn) {
return (Imaging) ImagingError_ModeError();
+ }
if (!mode) {
/* Map palette image to full depth */
- if (!imIn->palette)
+ if (!imIn->palette) {
return (Imaging) ImagingError_ModeError();
+ }
mode = imIn->palette->mode;
- } else
+ } else {
/* Same mode? */
- if (!strcmp(imIn->mode, mode))
+ if (!strcmp(imIn->mode, mode)) {
return ImagingCopy2(imOut, imIn);
+ }
+ }
/* test for special conversions */
- if (strcmp(imIn->mode, "P") == 0 || strcmp(imIn->mode, "PA") == 0)
+ if (strcmp(imIn->mode, "P") == 0 || strcmp(imIn->mode, "PA") == 0) {
return frompalette(imOut, imIn, mode);
+ }
- if (strcmp(mode, "P") == 0 || strcmp(mode, "PA") == 0)
+ if (strcmp(mode, "P") == 0 || strcmp(mode, "PA") == 0) {
return topalette(imOut, imIn, mode, palette, dither);
+ }
- if (dither && strcmp(mode, "1") == 0)
+ if (dither && strcmp(mode, "1") == 0) {
return tobilevel(imOut, imIn, dither);
+ }
/* standard conversion machinery */
convert = NULL;
- for (y = 0; converters[y].from; y++)
+ for (y = 0; converters[y].from; y++) {
if (!strcmp(imIn->mode, converters[y].from) &&
!strcmp(mode, converters[y].to)) {
convert = converters[y].convert;
break;
}
+ }
- if (!convert)
+ if (!convert) {
#ifdef notdef
return (Imaging) ImagingError_ValueError("conversion not supported");
#else
- {
- static char buf[256];
- /* FIXME: may overflow if mode is too large */
- sprintf(buf, "conversion from %s to %s not supported", imIn->mode, mode);
- return (Imaging) ImagingError_ValueError(buf);
- }
+ static char buf[256];
+ /* FIXME: may overflow if mode is too large */
+ sprintf(buf, "conversion from %s to %s not supported", imIn->mode, mode);
+ return (Imaging) ImagingError_ValueError(buf);
#endif
+ }
imOut = ImagingNew2Dirty(mode, imOut, imIn);
- if (!imOut)
+ if (!imOut) {
return NULL;
+ }
ImagingSectionEnter(&cookie);
- for (y = 0; y < imIn->ysize; y++)
+ for (y = 0; y < imIn->ysize; y++) {
(*convert)((UINT8*) imOut->image[y], (UINT8*) imIn->image[y],
imIn->xsize);
+ }
ImagingSectionLeave(&cookie);
return imOut;
@@ -1727,17 +1769,19 @@ ImagingConvertInPlace(Imaging imIn, const char* mode)
int y;
/* limited support for inplace conversion */
- if (strcmp(imIn->mode, "L") == 0 && strcmp(mode, "1") == 0)
+ if (strcmp(imIn->mode, "L") == 0 && strcmp(mode, "1") == 0) {
convert = l2bit;
- else if (strcmp(imIn->mode, "1") == 0 && strcmp(mode, "L") == 0)
+ } else if (strcmp(imIn->mode, "1") == 0 && strcmp(mode, "L") == 0) {
convert = bit2l;
- else
+ } else {
return ImagingError_ModeError();
+ }
ImagingSectionEnter(&cookie);
- for (y = 0; y < imIn->ysize; y++)
+ for (y = 0; y < imIn->ysize; y++) {
(*convert)((UINT8*) imIn->image[y], (UINT8*) imIn->image[y],
imIn->xsize);
+ }
ImagingSectionLeave(&cookie);
return imIn;
diff --git a/src/libImaging/ConvertYCbCr.c b/src/libImaging/ConvertYCbCr.c
index 6ce549111..47de4ff71 100644
--- a/src/libImaging/ConvertYCbCr.c
+++ b/src/libImaging/ConvertYCbCr.c
@@ -5,7 +5,7 @@
* code to convert YCbCr data
*
* history:
- * 98-07-01 hk Created
+ * 98-07-01 hk Created
*
* Copyright (c) Secret Labs AB 1998
*
diff --git a/src/libImaging/Copy.c b/src/libImaging/Copy.c
index 1bc9b1a70..5b4899f39 100644
--- a/src/libImaging/Copy.c
+++ b/src/libImaging/Copy.c
@@ -25,21 +25,25 @@ _copy(Imaging imOut, Imaging imIn)
ImagingSectionCookie cookie;
int y;
- if (!imIn)
- return (Imaging) ImagingError_ValueError(NULL);
+ if (!imIn) {
+ return (Imaging) ImagingError_ValueError(NULL);
+ }
imOut = ImagingNew2Dirty(imIn->mode, imOut, imIn);
- if (!imOut)
+ if (!imOut) {
return NULL;
+ }
ImagingCopyPalette(imOut, imIn);
ImagingSectionEnter(&cookie);
- if (imIn->block != NULL && imOut->block != NULL)
- memcpy(imOut->block, imIn->block, imIn->ysize * imIn->linesize);
- else
- for (y = 0; y < imIn->ysize; y++)
+ if (imIn->block != NULL && imOut->block != NULL) {
+ memcpy(imOut->block, imIn->block, imIn->ysize * imIn->linesize);
+ } else {
+ for (y = 0; y < imIn->ysize; y++) {
memcpy(imOut->image[y], imIn->image[y], imIn->linesize);
+ }
+ }
ImagingSectionLeave(&cookie);
return imOut;
diff --git a/src/libImaging/Crop.c b/src/libImaging/Crop.c
index 4407c1b1d..d136edbfc 100644
--- a/src/libImaging/Crop.c
+++ b/src/libImaging/Crop.c
@@ -5,9 +5,9 @@
* cut region from image
*
* history:
- * 95-11-27 fl Created
- * 98-07-10 fl Fixed "null result" error
- * 99-02-05 fl Rewritten to use Paste primitive
+ * 95-11-27 fl Created
+ * 98-07-10 fl Fixed "null result" error
+ * 99-02-05 fl Rewritten to use Paste primitive
*
* Copyright (c) Secret Labs AB 1997-99.
* Copyright (c) Fredrik Lundh 1995.
@@ -27,24 +27,29 @@ ImagingCrop(Imaging imIn, int sx0, int sy0, int sx1, int sy1)
int dx0, dy0, dx1, dy1;
INT32 zero = 0;
- if (!imIn)
- return (Imaging) ImagingError_ModeError();
+ if (!imIn) {
+ return (Imaging) ImagingError_ModeError();
+ }
xsize = sx1 - sx0;
- if (xsize < 0)
+ if (xsize < 0) {
xsize = 0;
+ }
ysize = sy1 - sy0;
- if (ysize < 0)
+ if (ysize < 0) {
ysize = 0;
+ }
imOut = ImagingNewDirty(imIn->mode, xsize, ysize);
- if (!imOut)
- return NULL;
+ if (!imOut) {
+ return NULL;
+ }
ImagingCopyPalette(imOut, imIn);
- if (sx0 < 0 || sy0 < 0 || sx1 > imIn->xsize || sy1 > imIn->ysize)
- (void) ImagingFill(imOut, &zero);
+ if (sx0 < 0 || sy0 < 0 || sx1 > imIn->xsize || sy1 > imIn->ysize) {
+ (void) ImagingFill(imOut, &zero);
+ }
dx0 = -sx0;
dy0 = -sy0;
diff --git a/src/libImaging/Dib.c b/src/libImaging/Dib.c
index 504290231..202b0c9fa 100644
--- a/src/libImaging/Dib.c
+++ b/src/libImaging/Dib.c
@@ -40,8 +40,9 @@ ImagingGetModeDIB(int size_out[2])
mode = "P";
if (!(GetDeviceCaps(dc, RASTERCAPS) & RC_PALETTE)) {
mode = "RGB";
- if (GetDeviceCaps(dc, BITSPIXEL) == 1)
+ if (GetDeviceCaps(dc, BITSPIXEL) == 1) {
mode = "1";
+ }
}
if (size_out) {
@@ -66,14 +67,16 @@ ImagingNewDIB(const char *mode, int xsize, int ysize)
/* Check mode */
if (strcmp(mode, "1") != 0 && strcmp(mode, "L") != 0 &&
- strcmp(mode, "RGB") != 0)
+ strcmp(mode, "RGB") != 0) {
return (ImagingDIB) ImagingError_ModeError();
+ }
/* Create DIB context and info header */
/* malloc check ok, small constant allocation */
dib = (ImagingDIB) malloc(sizeof(*dib));
- if (!dib)
+ if (!dib) {
return (ImagingDIB) ImagingError_MemoryError();
+ }
/* malloc check ok, small constant allocation */
dib->info = (BITMAPINFO*) malloc(sizeof(BITMAPINFOHEADER) +
256 * sizeof(RGBQUAD));
@@ -113,9 +116,9 @@ ImagingNewDIB(const char *mode, int xsize, int ysize)
dib->pixelsize = strlen(mode);
dib->linesize = (xsize * dib->pixelsize + 3) & -4;
- if (dib->pixelsize == 1)
+ if (dib->pixelsize == 1) {
dib->pack = dib->unpack = (ImagingShuffler) memcpy;
- else {
+ } else {
dib->pack = ImagingPackBGR;
dib->unpack = ImagingPackBGR;
}
@@ -174,14 +177,16 @@ ImagingNewDIB(const char *mode, int xsize, int ysize)
* images. */
i = 10;
- for (r = 0; r < 256; r += 51)
- for (g = 0; g < 256; g += 51)
+ for (r = 0; r < 256; r += 51) {
+ for (g = 0; g < 256; g += 51) {
for (b = 0; b < 256; b += 51) {
pal->palPalEntry[i].peRed = r;
pal->palPalEntry[i].peGreen = g;
pal->palPalEntry[i].peBlue = b;
i++;
}
+ }
+ }
for (r = 1; r < 22-1; r++) {
/* Black and white are already provided by the cube. */
pal->palPalEntry[i].peRed =
@@ -195,14 +200,16 @@ ImagingNewDIB(const char *mode, int xsize, int ysize)
/* Colour DIB. Alternate palette. */
i = 10;
- for (r = 0; r < 256; r += 37)
- for (g = 0; g < 256; g += 32)
+ for (r = 0; r < 256; r += 37) {
+ for (g = 0; g < 256; g += 32) {
for (b = 0; b < 256; b += 64) {
pal->palPalEntry[i].peRed = r;
pal->palPalEntry[i].peGreen = g;
pal->palPalEntry[i].peBlue = b;
i++;
}
+ }
+ }
#endif
@@ -223,9 +230,10 @@ ImagingPasteDIB(ImagingDIB dib, Imaging im, int xy[4])
/* FIXME: check size! */
int y;
- for (y = 0; y < im->ysize; y++)
+ for (y = 0; y < im->ysize; y++) {
dib->pack(dib->bits + dib->linesize*(dib->ysize-(xy[1]+y)-1) +
xy[0]*dib->pixelsize, im->image[y], im->xsize);
+ }
}
@@ -234,8 +242,9 @@ ImagingExposeDIB(ImagingDIB dib, void *dc)
{
/* Copy bitmap to display */
- if (dib->palette != 0)
+ if (dib->palette != 0) {
SelectPalette((HDC) dc, dib->palette, FALSE);
+ }
BitBlt((HDC) dc, 0, 0, dib->xsize, dib->ysize, dib->dc, 0, 0, SRCCOPY);
}
@@ -251,8 +260,9 @@ ImagingDrawDIB(ImagingDIB dib, void *dc, int dst[4], int src[4])
dib->info, DIB_RGB_COLORS, SRCCOPY);
} else {
/* stretchblt (displays) */
- if (dib->palette != 0)
+ if (dib->palette != 0) {
SelectPalette((HDC) dc, dib->palette, FALSE);
+ }
StretchBlt((HDC) dc, dst[0], dst[1], dst[2]-dst[0], dst[3]-dst[1],
dib->dc, src[0], src[1], src[2]-src[0], src[3]-src[1],
SRCCOPY);
@@ -275,8 +285,9 @@ ImagingQueryPaletteDIB(ImagingDIB dib, void *dc)
/* Restore palette */
SelectPalette((HDC) dc, now, FALSE);
- } else
+ } else {
n = 0;
+ }
return n; /* number of colours that was changed */
}
@@ -286,14 +297,16 @@ ImagingDeleteDIB(ImagingDIB dib)
{
/* Clean up */
- if (dib->palette)
+ if (dib->palette) {
DeleteObject(dib->palette);
+ }
if (dib->bitmap) {
SelectObject(dib->dc, dib->old_bitmap);
DeleteObject(dib->bitmap);
}
- if (dib->dc)
+ if (dib->dc) {
DeleteDC(dib->dc);
+ }
free(dib->info);
}
diff --git a/src/libImaging/Draw.c b/src/libImaging/Draw.c
index 6fe76e0b8..ea56d73f0 100644
--- a/src/libImaging/Draw.c
+++ b/src/libImaging/Draw.c
@@ -80,8 +80,9 @@ point8(Imaging im, int x, int y, int ink)
static inline void
point32(Imaging im, int x, int y, int ink)
{
- if (x >= 0 && x < im->xsize && y >= 0 && y < im->ysize)
+ if (x >= 0 && x < im->xsize && y >= 0 && y < im->ysize) {
im->image32[y][x] = ink;
+ }
}
static inline void
@@ -104,16 +105,19 @@ hline8(Imaging im, int x0, int y0, int x1, int ink)
int tmp, pixelwidth;
if (y0 >= 0 && y0 < im->ysize) {
- if (x0 > x1)
+ if (x0 > x1) {
tmp = x0, x0 = x1, x1 = tmp;
- if (x0 < 0)
+ }
+ if (x0 < 0) {
x0 = 0;
- else if (x0 >= im->xsize)
+ } else if (x0 >= im->xsize) {
return;
- if (x1 < 0)
+ }
+ if (x1 < 0) {
return;
- else if (x1 >= im->xsize)
+ } else if (x1 >= im->xsize) {
x1 = im->xsize-1;
+ }
if (x0 <= x1) {
pixelwidth = strncmp(im->mode, "I;16", 4) == 0 ? 2 : 1;
memset(im->image8[y0] + x0 * pixelwidth, (UINT8) ink,
@@ -129,19 +133,23 @@ hline32(Imaging im, int x0, int y0, int x1, int ink)
INT32* p;
if (y0 >= 0 && y0 < im->ysize) {
- if (x0 > x1)
+ if (x0 > x1) {
tmp = x0, x0 = x1, x1 = tmp;
- if (x0 < 0)
+ }
+ if (x0 < 0) {
x0 = 0;
- else if (x0 >= im->xsize)
+ } else if (x0 >= im->xsize) {
return;
- if (x1 < 0)
+ }
+ if (x1 < 0) {
return;
- else if (x1 >= im->xsize)
+ } else if (x1 >= im->xsize) {
x1 = im->xsize-1;
+ }
p = im->image32[y0];
- while (x0 <= x1)
+ while (x0 <= x1) {
p[x0++] = ink;
+ }
}
}
@@ -152,16 +160,19 @@ hline32rgba(Imaging im, int x0, int y0, int x1, int ink)
unsigned int tmp1;
if (y0 >= 0 && y0 < im->ysize) {
- if (x0 > x1)
+ if (x0 > x1) {
tmp = x0, x0 = x1, x1 = tmp;
- if (x0 < 0)
+ }
+ if (x0 < 0) {
x0 = 0;
- else if (x0 >= im->xsize)
+ } else if (x0 >= im->xsize) {
return;
- if (x1 < 0)
+ }
+ if (x1 < 0) {
return;
- else if (x1 >= im->xsize)
+ } else if (x1 >= im->xsize) {
x1 = im->xsize-1;
+ }
if (x0 <= x1) {
UINT8* out = (UINT8*) im->image[y0]+x0*4;
UINT8* in = (UINT8*) &ink;
@@ -184,19 +195,21 @@ line8(Imaging im, int x0, int y0, int x1, int y1, int ink)
/* normalize coordinates */
dx = x1-x0;
- if (dx < 0)
+ if (dx < 0) {
dx = -dx, xs = -1;
- else
+ } else {
xs = 1;
+ }
dy = y1-y0;
- if (dy < 0)
+ if (dy < 0) {
dy = -dy, ys = -1;
- else
+ } else {
ys = 1;
+ }
n = (dx > dy) ? dx : dy;
- if (dx == 0)
+ if (dx == 0) {
/* vertical */
for (i = 0; i < dy; i++) {
@@ -204,7 +217,7 @@ line8(Imaging im, int x0, int y0, int x1, int y1, int ink)
y0 += ys;
}
- else if (dy == 0)
+ } else if (dy == 0) {
/* horizontal */
for (i = 0; i < dx; i++) {
@@ -212,7 +225,7 @@ line8(Imaging im, int x0, int y0, int x1, int y1, int ink)
x0 += xs;
}
- else if (dx > dy) {
+ } else if (dx > dy) {
/* bresenham, horizontal slope */
n = dx;
@@ -260,19 +273,21 @@ line32(Imaging im, int x0, int y0, int x1, int y1, int ink)
/* normalize coordinates */
dx = x1-x0;
- if (dx < 0)
+ if (dx < 0) {
dx = -dx, xs = -1;
- else
+ } else {
xs = 1;
+ }
dy = y1-y0;
- if (dy < 0)
+ if (dy < 0) {
dy = -dy, ys = -1;
- else
+ } else {
ys = 1;
+ }
n = (dx > dy) ? dx : dy;
- if (dx == 0)
+ if (dx == 0) {
/* vertical */
for (i = 0; i < dy; i++) {
@@ -280,7 +295,7 @@ line32(Imaging im, int x0, int y0, int x1, int y1, int ink)
y0 += ys;
}
- else if (dy == 0)
+ } else if (dy == 0) {
/* horizontal */
for (i = 0; i < dx; i++) {
@@ -288,7 +303,7 @@ line32(Imaging im, int x0, int y0, int x1, int y1, int ink)
x0 += xs;
}
- else if (dx > dy) {
+ } else if (dx > dy) {
/* bresenham, horizontal slope */
n = dx;
@@ -336,19 +351,21 @@ line32rgba(Imaging im, int x0, int y0, int x1, int y1, int ink)
/* normalize coordinates */
dx = x1-x0;
- if (dx < 0)
+ if (dx < 0) {
dx = -dx, xs = -1;
- else
+ } else {
xs = 1;
+ }
dy = y1-y0;
- if (dy < 0)
+ if (dy < 0) {
dy = -dy, ys = -1;
- else
+ } else {
ys = 1;
+ }
n = (dx > dy) ? dx : dy;
- if (dx == 0)
+ if (dx == 0) {
/* vertical */
for (i = 0; i < dy; i++) {
@@ -356,7 +373,7 @@ line32rgba(Imaging im, int x0, int y0, int x1, int y1, int ink)
y0 += ys;
}
- else if (dy == 0)
+ } else if (dy == 0) {
/* horizontal */
for (i = 0; i < dx; i++) {
@@ -364,7 +381,7 @@ line32rgba(Imaging im, int x0, int y0, int x1, int y1, int ink)
x0 += xs;
}
- else if (dx > dy) {
+ } else if (dx > dy) {
/* bresenham, horizontal slope */
n = dx;
@@ -407,12 +424,13 @@ static int
x_cmp(const void *x0, const void *x1)
{
float diff = *((float*)x0) - *((float*)x1);
- if (diff < 0)
+ if (diff < 0) {
return -1;
- else if (diff > 0)
+ } else if (diff > 0) {
return 1;
- else
+ } else {
return 0;
+ }
}
@@ -472,15 +490,15 @@ polygon_generic(Imaging im, int n, Edge *e, int ink, int eofill,
}
for (i = 0; i < n; i++) {
- if (e[i].ymin == e[i].ymax) {
- continue;
- }
if (ymin > e[i].ymin) {
ymin = e[i].ymin;
}
if (ymax < e[i].ymax) {
ymax = e[i].ymax;
}
+ if (e[i].ymin == e[i].ymax) {
+ continue;
+ }
edge_table[edge_count++] = (e + i);
}
if (ymin < 0) {
@@ -567,25 +585,28 @@ add_edge(Edge *e, int x0, int y0, int x1, int y1)
{
/* printf("edge %d %d %d %d\n", x0, y0, x1, y1); */
- if (x0 <= x1)
+ if (x0 <= x1) {
e->xmin = x0, e->xmax = x1;
- else
+ } else {
e->xmin = x1, e->xmax = x0;
+ }
- if (y0 <= y1)
+ if (y0 <= y1) {
e->ymin = y0, e->ymax = y1;
- else
+ } else {
e->ymin = y1, e->ymax = y0;
+ }
if (y0 == y1) {
e->d = 0;
e->dx = 0.0;
} else {
e->dx = ((float)(x1-x0)) / (y1-y0);
- if (y0 == e->ymin)
+ if (y0 == e->ymin) {
e->d = 1;
- else
+ } else {
e->d = -1;
+ }
}
e->x0 = x0;
@@ -702,23 +723,27 @@ ImagingDrawRectangle(Imaging im, int x0, int y0, int x1, int y1,
DRAWINIT();
- if (y0 > y1)
+ if (y0 > y1) {
tmp = y0, y0 = y1, y1 = tmp;
+ }
if (fill) {
- if (y0 < 0)
+ if (y0 < 0) {
y0 = 0;
- else if (y0 >= im->ysize)
+ } else if (y0 >= im->ysize) {
return 0;
+ }
- if (y1 < 0)
+ if (y1 < 0) {
return 0;
- else if (y1 > im->ysize)
+ } else if (y1 > im->ysize) {
y1 = im->ysize;
+ }
- for (y = y0; y <= y1; y++)
+ for (y = y0; y <= y1; y++) {
draw->hline(im, x0, y, x1, ink);
+ }
} else {
/* outline */
@@ -744,8 +769,9 @@ ImagingDrawPolygon(Imaging im, int count, int* xy, const void* ink_,
DRAW* draw;
INT32 ink;
- if (count <= 0)
+ if (count <= 0) {
return 0;
+ }
DRAWINIT();
@@ -758,18 +784,21 @@ ImagingDrawPolygon(Imaging im, int count, int* xy, const void* ink_,
(void) ImagingError_MemoryError();
return -1;
}
- for (i = n = 0; i < count-1; i++)
+ for (i = n = 0; i < count-1; i++) {
add_edge(&e[n++], xy[i+i], xy[i+i+1], xy[i+i+2], xy[i+i+3]);
- if (xy[i+i] != xy[0] || xy[i+i+1] != xy[1])
+ }
+ if (xy[i+i] != xy[0] || xy[i+i+1] != xy[1]) {
add_edge(&e[n++], xy[i+i], xy[i+i+1], xy[0], xy[1]);
+ }
draw->polygon(im, n, e, ink, 0);
free(e);
} else {
/* Outline */
- for (i = 0; i < count-1; i++)
+ for (i = 0; i < count-1; i++) {
draw->line(im, xy[i+i], xy[i+i+1], xy[i+i+2], xy[i+i+3], ink);
+ }
draw->line(im, xy[i+i], xy[i+i+1], xy[0], xy[1], ink);
}
@@ -839,8 +868,9 @@ ellipse(Imaging im, int x0, int y0, int x1, int y1,
DRAWINIT();
- while (end < start)
+ while (end < start) {
end += 360;
+ }
if (end - start > 360) {
// no need to go in loops
@@ -849,8 +879,9 @@ ellipse(Imaging im, int x0, int y0, int x1, int y1,
w = x1 - x0;
h = y1 - y0;
- if (w <= 0 || h <= 0)
+ if (w <= 0 || h <= 0) {
return 0;
+ }
cx = (x0 + x1) / 2;
cy = (y0 + y1) / 2;
@@ -861,10 +892,11 @@ ellipse(Imaging im, int x0, int y0, int x1, int y1,
i = end;
}
ellipsePoint(cx, cy, w, h, i, &x, &y);
- if (i != start)
+ if (i != start) {
draw->line(im, lx, ly, x, y, ink);
- else
+ } else {
sx = x, sy = y;
+ }
lx = x, ly = y;
}
@@ -875,8 +907,9 @@ ellipse(Imaging im, int x0, int y0, int x1, int y1,
draw->line(im, cx, cy, sx, sy, ink);
}
} else if (mode == CHORD) {
- if (x != sx || y != sy)
+ if (x != sx || y != sy) {
draw->line(im, x, y, sx, sy, ink);
+ }
}
}
} else {
@@ -909,8 +942,9 @@ ellipse(Imaging im, int x0, int y0, int x1, int y1,
}
lx = x, ly = y;
}
- if (n == 0)
+ if (n == 0) {
return 0;
+ }
if (inner) {
// Inner circle
@@ -931,10 +965,11 @@ ellipse(Imaging im, int x0, int y0, int x1, int y1,
i = end;
}
ellipsePoint(cx, cy, w, h, i, &x, &y);
- if (i == start)
+ if (i == start) {
sx_inner = x, sy_inner = y;
- else
+ } else {
add_edge(&e[n++], lx_inner, ly_inner, x, y);
+ }
lx_inner = x, ly_inner = y;
}
}
@@ -1476,8 +1511,9 @@ ImagingOutlineNew(void)
ImagingOutline outline;
outline = calloc(1, sizeof(struct ImagingOutlineInstance));
- if (!outline)
+ if (!outline) {
return (ImagingOutline) ImagingError_MemoryError();
+ }
outline->edges = NULL;
outline->count = outline->size = 0;
@@ -1490,11 +1526,13 @@ ImagingOutlineNew(void)
void
ImagingOutlineDelete(ImagingOutline outline)
{
- if (!outline)
+ if (!outline) {
return;
+ }
- if (outline->edges)
+ if (outline->edges) {
free(outline->edges);
+ }
free(outline);
}
@@ -1518,8 +1556,9 @@ allocate(ImagingOutline outline, int extra)
/* malloc check ok, overflow checked above */
e = realloc(outline->edges, outline->size * sizeof(Edge));
}
- if (!e)
+ if (!e) {
return NULL;
+ }
outline->edges = e;
}
@@ -1545,8 +1584,9 @@ ImagingOutlineLine(ImagingOutline outline, float x1, float y1)
Edge* e;
e = allocate(outline, 1);
- if (!e)
+ if (!e) {
return -1; /* out of memory */
+ }
add_edge(e, (int) outline->x, (int) outline->y, (int) x1, (int) y1);
@@ -1567,8 +1607,9 @@ ImagingOutlineCurve(ImagingOutline outline, float x1, float y1,
#define STEPS 32
e = allocate(outline, STEPS);
- if (!e)
+ if (!e) {
return -1; /* out of memory */
+ }
xo = outline->x;
yo = outline->y;
@@ -1603,8 +1644,9 @@ ImagingOutlineCurve(ImagingOutline outline, float x1, float y1,
int
ImagingOutlineClose(ImagingOutline outline)
{
- if (outline->x == outline->x0 && outline->y == outline->y0)
+ if (outline->x == outline->x0 && outline->y == outline->y0) {
return 0;
+ }
return ImagingOutlineLine(outline, outline->x0, outline->y0);
}
@@ -1641,14 +1683,16 @@ ImagingOutlineTransform(ImagingOutline outline, double a[6])
y0 = eIn->y0;
/* FIXME: ouch! */
- if (eIn->x0 == eIn->xmin)
+ if (eIn->x0 == eIn->xmin) {
x1 = eIn->xmax;
- else
+ } else {
x1 = eIn->xmin;
- if (eIn->y0 == eIn->ymin)
+ }
+ if (eIn->y0 == eIn->ymin) {
y1 = eIn->ymax;
- else
+ } else {
y1 = eIn->ymin;
+ }
/* full moon tonight! if this doesn't work, you may need to
upgrade your compiler (make sure you have the right service
diff --git a/src/libImaging/Effects.c b/src/libImaging/Effects.c
index 7b4ff0b43..b9ff889d2 100644
--- a/src/libImaging/Effects.c
+++ b/src/libImaging/Effects.c
@@ -34,12 +34,14 @@ ImagingEffectMandelbrot(int xsize, int ysize, double extent[4], int quality)
/* Check arguments */
width = extent[2] - extent[0];
height = extent[3] - extent[1];
- if (width < 0.0 || height < 0.0 || quality < 2)
+ if (width < 0.0 || height < 0.0 || quality < 2) {
return (Imaging) ImagingError_ValueError(NULL);
+ }
im = ImagingNewDirty("L", xsize, ysize);
- if (!im)
+ if (!im) {
return NULL;
+ }
dr = width/(xsize-1);
di = height/(ysize-1);
@@ -82,8 +84,9 @@ ImagingEffectNoise(int xsize, int ysize, float sigma)
double this, next;
imOut = ImagingNewDirty("L", xsize, ysize);
- if (!imOut)
+ if (!imOut) {
return NULL;
+ }
next = 0.0;
nextok = 0;
@@ -123,20 +126,23 @@ ImagingEffectSpread(Imaging imIn, int distance)
imOut = ImagingNewDirty(imIn->mode, imIn->xsize, imIn->ysize);
- if (!imOut)
+ if (!imOut) {
return NULL;
+ }
#define SPREAD(type, image)\
- for (y = 0; y < imOut->ysize; y++)\
+ for (y = 0; y < imOut->ysize; y++) {\
for (x = 0; x < imOut->xsize; x++) {\
int xx = x + (rand() % distance) - distance/2;\
int yy = y + (rand() % distance) - distance/2;\
if (xx >= 0 && xx < imIn->xsize && yy >= 0 && yy < imIn->ysize) {\
imOut->image[yy][xx] = imIn->image[y][x];\
imOut->image[y][x] = imIn->image[yy][xx];\
- } else\
+ } else {\
imOut->image[y][x] = imIn->image[y][x];\
- }
+ }\
+ }\
+ }
if (imIn->image8) {
SPREAD(UINT8, image8);
diff --git a/src/libImaging/EpsEncode.c b/src/libImaging/EpsEncode.c
index 45fab0a6e..ac8a4059c 100644
--- a/src/libImaging/EpsEncode.c
+++ b/src/libImaging/EpsEncode.c
@@ -5,11 +5,11 @@
* encoder for EPS hex data
*
* history:
- * 96-04-19 fl created
- * 96-06-27 fl don't drop last block of encoded data
+ * 96-04-19 fl created
+ * 96-06-27 fl don't drop last block of encoded data
*
* notes:
- * FIXME: rename to HexEncode.c ??
+ * FIXME: rename to HexEncode.c ??
*
* Copyright (c) Fredrik Lundh 1996.
* Copyright (c) Secret Labs AB 1997.
@@ -31,47 +31,50 @@ ImagingEpsEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
UINT8* in, i;
if (!state->state) {
- state->state = HEXBYTE;
- state->xsize *= im->pixelsize; /* Hack! */
+ state->state = HEXBYTE;
+ state->xsize *= im->pixelsize; /* Hack! */
}
in = (UINT8*) im->image[state->y];
for (;;) {
- if (state->state == NEWLINE) {
- if (bytes < 1)
- break;
- *ptr++ = '\n';
- bytes--;
- state->state = HEXBYTE;
- }
+ if (state->state == NEWLINE) {
+ if (bytes < 1) {
+ break;
+ }
+ *ptr++ = '\n';
+ bytes--;
+ state->state = HEXBYTE;
+ }
- if (bytes < 2)
- break;
+ if (bytes < 2) {
+ break;
+ }
- i = in[state->x++];
- *ptr++ = hex[(i>>4)&15];
- *ptr++ = hex[i&15];
- bytes -= 2;
+ i = in[state->x++];
+ *ptr++ = hex[(i>>4)&15];
+ *ptr++ = hex[i&15];
+ bytes -= 2;
- /* Skip junk bytes */
- if (im->bands == 3 && (state->x & 3) == 3)
- state->x++;
+ /* Skip junk bytes */
+ if (im->bands == 3 && (state->x & 3) == 3) {
+ state->x++;
+ }
- if (++state->count >= 79/2) {
- state->state = NEWLINE;
- state->count = 0;
- }
+ if (++state->count >= 79/2) {
+ state->state = NEWLINE;
+ state->count = 0;
+ }
- if (state->x >= state->xsize) {
- state->x = 0;
- if (++state->y >= state->ysize) {
- state->errcode = IMAGING_CODEC_END;
- break;
- }
- in = (UINT8*) im->image[state->y];
- }
+ if (state->x >= state->xsize) {
+ state->x = 0;
+ if (++state->y >= state->ysize) {
+ state->errcode = IMAGING_CODEC_END;
+ break;
+ }
+ in = (UINT8*) im->image[state->y];
+ }
}
diff --git a/src/libImaging/Except.c b/src/libImaging/Except.c
index 515d85d1f..3903b5bb8 100644
--- a/src/libImaging/Except.c
+++ b/src/libImaging/Except.c
@@ -26,7 +26,7 @@
/* exception state */
void *
-ImagingError_IOError(void)
+ImagingError_OSError(void)
{
fprintf(stderr, "*** exception: file access error\n");
return NULL;
@@ -43,21 +43,20 @@ void *
ImagingError_ModeError(void)
{
return ImagingError_ValueError("bad image mode");
- return NULL;
}
void *
ImagingError_Mismatch(void)
{
return ImagingError_ValueError("images don't match");
- return NULL;
}
void *
ImagingError_ValueError(const char *message)
{
- if (!message)
- message = "exception: bad argument to function";
+ if (!message) {
+ message = "exception: bad argument to function";
+ }
fprintf(stderr, "*** %s\n", message);
return NULL;
}
diff --git a/src/libImaging/File.c b/src/libImaging/File.c
index 6f014c1f8..14688d661 100644
--- a/src/libImaging/File.c
+++ b/src/libImaging/File.c
@@ -31,15 +31,18 @@ ImagingSaveRaw(Imaging im, FILE* fp)
/* @PIL227: FIXME: for mode "1", map != 0 to 255 */
/* PGM "L" */
- for (y = 0; y < im->ysize; y++)
+ for (y = 0; y < im->ysize; y++) {
fwrite(im->image[y], 1, im->xsize, fp);
+ }
} else {
/* PPM "RGB" or other internal format */
- for (y = 0; y < im->ysize; y++)
- for (x = i = 0; x < im->xsize; x++, i += im->pixelsize)
+ for (y = 0; y < im->ysize; y++) {
+ for (x = i = 0; x < im->xsize; x++, i += im->pixelsize) {
fwrite(im->image[y]+i, 1, im->bands, fp);
+ }
+ }
}
@@ -59,7 +62,7 @@ ImagingSavePPM(Imaging im, const char* outfile)
fp = fopen(outfile, "wb");
if (!fp) {
- (void) ImagingError_IOError();
+ (void) ImagingError_OSError();
return 0;
}
diff --git a/src/libImaging/Fill.c b/src/libImaging/Fill.c
index d641a5996..da143b4f9 100644
--- a/src/libImaging/Fill.c
+++ b/src/libImaging/Fill.c
@@ -5,9 +5,9 @@
* fill image with constant pixel value
*
* history:
- * 95-11-26 fl moved from Imaging.c
- * 96-05-17 fl added radial fill, renamed wedge to linear
- * 98-06-23 fl changed ImageFill signature
+ * 95-11-26 fl moved from Imaging.c
+ * 96-05-17 fl added radial fill, renamed wedge to linear
+ * 98-06-23 fl changed ImageFill signature
*
* Copyright (c) Secret Labs AB 1997-98. All rights reserved.
* Copyright (c) Fredrik Lundh 1995-96.
@@ -30,27 +30,33 @@ ImagingFill(Imaging im, const void* colour)
/* use generic API */
ImagingAccess access = ImagingAccessNew(im);
if (access) {
- for (y = 0; y < im->ysize; y++)
- for (x = 0; x < im->xsize; x++)
+ for (y = 0; y < im->ysize; y++) {
+ for (x = 0; x < im->xsize; x++) {
access->put_pixel(im, x, y, colour);
+ }
+ }
ImagingAccessDelete(im, access);
} else {
/* wipe the image */
- for (y = 0; y < im->ysize; y++)
+ for (y = 0; y < im->ysize; y++) {
memset(im->image[y], 0, im->linesize);
+ }
}
} else {
INT32 c = 0L;
ImagingSectionEnter(&cookie);
memcpy(&c, colour, im->pixelsize);
if (im->image32 && c != 0L) {
- for (y = 0; y < im->ysize; y++)
- for (x = 0; x < im->xsize; x++)
+ for (y = 0; y < im->ysize; y++) {
+ for (x = 0; x < im->xsize; x++) {
im->image32[y][x] = c;
+ }
+ }
} else {
unsigned char cc = (unsigned char) *(UINT8*) colour;
- for (y = 0; y < im->ysize; y++)
+ for (y = 0; y < im->ysize; y++) {
memset(im->image[y], cc, im->linesize);
+ }
}
ImagingSectionLeave(&cookie);
}
diff --git a/src/libImaging/Filter.c b/src/libImaging/Filter.c
index b033abf66..0897ddbfe 100644
--- a/src/libImaging/Filter.c
+++ b/src/libImaging/Filter.c
@@ -29,10 +29,12 @@
static inline UINT8 clip8(float in)
{
- if (in <= 0.0)
+ if (in <= 0.0) {
return 0;
- if (in >= 255.0)
+ }
+ if (in >= 255.0) {
return 255;
+ }
return (UINT8) in;
}
@@ -43,32 +45,40 @@ ImagingExpand(Imaging imIn, int xmargin, int ymargin, int mode)
int x, y;
ImagingSectionCookie cookie;
- if (xmargin < 0 && ymargin < 0)
+ if (xmargin < 0 && ymargin < 0) {
return (Imaging) ImagingError_ValueError("bad kernel size");
+ }
imOut = ImagingNewDirty(
imIn->mode, imIn->xsize+2*xmargin, imIn->ysize+2*ymargin);
- if (!imOut)
+ if (!imOut) {
return NULL;
+ }
#define EXPAND_LINE(type, image, yin, yout) {\
- for (x = 0; x < xmargin; x++)\
+ for (x = 0; x < xmargin; x++) {\
imOut->image[yout][x] = imIn->image[yin][0];\
- for (x = 0; x < imIn->xsize; x++)\
+ }\
+ for (x = 0; x < imIn->xsize; x++) {\
imOut->image[yout][x+xmargin] = imIn->image[yin][x];\
- for (x = 0; x < xmargin; x++)\
+ }\
+ for (x = 0; x < xmargin; x++) {\
imOut->image[yout][xmargin+imIn->xsize+x] =\
imIn->image[yin][imIn->xsize-1];\
- }
+ }\
+}
#define EXPAND(type, image) {\
- for (y = 0; y < ymargin; y++)\
+ for (y = 0; y < ymargin; y++) {\
EXPAND_LINE(type, image, 0, y);\
- for (y = 0; y < imIn->ysize; y++)\
+ }\
+ for (y = 0; y < imIn->ysize; y++) {\
EXPAND_LINE(type, image, y, y+ymargin);\
- for (y = 0; y < ymargin; y++)\
+ }\
+ for (y = 0; y < ymargin; y++) {\
EXPAND_LINE(type, image, imIn->ysize-1, ymargin+imIn->ysize+y);\
- }
+ }\
+}
ImagingSectionEnter(&cookie);
if (imIn->image8) {
@@ -330,18 +340,22 @@ ImagingFilter(Imaging im, int xsize, int ysize, const FLOAT32* kernel,
Imaging imOut;
ImagingSectionCookie cookie;
- if ( ! im || im->type != IMAGING_TYPE_UINT8)
+ if ( ! im || im->type != IMAGING_TYPE_UINT8) {
return (Imaging) ImagingError_ModeError();
+ }
- if (im->xsize < xsize || im->ysize < ysize)
+ if (im->xsize < xsize || im->ysize < ysize) {
return ImagingCopy(im);
+ }
- if ((xsize != 3 && xsize != 5) || xsize != ysize)
+ if ((xsize != 3 && xsize != 5) || xsize != ysize) {
return (Imaging) ImagingError_ValueError("bad kernel size");
+ }
imOut = ImagingNewDirty(im->mode, im->xsize, im->ysize);
- if (!imOut)
+ if (!imOut) {
return NULL;
+ }
ImagingSectionEnter(&cookie);
if (xsize == 3) {
diff --git a/src/libImaging/FliDecode.c b/src/libImaging/FliDecode.c
index 108e1edf9..84508013d 100644
--- a/src/libImaging/FliDecode.c
+++ b/src/libImaging/FliDecode.c
@@ -5,8 +5,8 @@
* decoder for Autodesk Animator FLI/FLC animations
*
* history:
- * 97-01-03 fl Created
- * 97-01-17 fl Added SS2 support (FLC)
+ * 97-01-03 fl Created
+ * 97-01-17 fl Added SS2 support (FLC)
*
* Copyright (c) Fredrik Lundh 1997.
* Copyright (c) Secret Labs AB 1997.
@@ -18,10 +18,10 @@
#include "Imaging.h"
-#define I16(ptr)\
+#define I16(ptr)\
((ptr)[0] + ((ptr)[1] << 8))
-#define I32(ptr)\
+#define I32(ptr)\
((ptr)[0] + ((ptr)[1] << 8) + ((ptr)[2] << 16) + ((ptr)[3] << 24))
#define ERR_IF_DATA_OOB(offset) \
@@ -29,7 +29,7 @@
state->errcode = IMAGING_CODEC_OVERRUN; \
return -1; \
}
-
+
int
ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes)
{
@@ -41,8 +41,9 @@ ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt
/* If not even the chunk size is present, we'd better leave */
- if (bytes < 4)
- return 0;
+ if (bytes < 4) {
+ return 0;
+ }
/* We don't decode anything unless we have a full chunk in the
input buffer */
@@ -50,8 +51,9 @@ ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt
ptr = buf;
framesize = I32(ptr);
- if (framesize < I32(ptr))
- return 0;
+ if (framesize < I32(ptr)) {
+ return 0;
+ }
/* Make sure this is a frame chunk. The Python driver takes
case of other chunk types. */
@@ -61,8 +63,8 @@ ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt
return -1;
}
if (I16(ptr+4) != 0xF1FA) {
- state->errcode = IMAGING_CODEC_UNKNOWN;
- return -1;
+ state->errcode = IMAGING_CODEC_UNKNOWN;
+ return -1;
}
chunks = I16(ptr+6);
@@ -71,173 +73,181 @@ ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt
/* Process subchunks */
for (c = 0; c < chunks; c++) {
- UINT8* data;
- if (bytes < 10) {
- state->errcode = IMAGING_CODEC_OVERRUN;
- return -1;
- }
- data = ptr + 6;
- switch (I16(ptr+4)) {
- case 4: case 11:
- /* FLI COLOR chunk */
- break; /* ignored; handled by Python code */
- case 7:
- /* FLI SS2 chunk (word delta) */
- /* OOB ok, we've got 4 bytes min on entry */
- lines = I16(data); data += 2;
- for (l = y = 0; l < lines && y < state->ysize; l++, y++) {
- UINT8* local_buf = (UINT8*) im->image[y];
- int p, packets;
- ERR_IF_DATA_OOB(2)
- packets = I16(data); data += 2;
- while (packets & 0x8000) {
- /* flag word */
- if (packets & 0x4000) {
- y += 65536 - packets; /* skip lines */
- if (y >= state->ysize) {
- state->errcode = IMAGING_CODEC_OVERRUN;
- return -1;
- }
- local_buf = (UINT8*) im->image[y];
- } else {
- /* store last byte (used if line width is odd) */
- local_buf[state->xsize-1] = (UINT8) packets;
- }
- ERR_IF_DATA_OOB(2)
- packets = I16(data); data += 2;
- }
- for (p = x = 0; p < packets; p++) {
- ERR_IF_DATA_OOB(2)
- x += data[0]; /* pixel skip */
- if (data[1] >= 128) {
- ERR_IF_DATA_OOB(4)
- i = 256-data[1]; /* run */
- if (x + i + i > state->xsize)
- break;
- for (j = 0; j < i; j++) {
- local_buf[x++] = data[2];
- local_buf[x++] = data[3];
- }
- data += 2 + 2;
- } else {
- i = 2 * (int) data[1]; /* chunk */
- if (x + i > state->xsize)
- break;
- ERR_IF_DATA_OOB(2+i)
- memcpy(local_buf + x, data + 2, i);
- data += 2 + i;
- x += i;
- }
- }
- if (p < packets)
- break; /* didn't process all packets */
- }
- if (l < lines) {
- /* didn't process all lines */
- state->errcode = IMAGING_CODEC_OVERRUN;
- return -1;
- }
- break;
- case 12:
- /* FLI LC chunk (byte delta) */
- /* OOB Check ok, we have 4 bytes min here */
- y = I16(data); ymax = y + I16(data+2); data += 4;
- for (; y < ymax && y < state->ysize; y++) {
- UINT8* out = (UINT8*) im->image[y];
- ERR_IF_DATA_OOB(1)
- int p, packets = *data++;
- for (p = x = 0; p < packets; p++, x += i) {
- ERR_IF_DATA_OOB(2)
- x += data[0]; /* skip pixels */
- if (data[1] & 0x80) {
- i = 256-data[1]; /* run */
- if (x + i > state->xsize)
- break;
- ERR_IF_DATA_OOB(3)
- memset(out + x, data[2], i);
- data += 3;
- } else {
- i = data[1]; /* chunk */
- if (x + i > state->xsize)
- break;
- ERR_IF_DATA_OOB(2+i)
- memcpy(out + x, data + 2, i);
- data += i + 2;
- }
- }
- if (p < packets)
- break; /* didn't process all packets */
- }
- if (y < ymax) {
- /* didn't process all lines */
- state->errcode = IMAGING_CODEC_OVERRUN;
- return -1;
- }
- break;
- case 13:
- /* FLI BLACK chunk */
- for (y = 0; y < state->ysize; y++)
- memset(im->image[y], 0, state->xsize);
- break;
- case 15:
- /* FLI BRUN chunk */
- /* OOB, ok, we've got 4 bytes min on entry */
- for (y = 0; y < state->ysize; y++) {
- UINT8* out = (UINT8*) im->image[y];
- data += 1; /* ignore packetcount byte */
- for (x = 0; x < state->xsize; x += i) {
- ERR_IF_DATA_OOB(2)
- if (data[0] & 0x80) {
- i = 256 - data[0];
- if (x + i > state->xsize) {
- break; /* safety first */
- }
- ERR_IF_DATA_OOB(i+1)
- memcpy(out + x, data + 1, i);
- data += i + 1;
- } else {
- i = data[0];
- if (x + i > state->xsize)
- break; /* safety first */
- memset(out + x, data[1], i);
- data += 2;
- }
- }
- if (x != state->xsize) {
- /* didn't unpack whole line */
- state->errcode = IMAGING_CODEC_OVERRUN;
- return -1;
- }
- }
- break;
- case 16:
- /* COPY chunk */
- if (state->xsize > bytes/state->ysize) {
- /* not enough data for frame */
- return ptr - buf; /* bytes consumed */
- }
- for (y = 0; y < state->ysize; y++) {
- UINT8* local_buf = (UINT8*) im->image[y];
- memcpy(local_buf, data, state->xsize);
- data += state->xsize;
- }
- break;
- case 18:
- /* PSTAMP chunk */
- break; /* ignored */
- default:
- /* unknown chunk */
- /* printf("unknown FLI/FLC chunk: %d\n", I16(ptr+4)); */
- state->errcode = IMAGING_CODEC_UNKNOWN;
- return -1;
- }
- advance = I32(ptr);
- if (advance < 0 || advance > bytes) {
- state->errcode = IMAGING_CODEC_OVERRUN;
- return -1;
- }
- ptr += advance;
- bytes -= advance;
+ UINT8* data;
+ if (bytes < 10) {
+ state->errcode = IMAGING_CODEC_OVERRUN;
+ return -1;
+ }
+ data = ptr + 6;
+ switch (I16(ptr+4)) {
+ case 4: case 11:
+ /* FLI COLOR chunk */
+ break; /* ignored; handled by Python code */
+ case 7:
+ /* FLI SS2 chunk (word delta) */
+ /* OOB ok, we've got 4 bytes min on entry */
+ lines = I16(data); data += 2;
+ for (l = y = 0; l < lines && y < state->ysize; l++, y++) {
+ UINT8* local_buf = (UINT8*) im->image[y];
+ int p, packets;
+ ERR_IF_DATA_OOB(2)
+ packets = I16(data); data += 2;
+ while (packets & 0x8000) {
+ /* flag word */
+ if (packets & 0x4000) {
+ y += 65536 - packets; /* skip lines */
+ if (y >= state->ysize) {
+ state->errcode = IMAGING_CODEC_OVERRUN;
+ return -1;
+ }
+ local_buf = (UINT8*) im->image[y];
+ } else {
+ /* store last byte (used if line width is odd) */
+ local_buf[state->xsize-1] = (UINT8) packets;
+ }
+ ERR_IF_DATA_OOB(2)
+ packets = I16(data); data += 2;
+ }
+ for (p = x = 0; p < packets; p++) {
+ ERR_IF_DATA_OOB(2)
+ x += data[0]; /* pixel skip */
+ if (data[1] >= 128) {
+ ERR_IF_DATA_OOB(4)
+ i = 256-data[1]; /* run */
+ if (x + i + i > state->xsize) {
+ break;
+ }
+ for (j = 0; j < i; j++) {
+ local_buf[x++] = data[2];
+ local_buf[x++] = data[3];
+ }
+ data += 2 + 2;
+ } else {
+ i = 2 * (int) data[1]; /* chunk */
+ if (x + i > state->xsize) {
+ break;
+ }
+ ERR_IF_DATA_OOB(2+i)
+ memcpy(local_buf + x, data + 2, i);
+ data += 2 + i;
+ x += i;
+ }
+ }
+ if (p < packets) {
+ break; /* didn't process all packets */
+ }
+ }
+ if (l < lines) {
+ /* didn't process all lines */
+ state->errcode = IMAGING_CODEC_OVERRUN;
+ return -1;
+ }
+ break;
+ case 12:
+ /* FLI LC chunk (byte delta) */
+ /* OOB Check ok, we have 4 bytes min here */
+ y = I16(data); ymax = y + I16(data+2); data += 4;
+ for (; y < ymax && y < state->ysize; y++) {
+ UINT8* out = (UINT8*) im->image[y];
+ ERR_IF_DATA_OOB(1)
+ int p, packets = *data++;
+ for (p = x = 0; p < packets; p++, x += i) {
+ ERR_IF_DATA_OOB(2)
+ x += data[0]; /* skip pixels */
+ if (data[1] & 0x80) {
+ i = 256-data[1]; /* run */
+ if (x + i > state->xsize) {
+ break;
+ }
+ ERR_IF_DATA_OOB(3)
+ memset(out + x, data[2], i);
+ data += 3;
+ } else {
+ i = data[1]; /* chunk */
+ if (x + i > state->xsize) {
+ break;
+ }
+ ERR_IF_DATA_OOB(2+i)
+ memcpy(out + x, data + 2, i);
+ data += i + 2;
+ }
+ }
+ if (p < packets) {
+ break; /* didn't process all packets */
+ }
+ }
+ if (y < ymax) {
+ /* didn't process all lines */
+ state->errcode = IMAGING_CODEC_OVERRUN;
+ return -1;
+ }
+ break;
+ case 13:
+ /* FLI BLACK chunk */
+ for (y = 0; y < state->ysize; y++) {
+ memset(im->image[y], 0, state->xsize);
+ }
+ break;
+ case 15:
+ /* FLI BRUN chunk */
+ /* OOB, ok, we've got 4 bytes min on entry */
+ for (y = 0; y < state->ysize; y++) {
+ UINT8* out = (UINT8*) im->image[y];
+ data += 1; /* ignore packetcount byte */
+ for (x = 0; x < state->xsize; x += i) {
+ ERR_IF_DATA_OOB(2)
+ if (data[0] & 0x80) {
+ i = 256 - data[0];
+ if (x + i > state->xsize) {
+ break; /* safety first */
+ }
+ ERR_IF_DATA_OOB(i+1)
+ memcpy(out + x, data + 1, i);
+ data += i + 1;
+ } else {
+ i = data[0];
+ if (x + i > state->xsize) {
+ break; /* safety first */
+ }
+ memset(out + x, data[1], i);
+ data += 2;
+ }
+ }
+ if (x != state->xsize) {
+ /* didn't unpack whole line */
+ state->errcode = IMAGING_CODEC_OVERRUN;
+ return -1;
+ }
+ }
+ break;
+ case 16:
+ /* COPY chunk */
+ if (state->xsize > bytes/state->ysize) {
+ /* not enough data for frame */
+ return ptr - buf; /* bytes consumed */
+ }
+ for (y = 0; y < state->ysize; y++) {
+ UINT8* local_buf = (UINT8*) im->image[y];
+ memcpy(local_buf, data, state->xsize);
+ data += state->xsize;
+ }
+ break;
+ case 18:
+ /* PSTAMP chunk */
+ break; /* ignored */
+ default:
+ /* unknown chunk */
+ /* printf("unknown FLI/FLC chunk: %d\n", I16(ptr+4)); */
+ state->errcode = IMAGING_CODEC_UNKNOWN;
+ return -1;
+ }
+ advance = I32(ptr);
+ if (advance < 0 || advance > bytes) {
+ state->errcode = IMAGING_CODEC_OVERRUN;
+ return -1;
+ }
+ ptr += advance;
+ bytes -= advance;
}
return -1; /* end of frame */
diff --git a/src/libImaging/Geometry.c b/src/libImaging/Geometry.c
index fd5e25958..06d0cf24d 100644
--- a/src/libImaging/Geometry.c
+++ b/src/libImaging/Geometry.c
@@ -20,10 +20,12 @@ ImagingFlipLeftRight(Imaging imOut, Imaging imIn)
ImagingSectionCookie cookie;
int x, y, xr;
- if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0)
+ if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0) {
return (Imaging) ImagingError_ModeError();
- if (imIn->xsize != imOut->xsize || imIn->ysize != imOut->ysize)
+ }
+ if (imIn->xsize != imOut->xsize || imIn->ysize != imOut->ysize) {
return (Imaging) ImagingError_Mismatch();
+ }
ImagingCopyPalette(imOut, imIn);
@@ -32,8 +34,9 @@ ImagingFlipLeftRight(Imaging imOut, Imaging imIn)
INT* in = (INT *)imIn->image[y]; \
INT* out = (INT *)imOut->image[y]; \
xr = imIn->xsize-1; \
- for (x = 0; x < imIn->xsize; x++, xr--) \
+ for (x = 0; x < imIn->xsize; x++, xr--) { \
out[xr] = in[x]; \
+ } \
}
ImagingSectionEnter(&cookie);
@@ -62,18 +65,21 @@ ImagingFlipTopBottom(Imaging imOut, Imaging imIn)
ImagingSectionCookie cookie;
int y, yr;
- if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0)
+ if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0) {
return (Imaging) ImagingError_ModeError();
- if (imIn->xsize != imOut->xsize || imIn->ysize != imOut->ysize)
+ }
+ if (imIn->xsize != imOut->xsize || imIn->ysize != imOut->ysize) {
return (Imaging) ImagingError_Mismatch();
+ }
ImagingCopyPalette(imOut, imIn);
ImagingSectionEnter(&cookie);
yr = imIn->ysize - 1;
- for (y = 0; y < imIn->ysize; y++, yr--)
+ for (y = 0; y < imIn->ysize; y++, yr--) {
memcpy(imOut->image[yr], imIn->image[y], imIn->linesize);
+ }
ImagingSectionLeave(&cookie);
@@ -88,10 +94,12 @@ ImagingRotate90(Imaging imOut, Imaging imIn)
int x, y, xx, yy, xr, xxsize, yysize;
int xxx, yyy, xxxsize, yyysize;
- if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0)
+ if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0) {
return (Imaging) ImagingError_ModeError();
- if (imIn->xsize != imOut->ysize || imIn->ysize != imOut->xsize)
+ }
+ if (imIn->xsize != imOut->ysize || imIn->ysize != imOut->xsize) {
return (Imaging) ImagingError_Mismatch();
+ }
ImagingCopyPalette(imOut, imIn);
@@ -144,10 +152,12 @@ ImagingTranspose(Imaging imOut, Imaging imIn)
int x, y, xx, yy, xxsize, yysize;
int xxx, yyy, xxxsize, yyysize;
- if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0)
+ if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0) {
return (Imaging) ImagingError_ModeError();
- if (imIn->xsize != imOut->ysize || imIn->ysize != imOut->xsize)
+ }
+ if (imIn->xsize != imOut->ysize || imIn->ysize != imOut->xsize) {
return (Imaging) ImagingError_Mismatch();
+ }
ImagingCopyPalette(imOut, imIn);
@@ -199,10 +209,12 @@ ImagingTransverse(Imaging imOut, Imaging imIn)
int x, y, xr, yr, xx, yy, xxsize, yysize;
int xxx, yyy, xxxsize, yyysize;
- if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0)
+ if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0) {
return (Imaging) ImagingError_ModeError();
- if (imIn->xsize != imOut->ysize || imIn->ysize != imOut->xsize)
+ }
+ if (imIn->xsize != imOut->ysize || imIn->ysize != imOut->xsize) {
return (Imaging) ImagingError_Mismatch();
+ }
ImagingCopyPalette(imOut, imIn);
@@ -255,10 +267,12 @@ ImagingRotate180(Imaging imOut, Imaging imIn)
ImagingSectionCookie cookie;
int x, y, xr, yr;
- if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0)
+ if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0) {
return (Imaging) ImagingError_ModeError();
- if (imIn->xsize != imOut->xsize || imIn->ysize != imOut->ysize)
+ }
+ if (imIn->xsize != imOut->xsize || imIn->ysize != imOut->ysize) {
return (Imaging) ImagingError_Mismatch();
+ }
ImagingCopyPalette(imOut, imIn);
@@ -267,8 +281,9 @@ ImagingRotate180(Imaging imOut, Imaging imIn)
INT* in = (INT *)imIn->image[y]; \
INT* out = (INT *)imOut->image[yr]; \
xr = imIn->xsize-1; \
- for (x = 0; x < imIn->xsize; x++, xr--) \
+ for (x = 0; x < imIn->xsize; x++, xr--) { \
out[xr] = in[x]; \
+ } \
}
ImagingSectionEnter(&cookie);
@@ -299,10 +314,12 @@ ImagingRotate270(Imaging imOut, Imaging imIn)
int x, y, xx, yy, yr, xxsize, yysize;
int xxx, yyy, xxxsize, yyysize;
- if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0)
+ if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0) {
return (Imaging) ImagingError_ModeError();
- if (imIn->xsize != imOut->ysize || imIn->ysize != imOut->xsize)
+ }
+ if (imIn->xsize != imOut->ysize || imIn->ysize != imOut->xsize) {
return (Imaging) ImagingError_Mismatch();
+ }
ImagingCopyPalette(imOut, imIn);
@@ -415,8 +432,9 @@ nearest_filter8(void* out, Imaging im, double xin, double yin)
{
int x = COORD(xin);
int y = COORD(yin);
- if (x < 0 || x >= im->xsize || y < 0 || y >= im->ysize)
+ if (x < 0 || x >= im->xsize || y < 0 || y >= im->ysize) {
return 0;
+ }
((UINT8*)out)[0] = im->image8[y][x];
return 1;
}
@@ -426,8 +444,9 @@ nearest_filter16(void* out, Imaging im, double xin, double yin)
{
int x = COORD(xin);
int y = COORD(yin);
- if (x < 0 || x >= im->xsize || y < 0 || y >= im->ysize)
+ if (x < 0 || x >= im->xsize || y < 0 || y >= im->ysize) {
return 0;
+ }
memcpy(out, im->image8[y] + x * sizeof(INT16), sizeof(INT16));
return 1;
}
@@ -437,8 +456,9 @@ nearest_filter32(void* out, Imaging im, double xin, double yin)
{
int x = COORD(xin);
int y = COORD(yin);
- if (x < 0 || x >= im->xsize || y < 0 || y >= im->ysize)
+ if (x < 0 || x >= im->xsize || y < 0 || y >= im->ysize) {
return 0;
+ }
memcpy(out, &im->image32[y][x], sizeof(INT32));
return 1;
}
@@ -455,8 +475,9 @@ nearest_filter32(void* out, Imaging im, double xin, double yin)
double v1, v2;\
double dx, dy;\
type* in;\
- if (xin < 0.0 || xin >= im->xsize || yin < 0.0 || yin >= im->ysize)\
+ if (xin < 0.0 || xin >= im->xsize || yin < 0.0 || yin >= im->ysize) {\
return 0;\
+ }\
xin -= 0.5;\
yin -= 0.5;\
x = FLOOR(xin);\
@@ -472,8 +493,9 @@ nearest_filter32(void* out, Imaging im, double xin, double yin)
if (y+1 >= 0 && y+1 < im->ysize) {\
in = (type*) ((image)[y+1] + offset);\
BILINEAR(v2, in[x0], in[x1], dx);\
- } else\
+ } else {\
v2 = v1;\
+ }\
BILINEAR(v1, v1, v2, dy);\
}
@@ -552,8 +574,9 @@ bilinear_filter32RGB(void* out, Imaging im, double xin, double yin)
double v1, v2, v3, v4;\
double dx, dy;\
type* in;\
- if (xin < 0.0 || xin >= im->xsize || yin < 0.0 || yin >= im->ysize)\
+ if (xin < 0.0 || xin >= im->xsize || yin < 0.0 || yin >= im->ysize) {\
return 0;\
+ }\
xin -= 0.5;\
yin -= 0.5;\
x = FLOOR(xin);\
@@ -572,18 +595,21 @@ bilinear_filter32RGB(void* out, Imaging im, double xin, double yin)
if (y+1 >= 0 && y+1 < im->ysize) {\
in = (type*) ((image)[y+1] + offset);\
BICUBIC(v2, in[x0], in[x1], in[x2], in[x3], dx);\
- } else\
+ } else {\
v2 = v1;\
+ }\
if (y+2 >= 0 && y+2 < im->ysize) {\
in = (type*) ((image)[y+2] + offset);\
BICUBIC(v3, in[x0], in[x1], in[x2], in[x3], dx);\
- } else\
+ } else {\
v3 = v2;\
+ }\
if (y+3 >= 0 && y+3 < im->ysize) {\
in = (type*) ((image)[y+3] + offset);\
BICUBIC(v4, in[x0], in[x1], in[x2], in[x3], dx);\
- } else\
+ } else {\
v4 = v3;\
+ }\
BICUBIC(v1, v1, v2, v3, v4, dy);\
}
@@ -593,12 +619,13 @@ bicubic_filter8(void* out, Imaging im, double xin, double yin)
{
BICUBIC_HEAD(UINT8);
BICUBIC_BODY(UINT8, im->image8, 1, 0);
- if (v1 <= 0.0)
+ if (v1 <= 0.0) {
((UINT8*)out)[0] = 0;
- else if (v1 >= 255.0)
+ } else if (v1 >= 255.0) {
((UINT8*)out)[0] = 255;
- else
+ } else {
((UINT8*)out)[0] = (UINT8) v1;
+ }
return 1;
}
@@ -643,12 +670,13 @@ bicubic_filter32LA(void* out, Imaging im, double xin, double yin)
((UINT8*)out)[2] = (UINT8) v1;
}
BICUBIC_BODY(UINT8, im->image, 4, 3);
- if (v1 <= 0.0)
+ if (v1 <= 0.0) {
((UINT8*)out)[3] = 0;
- else if (v1 >= 255.0)
+ } else if (v1 >= 255.0) {
((UINT8*)out)[3] = 255;
- else
+ } else {
((UINT8*)out)[3] = (UINT8) v1;
+ }
return 1;
}
@@ -659,12 +687,13 @@ bicubic_filter32RGB(void* out, Imaging im, double xin, double yin)
BICUBIC_HEAD(UINT8);
for (b = 0; b < im->bands; b++) {
BICUBIC_BODY(UINT8, im->image, 4, b);
- if (v1 <= 0.0)
+ if (v1 <= 0.0) {
((UINT8*)out)[b] = 0;
- else if (v1 >= 255.0)
+ } else if (v1 >= 255.0) {
((UINT8*)out)[b] = 255;
- else
+ } else {
((UINT8*)out)[b] = (UINT8) v1;
+ }
}
return 1;
}
@@ -678,7 +707,7 @@ getfilter(Imaging im, int filterid)
{
switch (filterid) {
case IMAGING_TRANSFORM_NEAREST:
- if (im->image8)
+ if (im->image8) {
switch (im->type) {
case IMAGING_TYPE_UINT8:
return nearest_filter8;
@@ -692,19 +721,21 @@ getfilter(Imaging im, int filterid)
return nearest_filter32;
}
}
- else
+ } else {
return nearest_filter32;
+ }
break;
case IMAGING_TRANSFORM_BILINEAR:
- if (im->image8)
+ if (im->image8) {
return bilinear_filter8;
- else if (im->image32) {
+ } else if (im->image32) {
switch (im->type) {
case IMAGING_TYPE_UINT8:
- if (im->bands == 2)
+ if (im->bands == 2) {
return bilinear_filter32LA;
- else
+ } else {
return bilinear_filter32RGB;
+ }
case IMAGING_TYPE_INT32:
return bilinear_filter32I;
case IMAGING_TYPE_FLOAT32:
@@ -713,15 +744,16 @@ getfilter(Imaging im, int filterid)
}
break;
case IMAGING_TRANSFORM_BICUBIC:
- if (im->image8)
+ if (im->image8) {
return bicubic_filter8;
- else if (im->image32) {
+ } else if (im->image32) {
switch (im->type) {
case IMAGING_TYPE_UINT8:
- if (im->bands == 2)
+ if (im->bands == 2) {
return bicubic_filter32LA;
- else
+ } else {
return bicubic_filter32RGB;
+ }
case IMAGING_TYPE_INT32:
return bicubic_filter32I;
case IMAGING_TYPE_FLOAT32:
@@ -751,32 +783,39 @@ ImagingGenericTransform(
double xx, yy;
ImagingTransformFilter filter = getfilter(imIn, filterid);
- if (!filter)
+ if (!filter) {
return (Imaging) ImagingError_ValueError("bad filter number");
+ }
- if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0)
+ if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0) {
return (Imaging) ImagingError_ModeError();
+ }
ImagingCopyPalette(imOut, imIn);
ImagingSectionEnter(&cookie);
- if (x0 < 0)
+ if (x0 < 0) {
x0 = 0;
- if (y0 < 0)
+ }
+ if (y0 < 0) {
y0 = 0;
- if (x1 > imOut->xsize)
+ }
+ if (x1 > imOut->xsize) {
x1 = imOut->xsize;
- if (y1 > imOut->ysize)
+ }
+ if (y1 > imOut->ysize) {
y1 = imOut->ysize;
+ }
for (y = y0; y < y1; y++) {
out = imOut->image[y] + x0*imOut->pixelsize;
for (x = x0; x < x1; x++) {
if ( ! transform(&xx, &yy, x-x0, y-y0, transform_data) ||
! filter(out, imIn, xx, yy)) {
- if (fill)
+ if (fill) {
memset(out, 0, imOut->pixelsize);
+ }
}
out += imOut->pixelsize;
}
@@ -801,19 +840,24 @@ ImagingScaleAffine(Imaging imOut, Imaging imIn,
int xmin, xmax;
int *xintab;
- if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0)
+ if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0) {
return (Imaging) ImagingError_ModeError();
+ }
ImagingCopyPalette(imOut, imIn);
- if (x0 < 0)
+ if (x0 < 0) {
x0 = 0;
- if (y0 < 0)
+ }
+ if (y0 < 0) {
y0 = 0;
- if (x1 > imOut->xsize)
+ }
+ if (x1 > imOut->xsize) {
x1 = imOut->xsize;
- if (y1 > imOut->ysize)
+ }
+ if (y1 > imOut->ysize) {
y1 = imOut->ysize;
+ }
/* malloc check ok, uses calloc for overflow */
xintab = (int*) calloc(imOut->xsize, sizeof(int));
@@ -833,8 +877,9 @@ ImagingScaleAffine(Imaging imOut, Imaging imIn,
xin = COORD(xo);
if (xin >= 0 && xin < (int) imIn->xsize) {
xmax = x+1;
- if (x < xmin)
+ if (x < xmin) {
xmin = x;
+ }
xintab[x] = xin;
}
xo += a[0];
@@ -845,12 +890,14 @@ ImagingScaleAffine(Imaging imOut, Imaging imIn,
int yi = COORD(yo);\
pixel *in, *out;\
out = imOut->image[y];\
- if (fill && x1 > x0)\
+ if (fill && x1 > x0) {\
memset(out+x0, 0, (x1-x0)*sizeof(pixel));\
+ }\
if (yi >= 0 && yi < imIn->ysize) {\
in = imIn->image[yi];\
- for (x = xmin; x < xmax; x++)\
+ for (x = xmin; x < xmax; x++) {\
out[x] = in[xintab[x]];\
+ }\
}\
yo += a[4];\
}
@@ -915,14 +962,16 @@ affine_fixed(Imaging imOut, Imaging imIn,
xx = a2;\
yy = a5;\
out = imOut->image[y];\
- if (fill && x1 > x0)\
+ if (fill && x1 > x0) {\
memset(out+x0, 0, (x1-x0)*sizeof(pixel));\
+ }\
for (x = x0; x < x1; x++, out++) {\
xin = xx >> 16;\
if (xin >= 0 && xin < xsize) {\
yin = yy >> 16;\
- if (yin >= 0 && yin < ysize)\
+ if (yin >= 0 && yin < ysize) {\
*out = imIn->image[yin][xin];\
+ }\
}\
xx += a0;\
yy += a3;\
@@ -933,10 +982,11 @@ affine_fixed(Imaging imOut, Imaging imIn,
ImagingSectionEnter(&cookie);
- if (imIn->image8)
+ if (imIn->image8) {
AFFINE_TRANSFORM_FIXED(UINT8, image8)
- else
+ } else {
AFFINE_TRANSFORM_FIXED(INT32, image32)
+ }
ImagingSectionLeave(&cookie);
@@ -973,24 +1023,30 @@ ImagingTransformAffine(Imaging imOut, Imaging imIn,
return ImagingScaleAffine(imOut, imIn, x0, y0, x1, y1, a, fill);
}
- if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0)
+ if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0) {
return (Imaging) ImagingError_ModeError();
+ }
- if (x0 < 0)
+ if (x0 < 0) {
x0 = 0;
- if (y0 < 0)
+ }
+ if (y0 < 0) {
y0 = 0;
- if (x1 > imOut->xsize)
+ }
+ if (x1 > imOut->xsize) {
x1 = imOut->xsize;
- if (y1 > imOut->ysize)
+ }
+ if (y1 > imOut->ysize) {
y1 = imOut->ysize;
+ }
/* translate all four corners to check if they are within the
range that can be represented by the fixed point arithmetics */
if (check_fixed(a, 0, 0) && check_fixed(a, x1-x0, y1-y0) &&
- check_fixed(a, 0, y1-y0) && check_fixed(a, x1-x0, 0))
+ check_fixed(a, 0, y1-y0) && check_fixed(a, x1-x0, 0)) {
return affine_fixed(imOut, imIn, x0, y0, x1, y1, a, filterid, fill);
+ }
/* FIXME: cannot really think of any reasonable case when the
following code is used. maybe we should fall back on the slow
@@ -1010,14 +1066,16 @@ ImagingTransformAffine(Imaging imOut, Imaging imIn,
xx = xo;\
yy = yo;\
out = imOut->image[y];\
- if (fill && x1 > x0)\
+ if (fill && x1 > x0) {\
memset(out+x0, 0, (x1-x0)*sizeof(pixel));\
+ }\
for (x = x0; x < x1; x++, out++) {\
xin = COORD(xx);\
if (xin >= 0 && xin < xsize) {\
yin = COORD(yy);\
- if (yin >= 0 && yin < ysize)\
+ if (yin >= 0 && yin < ysize) {\
*out = imIn->image[yin][xin];\
+ }\
}\
xx += a[0];\
yy += a[3];\
@@ -1028,10 +1086,11 @@ ImagingTransformAffine(Imaging imOut, Imaging imIn,
ImagingSectionEnter(&cookie);
- if (imIn->image8)
+ if (imIn->image8) {
AFFINE_TRANSFORM(UINT8, image8)
- else
+ } else {
AFFINE_TRANSFORM(INT32, image32)
+ }
ImagingSectionLeave(&cookie);
diff --git a/src/libImaging/GetBBox.c b/src/libImaging/GetBBox.c
index ea7a35e48..9a8ae1f32 100644
--- a/src/libImaging/GetBBox.c
+++ b/src/libImaging/GetBBox.c
@@ -33,47 +33,52 @@ ImagingGetBBox(Imaging im, int bbox[4])
bbox[1] = -1;
bbox[2] = bbox[3] = 0;
-#define GETBBOX(image, mask)\
+#define GETBBOX(image, mask)\
for (y = 0; y < im->ysize; y++) {\
- has_data = 0;\
- for (x = 0; x < im->xsize; x++)\
- if (im->image[y][x] & mask) {\
- has_data = 1;\
- if (x < bbox[0])\
- bbox[0] = x;\
- if (x >= bbox[2])\
- bbox[2] = x+1;\
- }\
- if (has_data) {\
- if (bbox[1] < 0)\
- bbox[1] = y;\
- bbox[3] = y+1;\
- }\
+ has_data = 0;\
+ for (x = 0; x < im->xsize; x++) {\
+ if (im->image[y][x] & mask) {\
+ has_data = 1;\
+ if (x < bbox[0]) {\
+ bbox[0] = x;\
+ }\
+ if (x >= bbox[2]) {\
+ bbox[2] = x+1;\
+ }\
+ }\
+ }\
+ if (has_data) {\
+ if (bbox[1] < 0) {\
+ bbox[1] = y;\
+ }\
+ bbox[3] = y+1;\
+ }\
}
if (im->image8) {
- GETBBOX(image8, 0xff);
+ GETBBOX(image8, 0xff);
} else {
- INT32 mask = 0xffffffff;
- if (im->bands == 3) {
- ((UINT8*) &mask)[3] = 0;
- } else if (strcmp(im->mode, "RGBa") == 0 ||
- strcmp(im->mode, "RGBA") == 0 ||
- strcmp(im->mode, "La") == 0 ||
- strcmp(im->mode, "LA") == 0 ||
- strcmp(im->mode, "PA") == 0) {
+ INT32 mask = 0xffffffff;
+ if (im->bands == 3) {
+ ((UINT8*) &mask)[3] = 0;
+ } else if (strcmp(im->mode, "RGBa") == 0 ||
+ strcmp(im->mode, "RGBA") == 0 ||
+ strcmp(im->mode, "La") == 0 ||
+ strcmp(im->mode, "LA") == 0 ||
+ strcmp(im->mode, "PA") == 0) {
#ifdef WORDS_BIGENDIAN
- mask = 0x000000ff;
+ mask = 0x000000ff;
#else
- mask = 0xff000000;
+ mask = 0xff000000;
#endif
- }
- GETBBOX(image32, mask);
+ }
+ GETBBOX(image32, mask);
}
/* Check that we got a box */
- if (bbox[1] < 0)
- return 0; /* no data */
+ if (bbox[1] < 0) {
+ return 0; /* no data */
+ }
return 1; /* ok */
}
@@ -91,25 +96,28 @@ ImagingGetProjection(Imaging im, UINT8* xproj, UINT8* yproj)
memset(xproj, 0, im->xsize);
memset(yproj, 0, im->ysize);
-#define GETPROJ(image, mask)\
- for (y = 0; y < im->ysize; y++) {\
- has_data = 0;\
- for (x = 0; x < im->xsize; x++)\
- if (im->image[y][x] & mask) {\
- has_data = 1;\
- xproj[x] = 1;\
- }\
- if (has_data)\
- yproj[y] = 1;\
- }
+ #define GETPROJ(image, mask)\
+ for (y = 0; y < im->ysize; y++) {\
+ has_data = 0;\
+ for (x = 0; x < im->xsize; x++) {\
+ if (im->image[y][x] & mask) {\
+ has_data = 1;\
+ xproj[x] = 1;\
+ }\
+ }\
+ if (has_data) {\
+ yproj[y] = 1;\
+ }\
+ }
if (im->image8) {
- GETPROJ(image8, 0xff);
+ GETPROJ(image8, 0xff);
} else {
- INT32 mask = 0xffffffff;
- if (im->bands == 3)
- ((UINT8*) &mask)[3] = 0;
- GETPROJ(image32, mask);
+ INT32 mask = 0xffffffff;
+ if (im->bands == 3) {
+ ((UINT8*) &mask)[3] = 0;
+ }
+ GETPROJ(image32, mask);
}
return 1; /* ok */
@@ -124,12 +132,13 @@ ImagingGetExtrema(Imaging im, void *extrema)
FLOAT32 fmin, fmax;
if (im->bands != 1) {
- (void) ImagingError_ModeError();
+ (void) ImagingError_ModeError();
return -1; /* mismatch */
}
- if (!im->xsize || !im->ysize)
+ if (!im->xsize || !im->ysize) {
return 0; /* zero size */
+ }
switch (im->type) {
case IMAGING_TYPE_UINT8:
@@ -137,10 +146,11 @@ ImagingGetExtrema(Imaging im, void *extrema)
for (y = 0; y < im->ysize; y++) {
UINT8* in = im->image8[y];
for (x = 0; x < im->xsize; x++) {
- if (imin > in[x])
+ if (imin > in[x]) {
imin = in[x];
- else if (imax < in[x])
+ } else if (imax < in[x]) {
imax = in[x];
+ }
}
}
((UINT8*) extrema)[0] = (UINT8) imin;
@@ -151,10 +161,11 @@ ImagingGetExtrema(Imaging im, void *extrema)
for (y = 0; y < im->ysize; y++) {
INT32* in = im->image32[y];
for (x = 0; x < im->xsize; x++) {
- if (imin > in[x])
+ if (imin > in[x]) {
imin = in[x];
- else if (imax < in[x])
+ } else if (imax < in[x]) {
imax = in[x];
+ }
}
}
memcpy(extrema, &imin, sizeof(imin));
@@ -165,10 +176,11 @@ ImagingGetExtrema(Imaging im, void *extrema)
for (y = 0; y < im->ysize; y++) {
FLOAT32* in = (FLOAT32*) im->image32[y];
for (x = 0; x < im->xsize; x++) {
- if (fmin > in[x])
+ if (fmin > in[x]) {
fmin = in[x];
- else if (fmax < in[x])
+ } else if (fmax < in[x]) {
fmax = in[x];
+ }
}
}
memcpy(extrema, &fmin, sizeof(fmin));
@@ -192,21 +204,22 @@ ImagingGetExtrema(Imaging im, void *extrema)
#else
memcpy(&v, pixel, sizeof(v));
#endif
- if (imin > v)
+ if (imin > v) {
imin = v;
- else if (imax < v)
+ } else if (imax < v) {
imax = v;
+ }
}
}
v = (UINT16) imin;
memcpy(extrema, &v, sizeof(v));
v = (UINT16) imax;
memcpy(((char*)extrema) + sizeof(v), &v, sizeof(v));
- break;
+ break;
}
/* FALL THROUGH */
default:
- (void) ImagingError_ModeError();
+ (void) ImagingError_ModeError();
return -1;
}
return 1; /* ok */
@@ -264,19 +277,23 @@ getcolors32(Imaging im, int maxcolors, int* size)
/* printf("code_size=%d\n", code_size); */
/* printf("code_poly=%d\n", code_poly); */
- if (!code_size)
- return ImagingError_MemoryError(); /* just give up */
+ if (!code_size) {
+ return ImagingError_MemoryError(); /* just give up */
+ }
- if (!im->image32)
- return ImagingError_ModeError();
+ if (!im->image32) {
+ return ImagingError_ModeError();
+ }
table = calloc(code_size + 1, sizeof(ImagingColorItem));
- if (!table)
- return ImagingError_MemoryError();
+ if (!table) {
+ return ImagingError_MemoryError();
+ }
pixel_mask = 0xffffffff;
- if (im->bands == 3)
+ if (im->bands == 3) {
((UINT8*) &pixel_mask)[3] = 0;
+ }
colors = 0;
@@ -289,8 +306,9 @@ getcolors32(Imaging im, int maxcolors, int* size)
v = &table[i];
if (!v->count) {
/* add to table */
- if (colors++ == maxcolors)
+ if (colors++ == maxcolors) {
goto overflow;
+ }
v->x = x; v->y = y;
v->pixel = pixel;
v->count = 1;
@@ -300,15 +318,17 @@ getcolors32(Imaging im, int maxcolors, int* size)
continue;
}
incr = (h ^ (h >> 3)) & code_mask;
- if (!incr)
+ if (!incr) {
incr = code_mask;
+ }
for (;;) {
i = (i + incr) & code_mask;
v = &table[i];
if (!v->count) {
/* add to table */
- if (colors++ == maxcolors)
+ if (colors++ == maxcolors) {
goto overflow;
+ }
v->x = x; v->y = y;
v->pixel = pixel;
v->count = 1;
@@ -318,8 +338,9 @@ getcolors32(Imaging im, int maxcolors, int* size)
break;
}
incr = incr << 1;
- if (incr > code_mask)
+ if (incr > code_mask) {
incr = incr ^ code_poly;
+ }
}
}
}
@@ -329,8 +350,9 @@ overflow:
/* pack the table */
for (x = y = 0; x < (int) code_size; x++)
if (table[x].count) {
- if (x != y)
+ if (x != y) {
table[y] = table[x];
+ }
y++;
}
table[y].count = 0; /* mark end of table */
diff --git a/src/libImaging/Gif.h b/src/libImaging/Gif.h
index 2cb95efd2..bb118396c 100644
--- a/src/libImaging/Gif.h
+++ b/src/libImaging/Gif.h
@@ -10,10 +10,10 @@
/* Max size for a LZW code word. */
-#define GIFBITS 12
+#define GIFBITS 12
-#define GIFTABLE (1<
-#include /* memcpy() */
+#include /* memcpy() */
#include "Gif.h"
@@ -34,26 +34,27 @@
state->x = 0;\
state->y += context->step;\
while (state->y >= state->ysize)\
- switch (context->interlace) {\
- case 1:\
- context->repeat = state->y = 4;\
- context->interlace = 2;\
- break;\
- case 2:\
- context->step = 4;\
- context->repeat = state->y = 2;\
- context->interlace = 3;\
- break;\
- case 3:\
- context->step = 2;\
- context->repeat = state->y = 1;\
- context->interlace = 0;\
- break;\
- default:\
- return -1;\
+ switch (context->interlace) {\
+ case 1:\
+ context->repeat = state->y = 4;\
+ context->interlace = 2;\
+ break;\
+ case 2:\
+ context->step = 4;\
+ context->repeat = state->y = 2;\
+ context->interlace = 3;\
+ break;\
+ case 3:\
+ context->step = 2;\
+ context->repeat = state->y = 1;\
+ context->interlace = 0;\
+ break;\
+ default:\
+ return -1;\
}\
- if (state->y < state->ysize)\
+ if (state->y < state->ysize) {\
out = im->image8[state->y + state->yoff] + state->xoff;\
+ }\
}
@@ -70,227 +71,232 @@ ImagingGifDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t
if (!state->state) {
- /* Initialise state */
- if (context->bits < 0 || context->bits > 12) {
- state->errcode = IMAGING_CODEC_CONFIG;
- return -1;
- }
+ /* Initialise state */
+ if (context->bits < 0 || context->bits > 12) {
+ state->errcode = IMAGING_CODEC_CONFIG;
+ return -1;
+ }
- /* Clear code */
- context->clear = 1 << context->bits;
+ /* Clear code */
+ context->clear = 1 << context->bits;
- /* End code */
- context->end = context->clear + 1;
+ /* End code */
+ context->end = context->clear + 1;
- /* Interlace */
- if (context->interlace) {
- context->interlace = 1;
- context->step = context->repeat = 8;
- } else
- context->step = 1;
+ /* Interlace */
+ if (context->interlace) {
+ context->interlace = 1;
+ context->step = context->repeat = 8;
+ } else {
+ context->step = 1;
+ }
- state->state = 1;
+ state->state = 1;
}
out = im->image8[state->y + state->yoff] + state->xoff + state->x;
for (;;) {
- if (state->state == 1) {
+ if (state->state == 1) {
- /* First free entry in table */
- context->next = context->clear + 2;
+ /* First free entry in table */
+ context->next = context->clear + 2;
- /* Initial code size */
- context->codesize = context->bits + 1;
- context->codemask = (1 << context->codesize) - 1;
+ /* Initial code size */
+ context->codesize = context->bits + 1;
+ context->codemask = (1 << context->codesize) - 1;
- /* Buffer pointer. We fill the buffer from right, which
- allows us to return all of it in one operation. */
- context->bufferindex = GIFBUFFER;
+ /* Buffer pointer. We fill the buffer from right, which
+ allows us to return all of it in one operation. */
+ context->bufferindex = GIFBUFFER;
- state->state = 2;
- }
+ state->state = 2;
+ }
- if (context->bufferindex < GIFBUFFER) {
+ if (context->bufferindex < GIFBUFFER) {
- /* Return whole buffer in one chunk */
- i = GIFBUFFER - context->bufferindex;
- p = &context->buffer[context->bufferindex];
+ /* Return whole buffer in one chunk */
+ i = GIFBUFFER - context->bufferindex;
+ p = &context->buffer[context->bufferindex];
- context->bufferindex = GIFBUFFER;
+ context->bufferindex = GIFBUFFER;
- } else {
+ } else {
- /* Get current symbol */
+ /* Get current symbol */
- while (context->bitcount < context->codesize) {
+ while (context->bitcount < context->codesize) {
- if (context->blocksize > 0) {
+ if (context->blocksize > 0) {
- /* Read next byte */
- c = *ptr++; bytes--;
+ /* Read next byte */
+ c = *ptr++; bytes--;
- context->blocksize--;
+ context->blocksize--;
- /* New bits are shifted in from from the left. */
- context->bitbuffer |= (INT32) c << context->bitcount;
- context->bitcount += 8;
+ /* New bits are shifted in from from the left. */
+ context->bitbuffer |= (INT32) c << context->bitcount;
+ context->bitcount += 8;
- } else {
+ } else {
- /* New GIF block */
+ /* New GIF block */
- /* We don't start decoding unless we have a full block */
- if (bytes < 1)
- return ptr - buffer;
- c = *ptr;
- if (bytes < c+1)
- return ptr - buffer;
+ /* We don't start decoding unless we have a full block */
+ if (bytes < 1) {
+ return ptr - buffer;
+ }
+ c = *ptr;
+ if (bytes < c+1) {
+ return ptr - buffer;
+ }
- context->blocksize = c;
+ context->blocksize = c;
- ptr++; bytes--;
+ ptr++; bytes--;
- }
- }
+ }
+ }
- /* Extract current symbol from bit buffer. */
- c = (int) context->bitbuffer & context->codemask;
+ /* Extract current symbol from bit buffer. */
+ c = (int) context->bitbuffer & context->codemask;
- /* Adjust buffer */
- context->bitbuffer >>= context->codesize;
- context->bitcount -= context->codesize;
+ /* Adjust buffer */
+ context->bitbuffer >>= context->codesize;
+ context->bitcount -= context->codesize;
- /* If c is less than "clear", it's a data byte. Otherwise,
- it's either clear/end or a code symbol which should be
- expanded. */
+ /* If c is less than "clear", it's a data byte. Otherwise,
+ it's either clear/end or a code symbol which should be
+ expanded. */
- if (c == context->clear) {
- if (state->state != 2)
- state->state = 1;
- continue;
- }
+ if (c == context->clear) {
+ if (state->state != 2) {
+ state->state = 1;
+ }
+ continue;
+ }
- if (c == context->end)
- break;
+ if (c == context->end) {
+ break;
+ }
- i = 1;
- p = &context->lastdata;
+ i = 1;
+ p = &context->lastdata;
- if (state->state == 2) {
+ if (state->state == 2) {
- /* First valid symbol after clear; use as is */
- if (c > context->clear) {
- state->errcode = IMAGING_CODEC_BROKEN;
- return -1;
- }
+ /* First valid symbol after clear; use as is */
+ if (c > context->clear) {
+ state->errcode = IMAGING_CODEC_BROKEN;
+ return -1;
+ }
- context->lastdata = context->lastcode = c;
- state->state = 3;
+ context->lastdata = context->lastcode = c;
+ state->state = 3;
- } else {
+ } else {
- thiscode = c;
+ thiscode = c;
- if (c > context->next) {
- state->errcode = IMAGING_CODEC_BROKEN;
- return -1;
- }
+ if (c > context->next) {
+ state->errcode = IMAGING_CODEC_BROKEN;
+ return -1;
+ }
- if (c == context->next) {
+ if (c == context->next) {
- /* c == next is allowed. not sure why. */
+ /* c == next is allowed. not sure why. */
- if (context->bufferindex <= 0) {
- state->errcode = IMAGING_CODEC_BROKEN;
- return -1;
- }
+ if (context->bufferindex <= 0) {
+ state->errcode = IMAGING_CODEC_BROKEN;
+ return -1;
+ }
- context->buffer[--context->bufferindex] =
- context->lastdata;
+ context->buffer[--context->bufferindex] =
+ context->lastdata;
- c = context->lastcode;
+ c = context->lastcode;
- }
+ }
- while (c >= context->clear) {
+ while (c >= context->clear) {
- /* Copy data string to buffer (beginning from right) */
+ /* Copy data string to buffer (beginning from right) */
- if (context->bufferindex <= 0 || c >= GIFTABLE) {
- state->errcode = IMAGING_CODEC_BROKEN;
- return -1;
- }
+ if (context->bufferindex <= 0 || c >= GIFTABLE) {
+ state->errcode = IMAGING_CODEC_BROKEN;
+ return -1;
+ }
- context->buffer[--context->bufferindex] =
- context->data[c];
+ context->buffer[--context->bufferindex] =
+ context->data[c];
- c = context->link[c];
- }
+ c = context->link[c];
+ }
- context->lastdata = c;
+ context->lastdata = c;
- if (context->next < GIFTABLE) {
+ if (context->next < GIFTABLE) {
- /* We'll only add this symbol if we have room
- for it (take advise, Netscape!) */
- context->data[context->next] = c;
- context->link[context->next] = context->lastcode;
+ /* We'll only add this symbol if we have room
+ for it (take advise, Netscape!) */
+ context->data[context->next] = c;
+ context->link[context->next] = context->lastcode;
- if (context->next == context->codemask &&
- context->codesize < GIFBITS) {
+ if (context->next == context->codemask &&
+ context->codesize < GIFBITS) {
- /* Expand code size */
- context->codesize++;
- context->codemask = (1 << context->codesize) - 1;
- }
+ /* Expand code size */
+ context->codesize++;
+ context->codemask = (1 << context->codesize) - 1;
+ }
- context->next++;
+ context->next++;
- }
+ }
- context->lastcode = thiscode;
+ context->lastcode = thiscode;
- }
- }
+ }
+ }
- /* Copy the bytes into the image */
- if (state->y >= state->ysize) {
- state->errcode = IMAGING_CODEC_OVERRUN;
- return -1;
- }
+ /* Copy the bytes into the image */
+ if (state->y >= state->ysize) {
+ state->errcode = IMAGING_CODEC_OVERRUN;
+ return -1;
+ }
- /* To squeeze some extra pixels out of this loop, we test for
- some common cases and handle them separately. */
+ /* To squeeze some extra pixels out of this loop, we test for
+ some common cases and handle them separately. */
- /* FIXME: should we handle the transparency index in here??? */
+ /* FIXME: should we handle the transparency index in here??? */
- if (i == 1) {
- if (state->x < state->xsize-1) {
- /* Single pixel, not at the end of the line. */
- *out++ = p[0];
- state->x++;
- continue;
- }
- } else if (state->x + i <= state->xsize) {
- /* This string fits into current line. */
- memcpy(out, p, i);
- out += i;
- state->x += i;
- if (state->x == state->xsize) {
- NEWLINE(state, context);
- }
- continue;
- }
+ if (i == 1) {
+ if (state->x < state->xsize-1) {
+ /* Single pixel, not at the end of the line. */
+ *out++ = p[0];
+ state->x++;
+ continue;
+ }
+ } else if (state->x + i <= state->xsize) {
+ /* This string fits into current line. */
+ memcpy(out, p, i);
+ out += i;
+ state->x += i;
+ if (state->x == state->xsize) {
+ NEWLINE(state, context);
+ }
+ continue;
+ }
- /* No shortcut, copy pixel by pixel */
- for (c = 0; c < i; c++) {
- *out++ = p[c];
- if (++state->x >= state->xsize) {
- NEWLINE(state, context);
- }
- }
+ /* No shortcut, copy pixel by pixel */
+ for (c = 0; c < i; c++) {
+ *out++ = p[c];
+ if (++state->x >= state->xsize) {
+ NEWLINE(state, context);
+ }
+ }
}
return ptr - buffer;
diff --git a/src/libImaging/GifEncode.c b/src/libImaging/GifEncode.c
index f211814ed..e9c6c3149 100644
--- a/src/libImaging/GifEncode.c
+++ b/src/libImaging/GifEncode.c
@@ -5,11 +5,11 @@
* encoder for uncompressed GIF data
*
* history:
- * 97-01-05 fl created (writes uncompressed data)
- * 97-08-27 fl fixed off-by-one error in buffer size test
- * 98-07-09 fl added interlace write support
- * 99-02-07 fl rewritten, now uses a run-length encoding strategy
- * 99-02-08 fl improved run-length encoding for long runs
+ * 97-01-05 fl created (writes uncompressed data)
+ * 97-08-27 fl fixed off-by-one error in buffer size test
+ * 98-07-09 fl added interlace write support
+ * 99-02-07 fl rewritten, now uses a run-length encoding strategy
+ * 99-02-08 fl improved run-length encoding for long runs
*
* Copyright (c) Secret Labs AB 1997-99.
* Copyright (c) Fredrik Lundh 1997.
@@ -48,12 +48,14 @@ emit(GIFENCODERSTATE *context, int byte)
/* add current block to end of flush queue */
if (context->block) {
block = context->flush;
- while (block && block->next)
+ while (block && block->next) {
block = block->next;
- if (block)
+ }
+ if (block) {
block->next = context->block;
- else
+ } else {
context->flush = context->block;
+ }
}
/* get a new block */
@@ -63,8 +65,9 @@ emit(GIFENCODERSTATE *context, int byte)
} else {
/* malloc check ok, small constant allocation */
block = malloc(sizeof(GIFENCODERBLOCK));
- if (!block)
+ if (!block) {
return 0;
+ }
}
block->size = 0;
@@ -145,23 +148,25 @@ ImagingGifEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
if (!state->state) {
- /* place a clear code in the output buffer */
- context->bitbuffer = CLEAR_CODE;
- context->bitcount = 9;
+ /* place a clear code in the output buffer */
+ context->bitbuffer = CLEAR_CODE;
+ context->bitcount = 9;
- state->count = FIRST_CODE;
+ state->count = FIRST_CODE;
- if (context->interlace) {
- context->interlace = 1;
- context->step = 8;
- } else
- context->step = 1;
+ if (context->interlace) {
+ context->interlace = 1;
+ context->step = 8;
+ } else {
+ context->step = 1;
+ }
context->last = -1;
/* sanity check */
- if (state->xsize <= 0 || state->ysize <= 0)
+ if (state->xsize <= 0 || state->ysize <= 0) {
state->state = ENCODE_EOF;
+ }
}
@@ -169,152 +174,157 @@ ImagingGifEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
for (;;)
- switch (state->state) {
+ switch (state->state) {
- case INIT:
- case ENCODE:
+ case INIT:
+ case ENCODE:
- /* identify and store a run of pixels */
+ /* identify and store a run of pixels */
- if (state->x == 0 || state->x >= state->xsize) {
+ if (state->x == 0 || state->x >= state->xsize) {
- if (!context->interlace && state->y >= state->ysize) {
- state->state = ENCODE_EOF;
- break;
- }
-
- if (context->flush) {
- state->state = FLUSH;
- break;
- }
-
- /* get another line of data */
- state->shuffle(
- state->buffer,
- (UINT8*) im->image[state->y + state->yoff] +
- state->xoff * im->pixelsize, state->xsize
- );
-
- state->x = 0;
-
- if (state->state == INIT) {
- /* preload the run-length buffer and get going */
- context->last = state->buffer[0];
- context->count = state->x = 1;
- state->state = ENCODE;
- }
-
- /* step forward, according to the interlace settings */
- state->y += context->step;
- while (context->interlace && state->y >= state->ysize)
- switch (context->interlace) {
- case 1:
- state->y = 4;
- context->interlace = 2;
+ if (!context->interlace && state->y >= state->ysize) {
+ state->state = ENCODE_EOF;
break;
- case 2:
- context->step = 4;
- state->y = 2;
- context->interlace = 3;
- break;
- case 3:
- context->step = 2;
- state->y = 1;
- context->interlace = 0;
- break;
- default:
- /* just make sure we don't loop forever */
- context->interlace = 0;
}
- }
+ if (context->flush) {
+ state->state = FLUSH;
+ break;
+ }
- this = state->buffer[state->x++];
+ /* get another line of data */
+ state->shuffle(
+ state->buffer,
+ (UINT8*) im->image[state->y + state->yoff] +
+ state->xoff * im->pixelsize, state->xsize
+ );
- if (this == context->last)
- context->count++;
- else {
- EMIT_RUN(label1);
- context->last = this;
- context->count = 1;
- }
- break;
+ state->x = 0;
+ if (state->state == INIT) {
+ /* preload the run-length buffer and get going */
+ context->last = state->buffer[0];
+ context->count = state->x = 1;
+ state->state = ENCODE;
+ }
- case ENCODE_EOF:
+ /* step forward, according to the interlace settings */
+ state->y += context->step;
+ while (context->interlace && state->y >= state->ysize)
+ switch (context->interlace) {
+ case 1:
+ state->y = 4;
+ context->interlace = 2;
+ break;
+ case 2:
+ context->step = 4;
+ state->y = 2;
+ context->interlace = 3;
+ break;
+ case 3:
+ context->step = 2;
+ state->y = 1;
+ context->interlace = 0;
+ break;
+ default:
+ /* just make sure we don't loop forever */
+ context->interlace = 0;
+ }
- /* write the final run */
- EMIT_RUN(label2);
-
- /* write an end of image marker */
- EMIT(EOF_CODE);
-
- /* empty the bit buffer */
- while (context->bitcount > 0) {
- if (!emit(context, (UINT8) context->bitbuffer)) {
- state->errcode = IMAGING_CODEC_MEMORY;
- return 0;
}
- context->bitbuffer >>= 8;
- context->bitcount -= 8;
- }
- /* flush the last block, and exit */
- if (context->block) {
- GIFENCODERBLOCK* block;
- block = context->flush;
- while (block && block->next)
- block = block->next;
- if (block)
- block->next = context->block;
- else
- context->flush = context->block;
- context->block = NULL;
- }
+ this = state->buffer[state->x++];
- state->state = EXIT;
+ if (this == context->last) {
+ context->count++;
+ } else {
+ EMIT_RUN(label1);
+ context->last = this;
+ context->count = 1;
+ }
+ break;
- /* fall through... */
- case EXIT:
- case FLUSH:
+ case ENCODE_EOF:
- while (context->flush) {
+ /* write the final run */
+ EMIT_RUN(label2);
- /* get a block from the flush queue */
- block = context->flush;
+ /* write an end of image marker */
+ EMIT(EOF_CODE);
- if (block->size > 0) {
+ /* empty the bit buffer */
+ while (context->bitcount > 0) {
+ if (!emit(context, (UINT8) context->bitbuffer)) {
+ state->errcode = IMAGING_CODEC_MEMORY;
+ return 0;
+ }
+ context->bitbuffer >>= 8;
+ context->bitcount -= 8;
+ }
- /* make sure it fits into the output buffer */
- if (bytes < block->size+1)
+ /* flush the last block, and exit */
+ if (context->block) {
+ GIFENCODERBLOCK* block;
+ block = context->flush;
+ while (block && block->next) {
+ block = block->next;
+ }
+ if (block) {
+ block->next = context->block;
+ } else {
+ context->flush = context->block;
+ }
+ context->block = NULL;
+ }
+
+ state->state = EXIT;
+
+ /* fall through... */
+
+ case EXIT:
+ case FLUSH:
+
+ while (context->flush) {
+
+ /* get a block from the flush queue */
+ block = context->flush;
+
+ if (block->size > 0) {
+
+ /* make sure it fits into the output buffer */
+ if (bytes < block->size+1) {
+ return ptr - buf;
+ }
+
+ ptr[0] = block->size;
+ memcpy(ptr+1, block->data, block->size);
+
+ ptr += block->size+1;
+ bytes -= block->size+1;
+
+ }
+
+ context->flush = block->next;
+
+ if (context->free) {
+ free(context->free);
+ }
+ context->free = block;
+
+ }
+
+ if (state->state == EXIT) {
+ /* this was the last block! */
+ if (context->free) {
+ free(context->free);
+ }
+ state->errcode = IMAGING_CODEC_END;
return ptr - buf;
+ }
- ptr[0] = block->size;
- memcpy(ptr+1, block->data, block->size);
-
- ptr += block->size+1;
- bytes -= block->size+1;
-
- }
-
- context->flush = block->next;
-
- if (context->free)
- free(context->free);
- context->free = block;
-
- }
-
- if (state->state == EXIT) {
- /* this was the last block! */
- if (context->free)
- free(context->free);
- state->errcode = IMAGING_CODEC_END;
- return ptr - buf;
- }
-
- state->state = ENCODE;
- break;
- }
+ state->state = ENCODE;
+ break;
+ }
}
diff --git a/src/libImaging/HexDecode.c b/src/libImaging/HexDecode.c
index 8bd9bf67f..1def8766f 100644
--- a/src/libImaging/HexDecode.c
+++ b/src/libImaging/HexDecode.c
@@ -5,7 +5,7 @@
* decoder for hex encoded image data
*
* history:
- * 96-05-16 fl Created
+ * 96-05-16 fl Created
*
* Copyright (c) Fredrik Lundh 1996.
* Copyright (c) Secret Labs AB 1997.
@@ -16,9 +16,9 @@
#include "Imaging.h"
-#define HEX(v) ((v >= '0' && v <= '9') ? v - '0' :\
- (v >= 'a' && v <= 'f') ? v - 'a' + 10 :\
- (v >= 'A' && v <= 'F') ? v - 'A' + 10 : -1)
+#define HEX(v) ((v >= '0' && v <= '9') ? v - '0' :\
+ (v >= 'a' && v <= 'f') ? v - 'a' + 10 :\
+ (v >= 'A' && v <= 'F') ? v - 'A' + 10 : -1)
int
ImagingHexDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes)
@@ -30,38 +30,39 @@ ImagingHexDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt
for (;;) {
- if (bytes < 2)
- return ptr - buf;
+ if (bytes < 2) {
+ return ptr - buf;
+ }
- a = HEX(ptr[0]);
- b = HEX(ptr[1]);
+ a = HEX(ptr[0]);
+ b = HEX(ptr[1]);
- if (a < 0 || b < 0) {
+ if (a < 0 || b < 0) {
- ptr++;
- bytes--;
+ ptr++;
+ bytes--;
- } else {
+ } else {
- ptr += 2;
- bytes -= 2;
+ ptr += 2;
+ bytes -= 2;
- state->buffer[state->x] = (a<<4) + b;
+ state->buffer[state->x] = (a<<4) + b;
- if (++state->x >= state->bytes) {
+ if (++state->x >= state->bytes) {
- /* Got a full line, unpack it */
- state->shuffle((UINT8*) im->image[state->y], state->buffer,
- state->xsize);
+ /* Got a full line, unpack it */
+ state->shuffle((UINT8*) im->image[state->y], state->buffer,
+ state->xsize);
- state->x = 0;
+ state->x = 0;
- if (++state->y >= state->ysize) {
- /* End of file (errcode = 0) */
- return -1;
- }
- }
+ if (++state->y >= state->ysize) {
+ /* End of file (errcode = 0) */
+ return -1;
+ }
+ }
- }
+ }
}
}
diff --git a/src/libImaging/Histo.c b/src/libImaging/Histo.c
index 5c2824ab0..050c2840f 100644
--- a/src/libImaging/Histo.c
+++ b/src/libImaging/Histo.c
@@ -29,8 +29,9 @@
void
ImagingHistogramDelete(ImagingHistogram h)
{
- if (h->histogram)
- free(h->histogram);
+ if (h->histogram) {
+ free(h->histogram);
+ }
free(h);
}
@@ -59,116 +60,132 @@ ImagingGetHistogram(Imaging im, Imaging imMask, void* minmax)
INT32 imin, imax;
FLOAT32 fmin, fmax, scale;
- if (!im)
- return ImagingError_ModeError();
+ if (!im) {
+ return ImagingError_ModeError();
+ }
if (imMask) {
- /* Validate mask */
- if (im->xsize != imMask->xsize || im->ysize != imMask->ysize)
- return ImagingError_Mismatch();
- if (strcmp(imMask->mode, "1") != 0 && strcmp(imMask->mode, "L") != 0)
- return ImagingError_ValueError("bad transparency mask");
+ /* Validate mask */
+ if (im->xsize != imMask->xsize || im->ysize != imMask->ysize) {
+ return ImagingError_Mismatch();
+ }
+ if (strcmp(imMask->mode, "1") != 0 && strcmp(imMask->mode, "L") != 0) {
+ return ImagingError_ValueError("bad transparency mask");
+ }
}
h = ImagingHistogramNew(im);
if (imMask) {
- /* mask */
- if (im->image8) {
+ /* mask */
+ if (im->image8) {
ImagingSectionEnter(&cookie);
- for (y = 0; y < im->ysize; y++)
- for (x = 0; x < im->xsize; x++)
- if (imMask->image8[y][x] != 0)
- h->histogram[im->image8[y][x]]++;
+ for (y = 0; y < im->ysize; y++) {
+ for (x = 0; x < im->xsize; x++) {
+ if (imMask->image8[y][x] != 0) {
+ h->histogram[im->image8[y][x]]++;
+ }
+ }
+ }
ImagingSectionLeave(&cookie);
- } else { /* yes, we need the braces. C isn't Python! */
+ } else { /* yes, we need the braces. C isn't Python! */
if (im->type != IMAGING_TYPE_UINT8) {
ImagingHistogramDelete(h);
return ImagingError_ModeError();
}
ImagingSectionEnter(&cookie);
- for (y = 0; y < im->ysize; y++) {
- UINT8* in = (UINT8*) im->image32[y];
- for (x = 0; x < im->xsize; x++)
- if (imMask->image8[y][x] != 0) {
- h->histogram[(*in++)]++;
- h->histogram[(*in++)+256]++;
- h->histogram[(*in++)+512]++;
- h->histogram[(*in++)+768]++;
- } else
- in += 4;
- }
- ImagingSectionLeave(&cookie);
- }
- } else {
- /* mask not given; process pixels in image */
- if (im->image8) {
- ImagingSectionEnter(&cookie);
- for (y = 0; y < im->ysize; y++)
- for (x = 0; x < im->xsize; x++)
- h->histogram[im->image8[y][x]]++;
- ImagingSectionLeave(&cookie);
- } else {
- switch (im->type) {
- case IMAGING_TYPE_UINT8:
- ImagingSectionEnter(&cookie);
- for (y = 0; y < im->ysize; y++) {
- UINT8* in = (UINT8*) im->image[y];
- for (x = 0; x < im->xsize; x++) {
+ for (y = 0; y < im->ysize; y++) {
+ UINT8* in = (UINT8*) im->image32[y];
+ for (x = 0; x < im->xsize; x++) {
+ if (imMask->image8[y][x] != 0) {
h->histogram[(*in++)]++;
h->histogram[(*in++)+256]++;
h->histogram[(*in++)+512]++;
h->histogram[(*in++)+768]++;
+ } else {
+ in += 4;
}
}
- ImagingSectionLeave(&cookie);
- break;
- case IMAGING_TYPE_INT32:
- if (!minmax) {
- ImagingHistogramDelete(h);
- return ImagingError_ValueError("min/max not given");
+ }
+ ImagingSectionLeave(&cookie);
+ }
+ } else {
+ /* mask not given; process pixels in image */
+ if (im->image8) {
+ ImagingSectionEnter(&cookie);
+ for (y = 0; y < im->ysize; y++) {
+ for (x = 0; x < im->xsize; x++) {
+ h->histogram[im->image8[y][x]]++;
}
- if (!im->xsize || !im->ysize)
- break;
- memcpy(&imin, minmax, sizeof(imin));
- memcpy(&imax, ((char*)minmax) + sizeof(imin), sizeof(imax));
- if (imin >= imax)
- break;
- ImagingSectionEnter(&cookie);
- scale = 255.0F / (imax - imin);
- for (y = 0; y < im->ysize; y++) {
- INT32* in = im->image32[y];
- for (x = 0; x < im->xsize; x++) {
- i = (int) (((*in++)-imin)*scale);
- if (i >= 0 && i < 256)
- h->histogram[i]++;
+ }
+ ImagingSectionLeave(&cookie);
+ } else {
+ switch (im->type) {
+ case IMAGING_TYPE_UINT8:
+ ImagingSectionEnter(&cookie);
+ for (y = 0; y < im->ysize; y++) {
+ UINT8* in = (UINT8*) im->image[y];
+ for (x = 0; x < im->xsize; x++) {
+ h->histogram[(*in++)]++;
+ h->histogram[(*in++)+256]++;
+ h->histogram[(*in++)+512]++;
+ h->histogram[(*in++)+768]++;
+ }
}
- }
- ImagingSectionLeave(&cookie);
- break;
- case IMAGING_TYPE_FLOAT32:
- if (!minmax) {
- ImagingHistogramDelete(h);
- return ImagingError_ValueError("min/max not given");
- }
- if (!im->xsize || !im->ysize)
+ ImagingSectionLeave(&cookie);
break;
- memcpy(&fmin, minmax, sizeof(fmin));
- memcpy(&fmax, ((char*)minmax) + sizeof(fmin), sizeof(fmax));
- if (fmin >= fmax)
- break;
- ImagingSectionEnter(&cookie);
- scale = 255.0F / (fmax - fmin);
- for (y = 0; y < im->ysize; y++) {
- FLOAT32* in = (FLOAT32*) im->image32[y];
- for (x = 0; x < im->xsize; x++) {
- i = (int) (((*in++)-fmin)*scale);
- if (i >= 0 && i < 256)
- h->histogram[i]++;
+ case IMAGING_TYPE_INT32:
+ if (!minmax) {
+ ImagingHistogramDelete(h);
+ return ImagingError_ValueError("min/max not given");
}
- }
- ImagingSectionLeave(&cookie);
- break;
+ if (!im->xsize || !im->ysize) {
+ break;
+ }
+ memcpy(&imin, minmax, sizeof(imin));
+ memcpy(&imax, ((char*)minmax) + sizeof(imin), sizeof(imax));
+ if (imin >= imax) {
+ break;
+ }
+ ImagingSectionEnter(&cookie);
+ scale = 255.0F / (imax - imin);
+ for (y = 0; y < im->ysize; y++) {
+ INT32* in = im->image32[y];
+ for (x = 0; x < im->xsize; x++) {
+ i = (int) (((*in++)-imin)*scale);
+ if (i >= 0 && i < 256) {
+ h->histogram[i]++;
+ }
+ }
+ }
+ ImagingSectionLeave(&cookie);
+ break;
+ case IMAGING_TYPE_FLOAT32:
+ if (!minmax) {
+ ImagingHistogramDelete(h);
+ return ImagingError_ValueError("min/max not given");
+ }
+ if (!im->xsize || !im->ysize) {
+ break;
+ }
+ memcpy(&fmin, minmax, sizeof(fmin));
+ memcpy(&fmax, ((char*)minmax) + sizeof(fmin), sizeof(fmax));
+ if (fmin >= fmax) {
+ break;
+ }
+ ImagingSectionEnter(&cookie);
+ scale = 255.0F / (fmax - fmin);
+ for (y = 0; y < im->ysize; y++) {
+ FLOAT32* in = (FLOAT32*) im->image32[y];
+ for (x = 0; x < im->xsize; x++) {
+ i = (int) (((*in++)-fmin)*scale);
+ if (i >= 0 && i < 256) {
+ h->histogram[i]++;
+ }
+ }
+ }
+ ImagingSectionLeave(&cookie);
+ break;
}
}
}
diff --git a/src/libImaging/ImPlatform.h b/src/libImaging/ImPlatform.h
index b2d4db785..576ceaa58 100644
--- a/src/libImaging/ImPlatform.h
+++ b/src/libImaging/ImPlatform.h
@@ -39,41 +39,41 @@
/* For System that are not Windows, we'll need to define these. */
#if SIZEOF_SHORT == 2
-#define INT16 short
+#define INT16 short
#elif SIZEOF_INT == 2
-#define INT16 int
+#define INT16 int
#else
-#define INT16 short /* most things works just fine anyway... */
+#define INT16 short /* most things works just fine anyway... */
#endif
#if SIZEOF_SHORT == 4
-#define INT32 short
+#define INT32 short
#elif SIZEOF_INT == 4
-#define INT32 int
+#define INT32 int
#elif SIZEOF_LONG == 4
-#define INT32 long
+#define INT32 long
#else
#error Cannot find required 32-bit integer type
#endif
#if SIZEOF_LONG == 8
-#define INT64 long
+#define INT64 long
#elif SIZEOF_LONG_LONG == 8
-#define INT64 long
+#define INT64 long
#endif
-#define INT8 signed char
-#define UINT8 unsigned char
+#define INT8 signed char
+#define UINT8 unsigned char
-#define UINT16 unsigned INT16
-#define UINT32 unsigned INT32
+#define UINT16 unsigned INT16
+#define UINT32 unsigned INT32
#endif
/* assume IEEE; tweak if necessary (patches are welcome) */
-#define FLOAT16 UINT16
-#define FLOAT32 float
-#define FLOAT64 double
+#define FLOAT16 UINT16
+#define FLOAT32 float
+#define FLOAT64 double
#ifdef _MSC_VER
typedef signed __int64 int64_t;
diff --git a/src/libImaging/Imaging.h b/src/libImaging/Imaging.h
index 9032fcf07..47f577139 100644
--- a/src/libImaging/Imaging.h
+++ b/src/libImaging/Imaging.h
@@ -229,7 +229,7 @@ extern void ImagingSectionLeave(ImagingSectionCookie* cookie);
/* Exceptions */
/* ---------- */
-extern void* ImagingError_IOError(void);
+extern void* ImagingError_OSError(void);
extern void* ImagingError_MemoryError(void);
extern void* ImagingError_ModeError(void); /* maps to ValueError by default */
extern void* ImagingError_Mismatch(void); /* maps to ValueError by default */
diff --git a/src/libImaging/Jpeg.h b/src/libImaging/Jpeg.h
index 7ff658c32..df6d8a903 100644
--- a/src/libImaging/Jpeg.h
+++ b/src/libImaging/Jpeg.h
@@ -14,13 +14,13 @@
typedef struct {
- struct jpeg_error_mgr pub; /* "public" fields */
- jmp_buf setjmp_buffer; /* for return to caller */
+ struct jpeg_error_mgr pub; /* "public" fields */
+ jmp_buf setjmp_buffer; /* for return to caller */
} JPEGERROR;
/* -------------------------------------------------------------------- */
-/* Decoder */
+/* Decoder */
typedef struct {
struct jpeg_source_mgr pub;
@@ -56,7 +56,7 @@ typedef struct {
/* -------------------------------------------------------------------- */
-/* Encoder */
+/* Encoder */
typedef struct {
struct jpeg_destination_mgr pub;
diff --git a/src/libImaging/Jpeg2K.h b/src/libImaging/Jpeg2K.h
index 7bb14eb2c..7645b9326 100644
--- a/src/libImaging/Jpeg2K.h
+++ b/src/libImaging/Jpeg2K.h
@@ -14,7 +14,7 @@
#define BUFFER_SIZE OPJ_J2K_STREAM_CHUNK_SIZE
/* -------------------------------------------------------------------- */
-/* Decoder */
+/* Decoder */
/* -------------------------------------------------------------------- */
typedef struct {
@@ -44,7 +44,7 @@ typedef struct {
} JPEG2KDECODESTATE;
/* -------------------------------------------------------------------- */
-/* Encoder */
+/* Encoder */
/* -------------------------------------------------------------------- */
typedef struct {
diff --git a/src/libImaging/Jpeg2KDecode.c b/src/libImaging/Jpeg2KDecode.c
index d304511d1..d7a0a5b9f 100644
--- a/src/libImaging/Jpeg2KDecode.c
+++ b/src/libImaging/Jpeg2KDecode.c
@@ -84,10 +84,11 @@ struct j2k_decode_unpacker {
static inline
unsigned j2ku_shift(unsigned x, int n)
{
- if (n < 0)
+ if (n < 0) {
return x >> -n;
- else
+ } else {
return x << n;
+ }
}
static void
@@ -104,11 +105,13 @@ j2ku_gray_l(opj_image_t *in, const JPEG2KTILEINFO *tileinfo,
unsigned x, y;
- if (csiz == 3)
+ if (csiz == 3) {
csiz = 4;
+ }
- if (shift < 0)
+ if (shift < 0) {
offset += 1 << (-shift - 1);
+ }
/* csiz*h*w + offset = tileinfo.datasize */
switch (csiz) {
@@ -116,24 +119,27 @@ j2ku_gray_l(opj_image_t *in, const JPEG2KTILEINFO *tileinfo,
for (y = 0; y < h; ++y) {
const UINT8 *data = &tiledata[y * w];
UINT8 *row = (UINT8 *)im->image[y0 + y] + x0;
- for (x = 0; x < w; ++x)
+ for (x = 0; x < w; ++x) {
*row++ = j2ku_shift(offset + *data++, shift);
+ }
}
break;
case 2:
for (y = 0; y < h; ++y) {
const UINT16 *data = (const UINT16 *)&tiledata[2 * y * w];
UINT8 *row = (UINT8 *)im->image[y0 + y] + x0;
- for (x = 0; x < w; ++x)
+ for (x = 0; x < w; ++x) {
*row++ = j2ku_shift(offset + *data++, shift);
+ }
}
break;
case 4:
for (y = 0; y < h; ++y) {
const UINT32 *data = (const UINT32 *)&tiledata[4 * y * w];
UINT8 *row = (UINT8 *)im->image[y0 + y] + x0;
- for (x = 0; x < w; ++x)
+ for (x = 0; x < w; ++x) {
*row++ = j2ku_shift(offset + *data++, shift);
+ }
}
break;
}
@@ -154,35 +160,40 @@ j2ku_gray_i(opj_image_t *in, const JPEG2KTILEINFO *tileinfo,
unsigned x, y;
- if (csiz == 3)
+ if (csiz == 3) {
csiz = 4;
+ }
- if (shift < 0)
+ if (shift < 0) {
offset += 1 << (-shift - 1);
+ }
switch (csiz) {
case 1:
for (y = 0; y < h; ++y) {
const UINT8 *data = &tiledata[y * w];
UINT16 *row = (UINT16 *)im->image[y0 + y] + x0;
- for (x = 0; x < w; ++x)
+ for (x = 0; x < w; ++x) {
*row++ = j2ku_shift(offset + *data++, shift);
+ }
}
break;
case 2:
for (y = 0; y < h; ++y) {
const UINT16 *data = (const UINT16 *)&tiledata[2 * y * w];
UINT16 *row = (UINT16 *)im->image[y0 + y] + x0;
- for (x = 0; x < w; ++x)
+ for (x = 0; x < w; ++x) {
*row++ = j2ku_shift(offset + *data++, shift);
+ }
}
break;
case 4:
for (y = 0; y < h; ++y) {
const UINT32 *data = (const UINT32 *)&tiledata[4 * y * w];
UINT16 *row = (UINT16 *)im->image[y0 + y] + x0;
- for (x = 0; x < w; ++x)
+ for (x = 0; x < w; ++x) {
*row++ = j2ku_shift(offset + *data++, shift);
+ }
}
break;
}
@@ -203,11 +214,13 @@ j2ku_gray_rgb(opj_image_t *in, const JPEG2KTILEINFO *tileinfo,
unsigned x, y;
- if (shift < 0)
+ if (shift < 0) {
offset += 1 << (-shift - 1);
+ }
- if (csiz == 3)
+ if (csiz == 3) {
csiz = 4;
+ }
switch (csiz) {
case 1:
@@ -267,15 +280,19 @@ j2ku_graya_la(opj_image_t *in, const JPEG2KTILEINFO *tileinfo,
unsigned x, y;
- if (csiz == 3)
+ if (csiz == 3) {
csiz = 4;
- if (acsiz == 3)
+ }
+ if (acsiz == 3) {
acsiz = 4;
+ }
- if (shift < 0)
+ if (shift < 0) {
offset += 1 << (-shift - 1);
- if (ashift < 0)
+ }
+ if (ashift < 0) {
aoffset += 1 << (-ashift - 1);
+ }
atiledata = tiledata + csiz * w * h;
@@ -325,11 +342,13 @@ j2ku_srgb_rgb(opj_image_t *in, const JPEG2KTILEINFO *tileinfo,
offsets[n] = in->comps[n].sgnd ? 1 << (in->comps[n].prec - 1) : 0;
csiz[n] = (in->comps[n].prec + 7) >> 3;
- if (csiz[n] == 3)
+ if (csiz[n] == 3) {
csiz[n] = 4;
+ }
- if (shifts[n] < 0)
+ if (shifts[n] < 0) {
offsets[n] += 1 << (-shifts[n] - 1);
+ }
cptr += csiz[n] * w * h;
}
@@ -337,8 +356,9 @@ j2ku_srgb_rgb(opj_image_t *in, const JPEG2KTILEINFO *tileinfo,
for (y = 0; y < h; ++y) {
const UINT8 *data[3];
UINT8 *row = (UINT8 *)im->image[y0 + y] + x0 * 4;
- for (n = 0; n < 3; ++n)
+ for (n = 0; n < 3; ++n) {
data[n] = &cdata[n][csiz[n] * y * w];
+ }
for (x = 0; x < w; ++x) {
for (n = 0; n < 3; ++n) {
@@ -377,11 +397,13 @@ j2ku_sycc_rgb(opj_image_t *in, const JPEG2KTILEINFO *tileinfo,
offsets[n] = in->comps[n].sgnd ? 1 << (in->comps[n].prec - 1) : 0;
csiz[n] = (in->comps[n].prec + 7) >> 3;
- if (csiz[n] == 3)
+ if (csiz[n] == 3) {
csiz[n] = 4;
+ }
- if (shifts[n] < 0)
+ if (shifts[n] < 0) {
offsets[n] += 1 << (-shifts[n] - 1);
+ }
cptr += csiz[n] * w * h;
}
@@ -390,8 +412,9 @@ j2ku_sycc_rgb(opj_image_t *in, const JPEG2KTILEINFO *tileinfo,
const UINT8 *data[3];
UINT8 *row = (UINT8 *)im->image[y0 + y] + x0 * 4;
UINT8 *row_start = row;
- for (n = 0; n < 3; ++n)
+ for (n = 0; n < 3; ++n) {
data[n] = &cdata[n][csiz[n] * y * w];
+ }
for (x = 0; x < w; ++x) {
for (n = 0; n < 3; ++n) {
@@ -432,11 +455,13 @@ j2ku_srgba_rgba(opj_image_t *in, const JPEG2KTILEINFO *tileinfo,
offsets[n] = in->comps[n].sgnd ? 1 << (in->comps[n].prec - 1) : 0;
csiz[n] = (in->comps[n].prec + 7) >> 3;
- if (csiz[n] == 3)
+ if (csiz[n] == 3) {
csiz[n] = 4;
+ }
- if (shifts[n] < 0)
+ if (shifts[n] < 0) {
offsets[n] += 1 << (-shifts[n] - 1);
+ }
cptr += csiz[n] * w * h;
}
@@ -444,8 +469,9 @@ j2ku_srgba_rgba(opj_image_t *in, const JPEG2KTILEINFO *tileinfo,
for (y = 0; y < h; ++y) {
const UINT8 *data[4];
UINT8 *row = (UINT8 *)im->image[y0 + y] + x0 * 4;
- for (n = 0; n < 4; ++n)
+ for (n = 0; n < 4; ++n) {
data[n] = &cdata[n][csiz[n] * y * w];
+ }
for (x = 0; x < w; ++x) {
for (n = 0; n < 4; ++n) {
@@ -483,11 +509,13 @@ j2ku_sycca_rgba(opj_image_t *in, const JPEG2KTILEINFO *tileinfo,
offsets[n] = in->comps[n].sgnd ? 1 << (in->comps[n].prec - 1) : 0;
csiz[n] = (in->comps[n].prec + 7) >> 3;
- if (csiz[n] == 3)
+ if (csiz[n] == 3) {
csiz[n] = 4;
+ }
- if (shifts[n] < 0)
+ if (shifts[n] < 0) {
offsets[n] += 1 << (-shifts[n] - 1);
+ }
cptr += csiz[n] * w * h;
}
@@ -496,8 +524,9 @@ j2ku_sycca_rgba(opj_image_t *in, const JPEG2KTILEINFO *tileinfo,
const UINT8 *data[4];
UINT8 *row = (UINT8 *)im->image[y0 + y] + x0 * 4;
UINT8 *row_start = row;
- for (n = 0; n < 4; ++n)
+ for (n = 0; n < 4; ++n) {
data[n] = &cdata[n][csiz[n] * y * w];
+ }
for (x = 0; x < w; ++x) {
for (n = 0; n < 4; ++n) {
@@ -584,10 +613,11 @@ j2k_decode_entry(Imaging im, ImagingCodecState state)
possibly support is 4GB. We can't go larger than this, because
OpenJPEG truncates this value for the final box in the file, and
the box lengths in OpenJPEG are currently 32 bit. */
- if (context->length < 0)
+ if (context->length < 0) {
opj_stream_set_user_data_length(stream, 0xffffffff);
- else
+ } else {
opj_stream_set_user_data_length(stream, context->length);
+ }
#endif
/* Setup decompression context */
@@ -696,8 +726,9 @@ j2k_decode_entry(Imaging im, ImagingCodecState state)
goto quick_exit;
}
- if (!should_continue)
+ if (!should_continue) {
break;
+ }
/* Adjust the tile co-ordinates based on the reduction (OpenJPEG
doesn't do this for us) */
@@ -784,12 +815,15 @@ j2k_decode_entry(Imaging im, ImagingCodecState state)
}
quick_exit:
- if (codec)
+ if (codec) {
opj_destroy_codec(codec);
- if (image)
+ }
+ if (image) {
opj_image_destroy(image);
- if (stream)
+ }
+ if (stream) {
opj_stream_destroy(stream);
+ }
return -1;
}
@@ -804,8 +838,9 @@ ImagingJpeg2KDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t
return -1;
}
- if (state->state == J2K_STATE_DONE || state->state == J2K_STATE_FAILED)
+ if (state->state == J2K_STATE_DONE || state->state == J2K_STATE_FAILED) {
return -1;
+ }
if (state->state == J2K_STATE_START) {
state->state = J2K_STATE_DECODING;
diff --git a/src/libImaging/Jpeg2KEncode.c b/src/libImaging/Jpeg2KEncode.c
index aef1a4b94..49ef5e254 100644
--- a/src/libImaging/Jpeg2KEncode.c
+++ b/src/libImaging/Jpeg2KEncode.c
@@ -106,8 +106,9 @@ j2k_pack_l(Imaging im, UINT8 *buf,
unsigned x,y;
for (y = 0; y < h; ++y) {
UINT8 *data = (UINT8 *)(im->image[y + y0] + x0);
- for (x = 0; x < w; ++x)
+ for (x = 0; x < w; ++x) {
*ptr++ = *data++;
+ }
}
}
@@ -240,8 +241,9 @@ j2k_set_cinema_params(Imaging im, int components, opj_cparameters_t *params)
} else {
rate = ((float)(components * im->xsize * im->ysize * 8)
/ (params->tcp_rates[n] * 8));
- if (rate > CINEMA_24_CS_LENGTH)
+ if (rate > CINEMA_24_CS_LENGTH) {
params->tcp_rates[n] = max_rate;
+ }
}
}
@@ -257,8 +259,9 @@ j2k_set_cinema_params(Imaging im, int components, opj_cparameters_t *params)
} else {
rate = ((float)(components * im->xsize * im->ysize * 8)
/ (params->tcp_rates[n] * 8));
- if (rate > CINEMA_48_CS_LENGTH)
+ if (rate > CINEMA_48_CS_LENGTH) {
params->tcp_rates[n] = max_rate;
+ }
}
}
@@ -397,8 +400,9 @@ j2k_encode_entry(Imaging im, ImagingCodecState state)
float *pq;
if (len) {
- if (len > sizeof(params.tcp_rates) / sizeof(params.tcp_rates[0]))
+ if (len > sizeof(params.tcp_rates) / sizeof(params.tcp_rates[0])) {
len = sizeof(params.tcp_rates)/sizeof(params.tcp_rates[0]);
+ }
params.tcp_numlayers = (int)len;
@@ -423,8 +427,9 @@ j2k_encode_entry(Imaging im, ImagingCodecState state)
params.cp_disto_alloc = 1;
}
- if (context->num_resolutions)
+ if (context->num_resolutions) {
params.numresolution = context->num_resolutions;
+ }
if (context->cblk_width >= 4 && context->cblk_width <= 1024
&& context->cblk_height >= 4 && context->cblk_height <= 1024
@@ -455,18 +460,21 @@ j2k_encode_entry(Imaging im, ImagingCodecState state)
case OPJ_CINEMA2K_24:
case OPJ_CINEMA2K_48:
params.cp_rsiz = OPJ_CINEMA2K;
- if (params.numresolution > 6)
+ if (params.numresolution > 6) {
params.numresolution = 6;
+ }
break;
case OPJ_CINEMA4K_24:
params.cp_rsiz = OPJ_CINEMA4K;
- if (params.numresolution > 7)
+ if (params.numresolution > 7) {
params.numresolution = 7;
+ }
break;
}
- if (context->cinema_mode != OPJ_OFF)
+ if (context->cinema_mode != OPJ_OFF) {
j2k_set_cinema_params(im, components, ¶ms);
+ }
/* Set up the reference grid in the image */
image->x0 = params.image_offset_x0;
@@ -526,10 +534,12 @@ j2k_encode_entry(Imaging im, ImagingCodecState state)
unsigned ty1 = ty0 + tile_height;
unsigned pixy, pixh;
- if (ty0 < params.image_offset_y0)
+ if (ty0 < params.image_offset_y0) {
ty0 = params.image_offset_y0;
- if (ty1 > ysiz)
+ }
+ if (ty1 > ysiz) {
ty1 = ysiz;
+ }
pixy = ty0 - params.image_offset_y0;
pixh = ty1 - ty0;
@@ -540,10 +550,12 @@ j2k_encode_entry(Imaging im, ImagingCodecState state)
unsigned pixx, pixw;
unsigned data_size;
- if (tx0 < params.image_offset_x0)
+ if (tx0 < params.image_offset_x0) {
tx0 = params.image_offset_x0;
- if (tx1 > xsiz)
+ }
+ if (tx1 > xsiz) {
tx1 = xsiz;
+ }
pixx = tx0 - params.image_offset_x0;
pixw = tx1 - tx0;
@@ -572,12 +584,15 @@ j2k_encode_entry(Imaging im, ImagingCodecState state)
ret = -1;
quick_exit:
- if (codec)
+ if (codec) {
opj_destroy_codec(codec);
- if (image)
+ }
+ if (image) {
opj_image_destroy(image);
- if (stream)
+ }
+ if (stream) {
opj_stream_destroy(stream);
+ }
return ret;
}
@@ -585,8 +600,9 @@ j2k_encode_entry(Imaging im, ImagingCodecState state)
int
ImagingJpeg2KEncode(Imaging im, ImagingCodecState state, UINT8 *buf, int bytes)
{
- if (state->state == J2K_STATE_FAILED)
+ if (state->state == J2K_STATE_FAILED) {
return -1;
+ }
if (state->state == J2K_STATE_START) {
@@ -611,8 +627,9 @@ ImagingJpeg2KEncodeCleanup(ImagingCodecState state) {
context->quality_layers = NULL;
}
- if (context->error_msg)
+ if (context->error_msg) {
free ((void *)context->error_msg);
+ }
context->error_msg = NULL;
diff --git a/src/libImaging/JpegDecode.c b/src/libImaging/JpegDecode.c
index 39d96de53..fb6112044 100644
--- a/src/libImaging/JpegDecode.c
+++ b/src/libImaging/JpegDecode.c
@@ -176,8 +176,9 @@ ImagingJpegDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t by
if (context->source.skip > 0) {
skip_input_data(&context->cinfo, context->source.skip);
- if (context->source.skip > 0)
+ if (context->source.skip > 0) {
return context->source.pub.next_input_byte - buf;
+ }
}
switch (state->state) {
@@ -193,43 +194,46 @@ ImagingJpegDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t by
} while (ok == JPEG_HEADER_TABLES_ONLY);
- if (ok == JPEG_SUSPENDED)
+ if (ok == JPEG_SUSPENDED) {
break;
+ }
/* Decoder settings */
/* jpegmode indicates whats in the file; if not set, we'll
trust the decoder */
- if (strcmp(context->jpegmode, "L") == 0)
+ if (strcmp(context->jpegmode, "L") == 0) {
context->cinfo.jpeg_color_space = JCS_GRAYSCALE;
- else if (strcmp(context->jpegmode, "RGB") == 0)
+ } else if (strcmp(context->jpegmode, "RGB") == 0) {
context->cinfo.jpeg_color_space = JCS_RGB;
- else if (strcmp(context->jpegmode, "CMYK") == 0)
+ } else if (strcmp(context->jpegmode, "CMYK") == 0) {
context->cinfo.jpeg_color_space = JCS_CMYK;
- else if (strcmp(context->jpegmode, "YCbCr") == 0)
+ } else if (strcmp(context->jpegmode, "YCbCr") == 0) {
context->cinfo.jpeg_color_space = JCS_YCbCr;
- else if (strcmp(context->jpegmode, "YCbCrK") == 0) {
+ } else if (strcmp(context->jpegmode, "YCbCrK") == 0) {
context->cinfo.jpeg_color_space = JCS_YCCK;
}
/* rawmode indicates what we want from the decoder. if not
set, conversions are disabled */
- if (strcmp(context->rawmode, "L") == 0)
+ if (strcmp(context->rawmode, "L") == 0) {
context->cinfo.out_color_space = JCS_GRAYSCALE;
- else if (strcmp(context->rawmode, "RGB") == 0)
+ } else if (strcmp(context->rawmode, "RGB") == 0) {
context->cinfo.out_color_space = JCS_RGB;
+ }
#ifdef JCS_EXTENSIONS
- else if (strcmp(context->rawmode, "RGBX") == 0)
+ else if (strcmp(context->rawmode, "RGBX") == 0) {
context->cinfo.out_color_space = JCS_EXT_RGBX;
+ }
#endif
else if (strcmp(context->rawmode, "CMYK") == 0 ||
- strcmp(context->rawmode, "CMYK;I") == 0)
+ strcmp(context->rawmode, "CMYK;I") == 0) {
context->cinfo.out_color_space = JCS_CMYK;
- else if (strcmp(context->rawmode, "YCbCr") == 0)
+ } else if (strcmp(context->rawmode, "YCbCr") == 0) {
context->cinfo.out_color_space = JCS_YCbCr;
- else if (strcmp(context->rawmode, "YCbCrK") == 0)
+ } else if (strcmp(context->rawmode, "YCbCrK") == 0) {
context->cinfo.out_color_space = JCS_YCCK;
- else {
+ } else {
/* Disable decoder conversions */
context->cinfo.jpeg_color_space = JCS_UNKNOWN;
context->cinfo.out_color_space = JCS_UNKNOWN;
@@ -251,8 +255,9 @@ ImagingJpegDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t by
/* Set things up for decompression (this processes the entire
file if necessary to return data line by line) */
- if (!jpeg_start_decompress(&context->cinfo))
+ if (!jpeg_start_decompress(&context->cinfo)) {
break;
+ }
state->state++;
/* fall through */
@@ -263,15 +268,17 @@ ImagingJpegDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t by
ok = 1;
while (state->y < state->ysize) {
ok = jpeg_read_scanlines(&context->cinfo, &state->buffer, 1);
- if (ok != 1)
+ if (ok != 1) {
break;
+ }
state->shuffle((UINT8*) im->image[state->y + state->yoff] +
state->xoff * im->pixelsize, state->buffer,
state->xsize);
state->y++;
}
- if (ok != 1)
+ if (ok != 1) {
break;
+ }
state->state++;
/* fall through */
@@ -280,8 +287,9 @@ ImagingJpegDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t by
/* Finish decompression */
if (!jpeg_finish_decompress(&context->cinfo)) {
/* FIXME: add strictness mode test */
- if (state->y < state->ysize)
+ if (state->y < state->ysize) {
break;
+ }
}
/* Clean up */
@@ -301,14 +309,14 @@ ImagingJpegDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t by
/* -------------------------------------------------------------------- */
int ImagingJpegDecodeCleanup(ImagingCodecState state){
- /* called to free the decompression engine when the decode terminates
- due to a corrupt or truncated image
- */
+ /* called to free the decompression engine when the decode terminates
+ due to a corrupt or truncated image
+ */
JPEGSTATE* context = (JPEGSTATE*) state->context;
- /* Clean up */
- jpeg_destroy_decompress(&context->cinfo);
- return -1;
+ /* Clean up */
+ jpeg_destroy_decompress(&context->cinfo);
+ return -1;
}
#endif
diff --git a/src/libImaging/JpegEncode.c b/src/libImaging/JpegEncode.c
index 9d8382791..8882b61be 100644
--- a/src/libImaging/JpegEncode.c
+++ b/src/libImaging/JpegEncode.c
@@ -78,7 +78,7 @@ error(j_common_ptr cinfo)
/* -------------------------------------------------------------------- */
-/* Encoder */
+/* Encoder */
/* -------------------------------------------------------------------- */
int
@@ -88,24 +88,24 @@ ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
int ok;
if (setjmp(context->error.setjmp_buffer)) {
- /* JPEG error handler */
- jpeg_destroy_compress(&context->cinfo);
- state->errcode = IMAGING_CODEC_BROKEN;
- return -1;
+ /* JPEG error handler */
+ jpeg_destroy_compress(&context->cinfo);
+ state->errcode = IMAGING_CODEC_BROKEN;
+ return -1;
}
if (!state->state) {
- /* Setup compression context (very similar to the decoder) */
- context->cinfo.err = jpeg_std_error(&context->error.pub);
- context->error.pub.error_exit = error;
- jpeg_create_compress(&context->cinfo);
- jpeg_buffer_dest(&context->cinfo, &context->destination);
+ /* Setup compression context (very similar to the decoder) */
+ context->cinfo.err = jpeg_std_error(&context->error.pub);
+ context->error.pub.error_exit = error;
+ jpeg_create_compress(&context->cinfo);
+ jpeg_buffer_dest(&context->cinfo, &context->destination);
context->extra_offset = 0;
- /* Ready to encode */
- state->state = 1;
+ /* Ready to encode */
+ state->state = 1;
}
@@ -115,212 +115,221 @@ ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
switch (state->state) {
- case 1:
+ case 1:
- context->cinfo.image_width = state->xsize;
- context->cinfo.image_height = state->ysize;
+ context->cinfo.image_width = state->xsize;
+ context->cinfo.image_height = state->ysize;
- switch (state->bits) {
- case 8:
- context->cinfo.input_components = 1;
- context->cinfo.in_color_space = JCS_GRAYSCALE;
- break;
- case 24:
- context->cinfo.input_components = 3;
- if (strcmp(im->mode, "YCbCr") == 0)
- context->cinfo.in_color_space = JCS_YCbCr;
- else
- context->cinfo.in_color_space = JCS_RGB;
- break;
- case 32:
- context->cinfo.input_components = 4;
- context->cinfo.in_color_space = JCS_CMYK;
- #ifdef JCS_EXTENSIONS
- if (strcmp(context->rawmode, "RGBX") == 0)
- context->cinfo.in_color_space = JCS_EXT_RGBX;
- #endif
- break;
- default:
- state->errcode = IMAGING_CODEC_CONFIG;
- return -1;
- }
+ switch (state->bits) {
+ case 8:
+ context->cinfo.input_components = 1;
+ context->cinfo.in_color_space = JCS_GRAYSCALE;
+ break;
+ case 24:
+ context->cinfo.input_components = 3;
+ if (strcmp(im->mode, "YCbCr") == 0) {
+ context->cinfo.in_color_space = JCS_YCbCr;
+ } else {
+ context->cinfo.in_color_space = JCS_RGB;
+ }
+ break;
+ case 32:
+ context->cinfo.input_components = 4;
+ context->cinfo.in_color_space = JCS_CMYK;
+ #ifdef JCS_EXTENSIONS
+ if (strcmp(context->rawmode, "RGBX") == 0) {
+ context->cinfo.in_color_space = JCS_EXT_RGBX;
+ }
+ #endif
+ break;
+ default:
+ state->errcode = IMAGING_CODEC_CONFIG;
+ return -1;
+ }
- /* Compressor configuration */
- jpeg_set_defaults(&context->cinfo);
+ /* Compressor configuration */
+ jpeg_set_defaults(&context->cinfo);
- /* Use custom quantization tables */
- if (context->qtables) {
- int i;
- int quality = 100;
- int last_q = 0;
- if (context->quality != -1) {
- quality = context->quality;
- }
- for (i = 0; i < context->qtablesLen; i++) {
- // TODO: Should add support for none baseline
- jpeg_add_quant_table(&context->cinfo, i, &context->qtables[i * DCTSIZE2],
- quality, TRUE);
- context->cinfo.comp_info[i].quant_tbl_no = i;
- last_q = i;
- }
- if (context->qtablesLen == 1) {
- // jpeg_set_defaults created two qtables internally, but we only wanted one.
- jpeg_add_quant_table(&context->cinfo, 1, &context->qtables[0],
- quality, TRUE);
- }
- for (i = last_q; i < context->cinfo.num_components; i++) {
- context->cinfo.comp_info[i].quant_tbl_no = last_q;
- }
- } else if (context->quality != -1) {
- jpeg_set_quality(&context->cinfo, context->quality, 1);
- }
+ /* Use custom quantization tables */
+ if (context->qtables) {
+ int i;
+ int quality = 100;
+ int last_q = 0;
+ if (context->quality != -1) {
+ quality = context->quality;
+ }
+ for (i = 0; i < context->qtablesLen; i++) {
+ // TODO: Should add support for none baseline
+ jpeg_add_quant_table(&context->cinfo, i, &context->qtables[i * DCTSIZE2],
+ quality, TRUE);
+ context->cinfo.comp_info[i].quant_tbl_no = i;
+ last_q = i;
+ }
+ if (context->qtablesLen == 1) {
+ // jpeg_set_defaults created two qtables internally, but we only wanted one.
+ jpeg_add_quant_table(&context->cinfo, 1, &context->qtables[0],
+ quality, TRUE);
+ }
+ for (i = last_q; i < context->cinfo.num_components; i++) {
+ context->cinfo.comp_info[i].quant_tbl_no = last_q;
+ }
+ } else if (context->quality != -1) {
+ jpeg_set_quality(&context->cinfo, context->quality, 1);
+ }
- /* Set subsampling options */
- switch (context->subsampling)
- {
- case 0: /* 1x1 1x1 1x1 (4:4:4) : None */
- {
- context->cinfo.comp_info[0].h_samp_factor = 1;
- context->cinfo.comp_info[0].v_samp_factor = 1;
- context->cinfo.comp_info[1].h_samp_factor = 1;
- context->cinfo.comp_info[1].v_samp_factor = 1;
- context->cinfo.comp_info[2].h_samp_factor = 1;
- context->cinfo.comp_info[2].v_samp_factor = 1;
- break;
- }
- case 1: /* 2x1, 1x1, 1x1 (4:2:2) : Medium */
- {
- context->cinfo.comp_info[0].h_samp_factor = 2;
- context->cinfo.comp_info[0].v_samp_factor = 1;
- context->cinfo.comp_info[1].h_samp_factor = 1;
- context->cinfo.comp_info[1].v_samp_factor = 1;
- context->cinfo.comp_info[2].h_samp_factor = 1;
- context->cinfo.comp_info[2].v_samp_factor = 1;
- break;
- }
- case 2: /* 2x2, 1x1, 1x1 (4:2:0) : High */
- {
- context->cinfo.comp_info[0].h_samp_factor = 2;
- context->cinfo.comp_info[0].v_samp_factor = 2;
- context->cinfo.comp_info[1].h_samp_factor = 1;
- context->cinfo.comp_info[1].v_samp_factor = 1;
- context->cinfo.comp_info[2].h_samp_factor = 1;
- context->cinfo.comp_info[2].v_samp_factor = 1;
- break;
- }
- default:
- {
- /* Use the lib's default */
- break;
- }
- }
- if (context->progressive)
- jpeg_simple_progression(&context->cinfo);
- context->cinfo.smoothing_factor = context->smooth;
- context->cinfo.optimize_coding = (boolean) context->optimize;
- if (context->xdpi > 0 && context->ydpi > 0) {
- context->cinfo.density_unit = 1; /* dots per inch */
- context->cinfo.X_density = context->xdpi;
- context->cinfo.Y_density = context->ydpi;
- }
- switch (context->streamtype) {
- case 1:
- /* tables only -- not yet implemented */
- state->errcode = IMAGING_CODEC_CONFIG;
- return -1;
- case 2:
- /* image only */
- jpeg_suppress_tables(&context->cinfo, TRUE);
- jpeg_start_compress(&context->cinfo, FALSE);
- /* suppress extra section */
- context->extra_offset = context->extra_size;
- break;
- default:
- /* interchange stream */
- jpeg_start_compress(&context->cinfo, TRUE);
- break;
- }
- state->state++;
- /* fall through */
+ /* Set subsampling options */
+ switch (context->subsampling)
+ {
+ case 0: /* 1x1 1x1 1x1 (4:4:4) : None */
+ {
+ context->cinfo.comp_info[0].h_samp_factor = 1;
+ context->cinfo.comp_info[0].v_samp_factor = 1;
+ context->cinfo.comp_info[1].h_samp_factor = 1;
+ context->cinfo.comp_info[1].v_samp_factor = 1;
+ context->cinfo.comp_info[2].h_samp_factor = 1;
+ context->cinfo.comp_info[2].v_samp_factor = 1;
+ break;
+ }
+ case 1: /* 2x1, 1x1, 1x1 (4:2:2) : Medium */
+ {
+ context->cinfo.comp_info[0].h_samp_factor = 2;
+ context->cinfo.comp_info[0].v_samp_factor = 1;
+ context->cinfo.comp_info[1].h_samp_factor = 1;
+ context->cinfo.comp_info[1].v_samp_factor = 1;
+ context->cinfo.comp_info[2].h_samp_factor = 1;
+ context->cinfo.comp_info[2].v_samp_factor = 1;
+ break;
+ }
+ case 2: /* 2x2, 1x1, 1x1 (4:2:0) : High */
+ {
+ context->cinfo.comp_info[0].h_samp_factor = 2;
+ context->cinfo.comp_info[0].v_samp_factor = 2;
+ context->cinfo.comp_info[1].h_samp_factor = 1;
+ context->cinfo.comp_info[1].v_samp_factor = 1;
+ context->cinfo.comp_info[2].h_samp_factor = 1;
+ context->cinfo.comp_info[2].v_samp_factor = 1;
+ break;
+ }
+ default:
+ {
+ /* Use the lib's default */
+ break;
+ }
+ }
+ if (context->progressive) {
+ jpeg_simple_progression(&context->cinfo);
+ }
+ context->cinfo.smoothing_factor = context->smooth;
+ context->cinfo.optimize_coding = (boolean) context->optimize;
+ if (context->xdpi > 0 && context->ydpi > 0) {
+ context->cinfo.density_unit = 1; /* dots per inch */
+ context->cinfo.X_density = context->xdpi;
+ context->cinfo.Y_density = context->ydpi;
+ }
+ switch (context->streamtype) {
+ case 1:
+ /* tables only -- not yet implemented */
+ state->errcode = IMAGING_CODEC_CONFIG;
+ return -1;
+ case 2:
+ /* image only */
+ jpeg_suppress_tables(&context->cinfo, TRUE);
+ jpeg_start_compress(&context->cinfo, FALSE);
+ /* suppress extra section */
+ context->extra_offset = context->extra_size;
+ break;
+ default:
+ /* interchange stream */
+ jpeg_start_compress(&context->cinfo, TRUE);
+ break;
+ }
+ state->state++;
+ /* fall through */
- case 2:
- // check for exif len + 'APP1' header bytes
- if (context->rawExifLen + 5 > context->destination.pub.free_in_buffer){
- break;
- }
- //add exif header
- if (context->rawExifLen > 0){
- jpeg_write_marker(&context->cinfo, JPEG_APP0+1,
- (unsigned char*)context->rawExif, context->rawExifLen);
- }
-
- state->state++;
- /* fall through */
- case 3:
-
- if (context->extra) {
- /* copy extra buffer to output buffer */
- unsigned int n = context->extra_size - context->extra_offset;
- if (n > context->destination.pub.free_in_buffer)
- n = context->destination.pub.free_in_buffer;
- memcpy(context->destination.pub.next_output_byte,
- context->extra + context->extra_offset, n);
- context->destination.pub.next_output_byte += n;
- context->destination.pub.free_in_buffer -= n;
- context->extra_offset += n;
- if (context->extra_offset >= context->extra_size)
- state->state++;
- else
+ case 2:
+ // check for exif len + 'APP1' header bytes
+ if (context->rawExifLen + 5 > context->destination.pub.free_in_buffer){
break;
- } else
- state->state++;
+ }
+ //add exif header
+ if (context->rawExifLen > 0){
+ jpeg_write_marker(&context->cinfo, JPEG_APP0+1,
+ (unsigned char*)context->rawExif, context->rawExifLen);
+ }
- case 4:
- if (1024 > context->destination.pub.free_in_buffer){
+ state->state++;
+ /* fall through */
+ case 3:
+
+ if (context->extra) {
+ /* copy extra buffer to output buffer */
+ unsigned int n = context->extra_size - context->extra_offset;
+ if (n > context->destination.pub.free_in_buffer) {
+ n = context->destination.pub.free_in_buffer;
+ }
+ memcpy(context->destination.pub.next_output_byte,
+ context->extra + context->extra_offset, n);
+ context->destination.pub.next_output_byte += n;
+ context->destination.pub.free_in_buffer -= n;
+ context->extra_offset += n;
+ if (context->extra_offset >= context->extra_size) {
+ state->state++;
+ } else {
+ break;
+ }
+ } else {
+ state->state++;
+ }
+
+ case 4:
+ if (1024 > context->destination.pub.free_in_buffer){
+ break;
+ }
+
+ ok = 1;
+ while (state->y < state->ysize) {
+ state->shuffle(state->buffer,
+ (UINT8*) im->image[state->y + state->yoff] +
+ state->xoff * im->pixelsize, state->xsize);
+ ok = jpeg_write_scanlines(&context->cinfo, &state->buffer, 1);
+ if (ok != 1) {
+ break;
+ }
+ state->y++;
+ }
+
+ if (ok != 1) {
+ break;
+ }
+ state->state++;
+ /* fall through */
+
+ case 5:
+
+ /* Finish compression */
+ if (context->destination.pub.free_in_buffer < 100) {
+ break;
+ }
+ jpeg_finish_compress(&context->cinfo);
+
+ /* Clean up */
+ if (context->extra) {
+ free(context->extra);
+ context->extra = NULL;
+ }
+ if (context->rawExif) {
+ free(context->rawExif);
+ context->rawExif = NULL;
+ }
+ if (context->qtables) {
+ free(context->qtables);
+ context->qtables = NULL;
+ }
+
+ jpeg_destroy_compress(&context->cinfo);
+ /* if (jerr.pub.num_warnings) return BROKEN; */
+ state->errcode = IMAGING_CODEC_END;
break;
- }
-
- ok = 1;
- while (state->y < state->ysize) {
- state->shuffle(state->buffer,
- (UINT8*) im->image[state->y + state->yoff] +
- state->xoff * im->pixelsize, state->xsize);
- ok = jpeg_write_scanlines(&context->cinfo, &state->buffer, 1);
- if (ok != 1)
- break;
- state->y++;
- }
-
- if (ok != 1)
- break;
- state->state++;
- /* fall through */
-
- case 5:
-
- /* Finish compression */
- if (context->destination.pub.free_in_buffer < 100)
- break;
- jpeg_finish_compress(&context->cinfo);
-
- /* Clean up */
- if (context->extra) {
- free(context->extra);
- context->extra = NULL;
- }
- if (context->rawExif) {
- free(context->rawExif);
- context->rawExif = NULL;
- }
- if (context->qtables) {
- free(context->qtables);
- context->qtables = NULL;
- }
-
- jpeg_destroy_compress(&context->cinfo);
- /* if (jerr.pub.num_warnings) return BROKEN; */
- state->errcode = IMAGING_CODEC_END;
- break;
}
diff --git a/src/libImaging/Matrix.c b/src/libImaging/Matrix.c
index 5cc7795a4..e02b7b312 100644
--- a/src/libImaging/Matrix.c
+++ b/src/libImaging/Matrix.c
@@ -17,7 +17,7 @@
#include "Imaging.h"
-#define CLIPF(v) ((v <= 0.0) ? 0 : (v >= 255.0F) ? 255 : (UINT8) v)
+#define CLIPF(v) ((v <= 0.0) ? 0 : (v >= 255.0F) ? 255 : (UINT8) v)
Imaging
@@ -27,48 +27,52 @@ ImagingConvertMatrix(Imaging im, const char *mode, float m[])
int x, y;
/* Assume there's enough data in the buffer */
- if (!im)
- return (Imaging) ImagingError_ModeError();
+ if (!im) {
+ return (Imaging) ImagingError_ModeError();
+ }
if (strcmp(mode, "L") == 0 && im->bands == 3) {
- imOut = ImagingNewDirty("L", im->xsize, im->ysize);
- if (!imOut)
- return NULL;
+ imOut = ImagingNewDirty("L", im->xsize, im->ysize);
+ if (!imOut) {
+ return NULL;
+ }
- for (y = 0; y < im->ysize; y++) {
- UINT8* in = (UINT8*) im->image[y];
- UINT8* out = (UINT8*) imOut->image[y];
+ for (y = 0; y < im->ysize; y++) {
+ UINT8* in = (UINT8*) im->image[y];
+ UINT8* out = (UINT8*) imOut->image[y];
- for (x = 0; x < im->xsize; x++) {
- float v = m[0]*in[0] + m[1]*in[1] + m[2]*in[2] + m[3] + 0.5;
- out[x] = CLIPF(v);
- in += 4;
- }
- }
+ for (x = 0; x < im->xsize; x++) {
+ float v = m[0]*in[0] + m[1]*in[1] + m[2]*in[2] + m[3] + 0.5;
+ out[x] = CLIPF(v);
+ in += 4;
+ }
+ }
} else if (strlen(mode) == 3 && im->bands == 3) {
- imOut = ImagingNewDirty(mode, im->xsize, im->ysize);
- if (!imOut)
- return NULL;
+ imOut = ImagingNewDirty(mode, im->xsize, im->ysize);
+ if (!imOut) {
+ return NULL;
+ }
- for (y = 0; y < im->ysize; y++) {
- UINT8* in = (UINT8*) im->image[y];
- UINT8* out = (UINT8*) imOut->image[y];
+ for (y = 0; y < im->ysize; y++) {
+ UINT8* in = (UINT8*) im->image[y];
+ UINT8* out = (UINT8*) imOut->image[y];
- for (x = 0; x < im->xsize; x++) {
- float v0 = m[0]*in[0] + m[1]*in[1] + m[2]*in[2] + m[3] + 0.5;
- float v1 = m[4]*in[0] + m[5]*in[1] + m[6]*in[2] + m[7] + 0.5;
- float v2 = m[8]*in[0] + m[9]*in[1] + m[10]*in[2] + m[11] + 0.5;
- out[0] = CLIPF(v0);
- out[1] = CLIPF(v1);
- out[2] = CLIPF(v2);
- in += 4; out += 4;
- }
- }
- } else
- return (Imaging) ImagingError_ModeError();
+ for (x = 0; x < im->xsize; x++) {
+ float v0 = m[0]*in[0] + m[1]*in[1] + m[2]*in[2] + m[3] + 0.5;
+ float v1 = m[4]*in[0] + m[5]*in[1] + m[6]*in[2] + m[7] + 0.5;
+ float v2 = m[8]*in[0] + m[9]*in[1] + m[10]*in[2] + m[11] + 0.5;
+ out[0] = CLIPF(v0);
+ out[1] = CLIPF(v1);
+ out[2] = CLIPF(v2);
+ in += 4; out += 4;
+ }
+ }
+ } else {
+ return (Imaging) ImagingError_ModeError();
+ }
return imOut;
}
diff --git a/src/libImaging/ModeFilter.c b/src/libImaging/ModeFilter.c
index 5237d0732..b1cf7442c 100644
--- a/src/libImaging/ModeFilter.c
+++ b/src/libImaging/ModeFilter.c
@@ -25,12 +25,14 @@ ImagingModeFilter(Imaging im, int size)
UINT8 maxpixel;
int histogram[256];
- if (!im || im->bands != 1 || im->type != IMAGING_TYPE_UINT8)
+ if (!im || im->bands != 1 || im->type != IMAGING_TYPE_UINT8) {
return (Imaging) ImagingError_ModeError();
+ }
imOut = ImagingNewDirty(im->mode, im->xsize, im->ysize);
- if (!imOut)
+ if (!imOut) {
return NULL;
+ }
size = size / 2;
@@ -46,27 +48,32 @@ ImagingModeFilter(Imaging im, int size)
the added complexity... */
memset(histogram, 0, sizeof(histogram));
- for (yy = y - size; yy <= y + size; yy++)
+ for (yy = y - size; yy <= y + size; yy++) {
if (yy >= 0 && yy < imOut->ysize) {
UINT8* in = &IMAGING_PIXEL_L(im, 0, yy);
- for (xx = x - size; xx <= x + size; xx++)
- if (xx >= 0 && xx < imOut->xsize)
+ for (xx = x - size; xx <= x + size; xx++) {
+ if (xx >= 0 && xx < imOut->xsize) {
histogram[in[xx]]++;
+ }
+ }
}
+ }
/* find most frequent pixel value in this region */
maxpixel = 0;
maxcount = histogram[maxpixel];
- for (i = 1; i < 256; i++)
+ for (i = 1; i < 256; i++) {
if (histogram[i] > maxcount) {
maxcount = histogram[i];
maxpixel = (UINT8) i;
}
+ }
- if (maxcount > 2)
+ if (maxcount > 2) {
out[x] = maxpixel;
- else
+ } else {
out[x] = IMAGING_PIXEL_L(im, x, y);
+ }
}
diff --git a/src/libImaging/Negative.c b/src/libImaging/Negative.c
index 4dedcb245..09c946bbe 100644
--- a/src/libImaging/Negative.c
+++ b/src/libImaging/Negative.c
@@ -8,7 +8,7 @@
* FIXME: Maybe this should be implemented using ImagingPoint()
*
* history:
- * 95-11-27 fl: Created
+ * 95-11-27 fl: Created
*
* Copyright (c) Fredrik Lundh 1995.
* Copyright (c) Secret Labs AB 1997.
@@ -26,16 +26,20 @@ ImagingNegative(Imaging im)
Imaging imOut;
int x, y;
- if (!im)
- return (Imaging) ImagingError_ModeError();
+ if (!im) {
+ return (Imaging) ImagingError_ModeError();
+ }
imOut = ImagingNewDirty(im->mode, im->xsize, im->ysize);
- if (!imOut)
- return NULL;
+ if (!imOut) {
+ return NULL;
+ }
- for (y = 0; y < im->ysize; y++)
- for (x = 0; x < im->linesize; x++)
- imOut->image[y][x] = ~im->image[y][x];
+ for (y = 0; y < im->ysize; y++) {
+ for (x = 0; x < im->linesize; x++) {
+ imOut->image[y][x] = ~im->image[y][x];
+ }
+ }
return imOut;
}
diff --git a/src/libImaging/Offset.c b/src/libImaging/Offset.c
index b3d9425fb..29f038153 100644
--- a/src/libImaging/Offset.c
+++ b/src/libImaging/Offset.c
@@ -5,7 +5,7 @@
* offset an image in x and y directions
*
* history:
- * 96-07-22 fl: Created
+ * 96-07-22 fl: Created
* 98-11-01 cgw@pgt.com: Fixed negative-array index bug
*
* Copyright (c) Fredrik Lundh 1996.
@@ -24,38 +24,44 @@ ImagingOffset(Imaging im, int xoffset, int yoffset)
int x, y;
Imaging imOut;
- if (!im)
- return (Imaging) ImagingError_ModeError();
+ if (!im) {
+ return (Imaging) ImagingError_ModeError();
+ }
imOut = ImagingNewDirty(im->mode, im->xsize, im->ysize);
- if (!imOut)
- return NULL;
+ if (!imOut) {
+ return NULL;
+ }
ImagingCopyPalette(imOut, im);
/* make offsets positive to avoid negative coordinates */
xoffset %= im->xsize;
xoffset = im->xsize - xoffset;
- if (xoffset < 0)
- xoffset += im->xsize;
+ if (xoffset < 0) {
+ xoffset += im->xsize;
+ }
yoffset %= im->ysize;
yoffset = im->ysize - yoffset;
- if (yoffset < 0)
- yoffset += im->ysize;
+ if (yoffset < 0) {
+ yoffset += im->ysize;
+ }
-#define OFFSET(image)\
- for (y = 0; y < im->ysize; y++)\
- for (x = 0; x < im->xsize; x++) {\
- int yi = (y + yoffset) % im->ysize;\
- int xi = (x + xoffset) % im->xsize;\
- imOut->image[y][x] = im->image[yi][xi];\
- }
+#define OFFSET(image)\
+ for (y = 0; y < im->ysize; y++) {\
+ for (x = 0; x < im->xsize; x++) {\
+ int yi = (y + yoffset) % im->ysize;\
+ int xi = (x + xoffset) % im->xsize;\
+ imOut->image[y][x] = im->image[yi][xi];\
+ }\
+ }
- if (im->image8)
- OFFSET(image8)
- else
- OFFSET(image32)
+ if (im->image8) {
+ OFFSET(image8)
+ } else {
+ OFFSET(image32)
+ }
return imOut;
}
diff --git a/src/libImaging/Pack.c b/src/libImaging/Pack.c
index a239464d4..0be7ad8c9 100644
--- a/src/libImaging/Pack.c
+++ b/src/libImaging/Pack.c
@@ -80,16 +80,18 @@ pack1(UINT8* out, const UINT8* in, int pixels)
/* bilevel (black is 0) */
b = 0; m = 128;
for (i = 0; i < pixels; i++) {
- if (in[i] != 0)
+ if (in[i] != 0) {
b |= m;
+ }
m >>= 1;
if (m == 0) {
*out++ = b;
b = 0; m = 128;
}
}
- if (m != 128)
+ if (m != 128) {
*out++ = b;
+ }
}
static void
@@ -99,16 +101,18 @@ pack1I(UINT8* out, const UINT8* in, int pixels)
/* bilevel (black is 1) */
b = 0; m = 128;
for (i = 0; i < pixels; i++) {
- if (in[i] == 0)
+ if (in[i] == 0) {
b |= m;
+ }
m >>= 1;
if (m == 0) {
*out++ = b;
b = 0; m = 128;
}
}
- if (m != 128)
+ if (m != 128) {
*out++ = b;
+ }
}
static void
@@ -118,16 +122,18 @@ pack1R(UINT8* out, const UINT8* in, int pixels)
/* bilevel, lsb first (black is 0) */
b = 0; m = 1;
for (i = 0; i < pixels; i++) {
- if (in[i] != 0)
+ if (in[i] != 0) {
b |= m;
+ }
m <<= 1;
if (m == 256){
*out++ = b;
b = 0; m = 1;
}
}
- if (m != 1)
+ if (m != 1) {
*out++ = b;
+ }
}
static void
@@ -137,16 +143,18 @@ pack1IR(UINT8* out, const UINT8* in, int pixels)
/* bilevel, lsb first (black is 1) */
b = 0; m = 1;
for (i = 0; i < pixels; i++) {
- if (in[i] == 0)
+ if (in[i] == 0) {
b |= m;
+ }
m <<= 1;
if (m == 256){
*out++ = b;
b = 0; m = 1;
}
}
- if (m != 1)
+ if (m != 1) {
*out++ = b;
+ }
}
static void
@@ -154,8 +162,9 @@ pack1L(UINT8* out, const UINT8* in, int pixels)
{
int i;
/* bilevel, stored as bytes */
- for (i = 0; i < pixels; i++)
+ for (i = 0; i < pixels; i++) {
out[i] = (in[i] != 0) ? 255 : 0;
+ }
}
static void
@@ -167,8 +176,9 @@ packP4(UINT8* out, const UINT8* in, int pixels)
in += 2; pixels -= 2;
}
- if (pixels)
+ if (pixels) {
out[0] = (in[0] << 4);
+ }
}
static void
@@ -407,12 +417,13 @@ packI16B(UINT8* out, const UINT8* in_, int pixels)
for (i = 0; i < pixels; i++) {
INT32 in;
memcpy(&in, in_, sizeof(in));
- if (in <= 0)
+ if (in <= 0) {
tmp_ = 0;
- else if (in > 65535)
+ } else if (in > 65535) {
tmp_ = 65535;
- else
+ } else {
tmp_ = in;
+ }
C16B;
out += 2; in_ += sizeof(in);
}
@@ -496,40 +507,45 @@ copy4I(UINT8* out, const UINT8* in, int pixels)
{
/* RGBA, CMYK quadruples, inverted */
int i;
- for (i = 0; i < pixels*4; i++)
+ for (i = 0; i < pixels*4; i++) {
out[i] = ~in[i];
+ }
}
static void
band0(UINT8* out, const UINT8* in, int pixels)
{
int i;
- for (i = 0; i < pixels; i++, in += 4)
+ for (i = 0; i < pixels; i++, in += 4) {
out[i] = in[0];
+ }
}
static void
band1(UINT8* out, const UINT8* in, int pixels)
{
int i;
- for (i = 0; i < pixels; i++, in += 4)
+ for (i = 0; i < pixels; i++, in += 4) {
out[i] = in[1];
+ }
}
static void
band2(UINT8* out, const UINT8* in, int pixels)
{
int i;
- for (i = 0; i < pixels; i++, in += 4)
+ for (i = 0; i < pixels; i++, in += 4) {
out[i] = in[2];
+ }
}
static void
band3(UINT8* out, const UINT8* in, int pixels)
{
int i;
- for (i = 0; i < pixels; i++, in += 4)
+ for (i = 0; i < pixels; i++, in += 4) {
out[i] = in[3];
+ }
}
static struct {
@@ -673,12 +689,14 @@ ImagingFindPacker(const char* mode, const char* rawmode, int* bits_out)
int i;
/* find a suitable pixel packer */
- for (i = 0; packers[i].rawmode; i++)
+ for (i = 0; packers[i].rawmode; i++) {
if (strcmp(packers[i].mode, mode) == 0 &&
strcmp(packers[i].rawmode, rawmode) == 0) {
- if (bits_out)
+ if (bits_out) {
*bits_out = packers[i].bits;
+ }
return packers[i].pack;
}
+ }
return NULL;
}
diff --git a/src/libImaging/PackDecode.c b/src/libImaging/PackDecode.c
index ef54f3c9a..34671828a 100644
--- a/src/libImaging/PackDecode.c
+++ b/src/libImaging/PackDecode.c
@@ -5,7 +5,7 @@
* decoder for PackBits image data.
*
* history:
- * 96-04-19 fl Created
+ * 96-04-19 fl Created
*
* Copyright (c) Fredrik Lundh 1996.
* Copyright (c) Secret Labs AB 1997.
@@ -18,7 +18,7 @@
int
ImagingPackbitsDecode(Imaging im, ImagingCodecState state,
- UINT8* buf, Py_ssize_t bytes)
+ UINT8* buf, Py_ssize_t bytes)
{
UINT8 n;
UINT8* ptr;
@@ -28,65 +28,68 @@ ImagingPackbitsDecode(Imaging im, ImagingCodecState state,
for (;;) {
- if (bytes < 1)
- return ptr - buf;
+ if (bytes < 1) {
+ return ptr - buf;
+ }
- if (ptr[0] & 0x80) {
+ if (ptr[0] & 0x80) {
- if (ptr[0] == 0x80) {
- /* Nop */
- ptr++; bytes--;
- continue;
- }
+ if (ptr[0] == 0x80) {
+ /* Nop */
+ ptr++; bytes--;
+ continue;
+ }
- /* Run */
- if (bytes < 2)
- return ptr - buf;
+ /* Run */
+ if (bytes < 2) {
+ return ptr - buf;
+ }
- for (n = 257 - ptr[0]; n > 0; n--) {
- if (state->x >= state->bytes) {
- /* state->errcode = IMAGING_CODEC_OVERRUN; */
- break;
- }
- state->buffer[state->x++] = ptr[1];
- }
+ for (n = 257 - ptr[0]; n > 0; n--) {
+ if (state->x >= state->bytes) {
+ /* state->errcode = IMAGING_CODEC_OVERRUN; */
+ break;
+ }
+ state->buffer[state->x++] = ptr[1];
+ }
- ptr += 2; bytes -= 2;
+ ptr += 2; bytes -= 2;
- } else {
+ } else {
- /* Literal */
- n = ptr[0]+2;
+ /* Literal */
+ n = ptr[0]+2;
- if (bytes < n)
- return ptr - buf;
+ if (bytes < n) {
+ return ptr - buf;
+ }
- for (i = 1; i < n; i++) {
- if (state->x >= state->bytes) {
- /* state->errcode = IMAGING_CODEC_OVERRUN; */
- break;
- }
- state->buffer[state->x++] = ptr[i];
- }
+ for (i = 1; i < n; i++) {
+ if (state->x >= state->bytes) {
+ /* state->errcode = IMAGING_CODEC_OVERRUN; */
+ break;
+ }
+ state->buffer[state->x++] = ptr[i];
+ }
- ptr += n; bytes -= n;
+ ptr += n; bytes -= n;
- }
+ }
- if (state->x >= state->bytes) {
+ if (state->x >= state->bytes) {
- /* Got a full line, unpack it */
- state->shuffle((UINT8*) im->image[state->y + state->yoff] +
- state->xoff * im->pixelsize, state->buffer,
- state->xsize);
+ /* Got a full line, unpack it */
+ state->shuffle((UINT8*) im->image[state->y + state->yoff] +
+ state->xoff * im->pixelsize, state->buffer,
+ state->xsize);
- state->x = 0;
+ state->x = 0;
- if (++state->y >= state->ysize) {
- /* End of file (errcode = 0) */
- return -1;
- }
- }
+ if (++state->y >= state->ysize) {
+ /* End of file (errcode = 0) */
+ return -1;
+ }
+ }
}
}
diff --git a/src/libImaging/Palette.c b/src/libImaging/Palette.c
index 7aee6e8ee..ac548f50c 100644
--- a/src/libImaging/Palette.c
+++ b/src/libImaging/Palette.c
@@ -30,12 +30,14 @@ ImagingPaletteNew(const char* mode)
int i;
ImagingPalette palette;
- if (strcmp(mode, "RGB") && strcmp(mode, "RGBA"))
+ if (strcmp(mode, "RGB") && strcmp(mode, "RGBA")) {
return (ImagingPalette) ImagingError_ModeError();
+ }
palette = calloc(1, sizeof(struct ImagingPaletteInstance));
- if (!palette)
+ if (!palette) {
return (ImagingPalette) ImagingError_MemoryError();
+ }
strncpy(palette->mode, mode, IMAGING_MODE_LENGTH-1);
palette->mode[IMAGING_MODE_LENGTH-1] = 0;
@@ -60,8 +62,9 @@ ImagingPaletteNewBrowser(void)
ImagingPalette palette;
palette = ImagingPaletteNew("RGB");
- if (!palette)
+ if (!palette) {
return NULL;
+ }
/* Blank out unused entries */
/* FIXME: Add 10-level windows palette here? */
@@ -74,14 +77,16 @@ ImagingPaletteNewBrowser(void)
/* Simple 6x6x6 colour cube */
- for (b = 0; b < 256; b += 51)
- for (g = 0; g < 256; g += 51)
+ for (b = 0; b < 256; b += 51) {
+ for (g = 0; g < 256; g += 51) {
for (r = 0; r < 256; r += 51) {
palette->palette[i*4+0] = r;
palette->palette[i*4+1] = g;
palette->palette[i*4+2] = b;
i++;
}
+ }
+ }
/* Blank out unused entries */
/* FIXME: add 30-level greyscale wedge here? */
@@ -102,12 +107,14 @@ ImagingPaletteDuplicate(ImagingPalette palette)
ImagingPalette new_palette;
- if (!palette)
+ if (!palette) {
return NULL;
+ }
/* malloc check ok, small constant allocation */
new_palette = malloc(sizeof(struct ImagingPaletteInstance));
- if (!new_palette)
+ if (!new_palette) {
return (ImagingPalette) ImagingError_MemoryError();
+ }
memcpy(new_palette, palette, sizeof(struct ImagingPaletteInstance));
@@ -123,8 +130,9 @@ ImagingPaletteDelete(ImagingPalette palette)
/* Destroy palette object */
if (palette) {
- if (palette->cache)
+ if (palette->cache) {
free(palette->cache);
+ }
free(palette);
}
}
@@ -209,8 +217,9 @@ ImagingPaletteCacheUpdate(ImagingPalette palette, int r, int g, int b)
tmax += (b <= bc) ? BDIST(b, b1) : BDIST(b, b0);
dmin[i] = tmin;
- if (tmax < dmax)
+ if (tmax < dmax) {
dmax = tmax; /* keep the smallest max distance only */
+ }
}
@@ -220,10 +229,11 @@ ImagingPaletteCacheUpdate(ImagingPalette palette, int r, int g, int b)
* all slots in that box. We only check boxes for which the min
* distance is less than or equal the smallest max distance */
- for (i = 0; i < BOXVOLUME; i++)
+ for (i = 0; i < BOXVOLUME; i++) {
d[i] = (unsigned int) ~0;
+ }
- for (i = 0; i < 256; i++)
+ for (i = 0; i < 256; i++) {
if (dmin[i] <= dmax) {
@@ -262,6 +272,7 @@ ImagingPaletteCacheUpdate(ImagingPalette palette, int r, int g, int b)
rx += 2 * RSTEP * RSTEP;
}
}
+ }
/* Step 3 -- Update cache */
@@ -269,10 +280,13 @@ ImagingPaletteCacheUpdate(ImagingPalette palette, int r, int g, int b)
* cache slot in the box. Update the cache. */
j = 0;
- for (r = r0; r < r1; r+=4)
- for (g = g0; g < g1; g+=4)
- for (b = b0; b < b1; b+=4)
+ for (r = r0; r < r1; r+=4) {
+ for (g = g0; g < g1; g+=4) {
+ for (b = b0; b < b1; b+=4) {
ImagingPaletteCache(palette, r, g, b) = c[j++];
+ }
+ }
+ }
}
@@ -297,8 +311,9 @@ ImagingPaletteCachePrepare(ImagingPalette palette)
}
/* Mark all entries as empty */
- for (i = 0; i < entries; i++)
+ for (i = 0; i < entries; i++) {
palette->cache[i] = 0x100;
+ }
}
diff --git a/src/libImaging/Paste.c b/src/libImaging/Paste.c
index 0bda25739..6dfff4afb 100644
--- a/src/libImaging/Paste.c
+++ b/src/libImaging/Paste.c
@@ -37,8 +37,9 @@ paste(Imaging imOut, Imaging imIn, int dx, int dy, int sx, int sy,
xsize *= pixelsize;
- for (y = 0; y < ysize; y++)
+ for (y = 0; y < ysize; y++) {
memcpy(imOut->image[y+dy]+dx, imIn->image[y+sy]+sx, xsize);
+ }
}
static inline void
@@ -57,8 +58,9 @@ paste_mask_1(Imaging imOut, Imaging imIn, Imaging imMask,
UINT8* in = imIn->image8[y+sy]+sx;
UINT8* mask = imMask->image8[y+sy]+sx;
for (x = 0; x < xsize; x++) {
- if (*mask++)
+ if (*mask++) {
*out = *in;
+ }
out++, in++;
}
}
@@ -70,8 +72,9 @@ paste_mask_1(Imaging imOut, Imaging imIn, Imaging imMask,
INT32* in = imIn->image32[y+sy]+sx;
UINT8* mask = imMask->image8[y+sy]+sx;
for (x = 0; x < xsize; x++) {
- if (*mask++)
+ if (*mask++) {
*out = *in;
+ }
out++, in++;
}
}
@@ -231,17 +234,22 @@ ImagingPaste(Imaging imOut, Imaging imIn, Imaging imMask,
/* Determine which region to copy */
sx0 = sy0 = 0;
- if (dx0 < 0)
+ if (dx0 < 0) {
xsize += dx0, sx0 = -dx0, dx0 = 0;
- if (dx0 + xsize > imOut->xsize)
+ }
+ if (dx0 + xsize > imOut->xsize) {
xsize = imOut->xsize - dx0;
- if (dy0 < 0)
+ }
+ if (dy0 < 0) {
ysize += dy0, sy0 = -dy0, dy0 = 0;
- if (dy0 + ysize > imOut->ysize)
+ }
+ if (dy0 + ysize > imOut->ysize) {
ysize = imOut->ysize - dy0;
+ }
- if (xsize <= 0 || ysize <= 0)
+ if (xsize <= 0 || ysize <= 0) {
return 0;
+ }
if (!imMask) {
ImagingSectionEnter(&cookie);
@@ -297,15 +305,17 @@ fill(Imaging imOut, const void* ink_, int dx, int dy,
dx *= pixelsize;
xsize *= pixelsize;
- for (y = 0; y < ysize; y++)
+ for (y = 0; y < ysize; y++) {
memset(imOut->image[y+dy]+dx, ink8, xsize);
+ }
} else {
for (y = 0; y < ysize; y++) {
INT32* out = imOut->image32[y+dy]+dx;
- for (x = 0; x < xsize; x++)
+ for (x = 0; x < xsize; x++) {
out[x] = ink32;
+ }
}
}
@@ -331,8 +341,9 @@ fill_mask_1(Imaging imOut, const void* ink_, Imaging imMask,
UINT8* out = imOut->image8[y+dy]+dx;
UINT8* mask = imMask->image8[y+sy]+sx;
for (x = 0; x < xsize; x++) {
- if (*mask++)
+ if (*mask++) {
*out = ink8;
+ }
out++;
}
}
@@ -343,8 +354,9 @@ fill_mask_1(Imaging imOut, const void* ink_, Imaging imMask,
INT32* out = imOut->image32[y+dy]+dx;
UINT8* mask = imMask->image8[y+sy]+sx;
for (x = 0; x < xsize; x++) {
- if (*mask++)
+ if (*mask++) {
*out = ink32;
+ }
out++;
}
}
@@ -494,17 +506,22 @@ ImagingFill2(Imaging imOut, const void* ink, Imaging imMask,
/* Determine which region to fill */
sx0 = sy0 = 0;
- if (dx0 < 0)
+ if (dx0 < 0) {
xsize += dx0, sx0 = -dx0, dx0 = 0;
- if (dx0 + xsize > imOut->xsize)
+ }
+ if (dx0 + xsize > imOut->xsize) {
xsize = imOut->xsize - dx0;
- if (dy0 < 0)
+ }
+ if (dy0 < 0) {
ysize += dy0, sy0 = -dy0, dy0 = 0;
- if (dy0 + ysize > imOut->ysize)
+ }
+ if (dy0 + ysize > imOut->ysize) {
ysize = imOut->ysize - dy0;
+ }
- if (xsize <= 0 || ysize <= 0)
+ if (xsize <= 0 || ysize <= 0) {
return 0;
+ }
if (!imMask) {
ImagingSectionEnter(&cookie);
diff --git a/src/libImaging/PcdDecode.c b/src/libImaging/PcdDecode.c
index 8ff264edf..ff192a174 100644
--- a/src/libImaging/PcdDecode.c
+++ b/src/libImaging/PcdDecode.c
@@ -5,13 +5,13 @@
* decoder for uncompressed PCD image data.
*
* history:
- * 96-05-10 fl Created
- * 96-05-18 fl New tables
- * 97-01-25 fl Use PhotoYCC unpacker
+ * 96-05-10 fl Created
+ * 96-05-18 fl New tables
+ * 97-01-25 fl Use PhotoYCC unpacker
*
* notes:
- * This driver supports uncompressed PCD modes only
- * (resolutions up to 768x512).
+ * This driver supports uncompressed PCD modes only
+ * (resolutions up to 768x512).
*
* Copyright (c) Fredrik Lundh 1996-97.
* Copyright (c) Secret Labs AB 1997.
@@ -37,42 +37,45 @@ ImagingPcdDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt
for (;;) {
- /* We need data for two full lines before we can do anything */
- if (bytes < chunk)
- return ptr - buf;
+ /* We need data for two full lines before we can do anything */
+ if (bytes < chunk) {
+ return ptr - buf;
+ }
- /* Unpack first line */
- out = state->buffer;
- for (x = 0; x < state->xsize; x++) {
- out[0] = ptr[x];
- out[1] = ptr[(x+4*state->xsize)/2];
- out[2] = ptr[(x+5*state->xsize)/2];
- out += 3;
- }
+ /* Unpack first line */
+ out = state->buffer;
+ for (x = 0; x < state->xsize; x++) {
+ out[0] = ptr[x];
+ out[1] = ptr[(x+4*state->xsize)/2];
+ out[2] = ptr[(x+5*state->xsize)/2];
+ out += 3;
+ }
- state->shuffle((UINT8*) im->image[state->y],
- state->buffer, state->xsize);
+ state->shuffle((UINT8*) im->image[state->y],
+ state->buffer, state->xsize);
- if (++state->y >= state->ysize)
- return -1; /* This can hardly happen */
+ if (++state->y >= state->ysize) {
+ return -1; /* This can hardly happen */
+ }
- /* Unpack second line */
- out = state->buffer;
- for (x = 0; x < state->xsize; x++) {
- out[0] = ptr[x+state->xsize];
- out[1] = ptr[(x+4*state->xsize)/2];
- out[2] = ptr[(x+5*state->xsize)/2];
- out += 3;
- }
+ /* Unpack second line */
+ out = state->buffer;
+ for (x = 0; x < state->xsize; x++) {
+ out[0] = ptr[x+state->xsize];
+ out[1] = ptr[(x+4*state->xsize)/2];
+ out[2] = ptr[(x+5*state->xsize)/2];
+ out += 3;
+ }
- state->shuffle((UINT8*) im->image[state->y],
- state->buffer, state->xsize);
+ state->shuffle((UINT8*) im->image[state->y],
+ state->buffer, state->xsize);
- if (++state->y >= state->ysize)
- return -1;
+ if (++state->y >= state->ysize) {
+ return -1;
+ }
- ptr += chunk;
- bytes -= chunk;
+ ptr += chunk;
+ bytes -= chunk;
}
}
diff --git a/src/libImaging/PcxDecode.c b/src/libImaging/PcxDecode.c
index e5a38f4be..eb0fecc83 100644
--- a/src/libImaging/PcxDecode.c
+++ b/src/libImaging/PcxDecode.c
@@ -5,7 +5,7 @@
* decoder for PCX image data.
*
* history:
- * 95-09-14 fl Created
+ * 95-09-14 fl Created
*
* Copyright (c) Fredrik Lundh 1995.
* Copyright (c) Secret Labs AB 1997.
@@ -31,59 +31,61 @@ ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt
for (;;) {
- if (bytes < 1)
- return ptr - buf;
+ if (bytes < 1) {
+ return ptr - buf;
+ }
- if ((*ptr & 0xC0) == 0xC0) {
+ if ((*ptr & 0xC0) == 0xC0) {
- /* Run */
- if (bytes < 2)
- return ptr - buf;
+ /* Run */
+ if (bytes < 2) {
+ return ptr - buf;
+ }
- n = ptr[0] & 0x3F;
+ n = ptr[0] & 0x3F;
- while (n > 0) {
- if (state->x >= state->bytes) {
- state->errcode = IMAGING_CODEC_OVERRUN;
- break;
- }
- state->buffer[state->x++] = ptr[1];
- n--;
- }
+ while (n > 0) {
+ if (state->x >= state->bytes) {
+ state->errcode = IMAGING_CODEC_OVERRUN;
+ break;
+ }
+ state->buffer[state->x++] = ptr[1];
+ n--;
+ }
- ptr += 2; bytes -= 2;
+ ptr += 2; bytes -= 2;
- } else {
+ } else {
- /* Literal */
- state->buffer[state->x++] = ptr[0];
- ptr++; bytes--;
+ /* Literal */
+ state->buffer[state->x++] = ptr[0];
+ ptr++; bytes--;
- }
+ }
- if (state->x >= state->bytes) {
- if (state->bytes % state->xsize && state->bytes > state->xsize) {
- int bands = state->bytes / state->xsize;
- int stride = state->bytes / bands;
- int i;
- for (i=1; i< bands; i++) { // note -- skipping first band
- memmove(&state->buffer[i*state->xsize],
- &state->buffer[i*stride],
- state->xsize);
+ if (state->x >= state->bytes) {
+ if (state->bytes % state->xsize && state->bytes > state->xsize) {
+ int bands = state->bytes / state->xsize;
+ int stride = state->bytes / bands;
+ int i;
+ for (i=1; i< bands; i++) { // note -- skipping first band
+ memmove(&state->buffer[i*state->xsize],
+ &state->buffer[i*stride],
+ state->xsize);
+ }
+ }
+ /* Got a full line, unpack it */
+ state->shuffle((UINT8*) im->image[state->y + state->yoff] +
+ state->xoff * im->pixelsize, state->buffer,
+ state->xsize);
+
+ state->x = 0;
+
+ if (++state->y >= state->ysize) {
+ /* End of file (errcode = 0) */
+ return -1;
}
}
- /* Got a full line, unpack it */
- state->shuffle((UINT8*) im->image[state->y + state->yoff] +
- state->xoff * im->pixelsize, state->buffer,
- state->xsize);
-
- state->x = 0;
-
- if (++state->y >= state->ysize) {
- /* End of file (errcode = 0) */
- return -1;
- }
- }
}
}
diff --git a/src/libImaging/Point.c b/src/libImaging/Point.c
index 9b4bf6b75..b70840b07 100644
--- a/src/libImaging/Point.c
+++ b/src/libImaging/Point.c
@@ -35,8 +35,9 @@ im_point_8_8(Imaging imOut, Imaging imIn, im_point_context* context)
for (y = 0; y < imIn->ysize; y++) {
UINT8* in = imIn->image8[y];
UINT8* out = imOut->image8[y];
- for (x = 0; x < imIn->xsize; x++)
+ for (x = 0; x < imIn->xsize; x++) {
out[x] = table[in[x]];
+ }
}
}
@@ -103,8 +104,9 @@ im_point_8_32(Imaging imOut, Imaging imIn, im_point_context* context)
for (y = 0; y < imIn->ysize; y++) {
UINT8* in = imIn->image8[y];
INT32* out = imOut->image32[y];
- for (x = 0; x < imIn->xsize; x++)
+ for (x = 0; x < imIn->xsize; x++) {
memcpy(out + x, table + in[x] * sizeof(INT32), sizeof(INT32));
+ }
}
}
@@ -119,10 +121,11 @@ im_point_32_8(Imaging imOut, Imaging imIn, im_point_context* context)
UINT8* out = imOut->image8[y];
for (x = 0; x < imIn->xsize; x++) {
int v = in[x];
- if (v < 0)
+ if (v < 0) {
v = 0;
- else if (v > 65535)
+ } else if (v > 65535) {
v = 65535;
+ }
out[x] = table[v];
}
}
@@ -138,21 +141,26 @@ ImagingPoint(Imaging imIn, const char* mode, const void* table)
im_point_context context;
void (*point)(Imaging imIn, Imaging imOut, im_point_context* context);
- if (!imIn)
- return (Imaging) ImagingError_ModeError();
+ if (!imIn) {
+ return (Imaging) ImagingError_ModeError();
+ }
- if (!mode)
+ if (!mode) {
mode = imIn->mode;
+ }
if (imIn->type != IMAGING_TYPE_UINT8) {
- if (imIn->type != IMAGING_TYPE_INT32 || strcmp(mode, "L") != 0)
+ if (imIn->type != IMAGING_TYPE_INT32 || strcmp(mode, "L") != 0) {
goto mode_mismatch;
- } else if (!imIn->image8 && strcmp(imIn->mode, mode) != 0)
+ }
+ } else if (!imIn->image8 && strcmp(imIn->mode, mode) != 0) {
goto mode_mismatch;
+ }
imOut = ImagingNew(mode, imIn->xsize, imIn->ysize);
- if (!imOut)
- return NULL;
+ if (!imOut) {
+ return NULL;
+ }
/* find appropriate handler */
if (imIn->type == IMAGING_TYPE_UINT8) {
@@ -175,10 +183,12 @@ ImagingPoint(Imaging imIn, const char* mode, const void* table)
point = im_point_8_8;
break;
}
- } else
+ } else {
point = im_point_8_32;
- } else
+ }
+ } else {
point = im_point_32_8;
+ }
ImagingCopyPalette(imOut, imIn);
@@ -209,12 +219,14 @@ ImagingPointTransform(Imaging imIn, double scale, double offset)
if (!imIn || (strcmp(imIn->mode, "I") != 0 &&
strcmp(imIn->mode, "I;16") != 0 &&
- strcmp(imIn->mode, "F") != 0))
- return (Imaging) ImagingError_ModeError();
+ strcmp(imIn->mode, "F") != 0)) {
+ return (Imaging) ImagingError_ModeError();
+ }
imOut = ImagingNew(imIn->mode, imIn->xsize, imIn->ysize);
- if (!imOut)
- return NULL;
+ if (!imOut) {
+ return NULL;
+ }
switch (imIn->type) {
case IMAGING_TYPE_INT32:
@@ -223,8 +235,9 @@ ImagingPointTransform(Imaging imIn, double scale, double offset)
INT32* in = imIn->image32[y];
INT32* out = imOut->image32[y];
/* FIXME: add clipping? */
- for (x = 0; x < imIn->xsize; x++)
+ for (x = 0; x < imIn->xsize; x++) {
out[x] = in[x] * scale + offset;
+ }
}
ImagingSectionLeave(&cookie);
break;
@@ -233,8 +246,9 @@ ImagingPointTransform(Imaging imIn, double scale, double offset)
for (y = 0; y < imIn->ysize; y++) {
FLOAT32* in = (FLOAT32*) imIn->image32[y];
FLOAT32* out = (FLOAT32*) imOut->image32[y];
- for (x = 0; x < imIn->xsize; x++)
+ for (x = 0; x < imIn->xsize; x++) {
out[x] = in[x] * scale + offset;
+ }
}
ImagingSectionLeave(&cookie);
break;
@@ -254,7 +268,7 @@ ImagingPointTransform(Imaging imIn, double scale, double offset)
}
ImagingSectionLeave(&cookie);
break;
- }
+ }
/* FALL THROUGH */
default:
ImagingDelete(imOut);
diff --git a/src/libImaging/Quant.c b/src/libImaging/Quant.c
index b94dc6e1d..6c9f8d9b7 100644
--- a/src/libImaging/Quant.c
+++ b/src/libImaging/Quant.c
@@ -157,7 +157,9 @@ create_pixel_hash(Pixel *pixelData,uint32_t nPixels)
/* malloc check ok, small constant allocation */
d=malloc(sizeof(PixelHashData));
- if (!d) return NULL;
+ if (!d) {
+ return NULL;
+ }
hash=hashtable_new(pixel_hash,pixel_cmp);
hashtable_set_user_data(hash,d);
d->scale=0;
@@ -197,7 +199,9 @@ static void
destroy_pixel_hash(HashTable *hash)
{
PixelHashData *d=(PixelHashData *)hashtable_get_user_data(hash);
- if (d) free(d);
+ if (d) {
+ free(d);
+ }
hashtable_free(hash);
}
@@ -214,7 +218,9 @@ static int
compute_box_volume(BoxNode *b)
{
unsigned char rl,rh,gl,gh,bl,bh;
- if (b->volume>=0) return b->volume;
+ if (b->volume>=0) {
+ return b->volume;
+ }
if (!b->head[0]) {
b->volume=0;
} else {
@@ -242,7 +248,9 @@ hash_to_list(const HashTable *h, const Pixel pixel, const uint32_t count, void *
/* malloc check ok, small constant allocation */
p=malloc(sizeof(PixelList));
- if (!p) return;
+ if (!p) {
+ return;
+ }
p->flag=0;
p->p=q;
@@ -250,7 +258,9 @@ hash_to_list(const HashTable *h, const Pixel pixel, const uint32_t count, void *
for (i=0;i<3;i++) {
p->next[i]=pl[i];
p->prev[i]=NULL;
- if (pl[i]) pl[i]->prev[i]=p;
+ if (pl[i]) {
+ pl[i]->prev[i]=p;
+ }
pl[i]=p;
}
}
@@ -268,7 +278,9 @@ mergesort_pixels(PixelList *head, int i)
}
for (c=t=head;c&&t;c=c->next[i],t=(t->next[i])?t->next[i]->next[i]:NULL);
if (c) {
- if (c->prev[i]) c->prev[i]->next[i]=NULL;
+ if (c->prev[i]) {
+ c->prev[i]->next[i]=NULL;
+ }
c->prev[i]=NULL;
}
a=mergesort_pixels(head,i);
@@ -285,9 +297,13 @@ mergesort_pixels(PixelList *head, int i)
}
c->prev[i]=p;
c->next[i]=NULL;
- if (p) p->next[i]=c;
+ if (p) {
+ p->next[i]=c;
+ }
p=c;
- if (!head) head=c;
+ if (!head) {
+ head=c;
+ }
}
if (a) {
c->next[i]=a;
@@ -442,17 +458,29 @@ splitlists(PixelList *h[3],
for (c=h[i];c;c=n) {
n=c->next[i];
if (c->flag) { /* move pixel to right list*/
- if (r) r->next[i]=c; else nh[1][i]=c;
+ if (r) {
+ r->next[i]=c;
+ } else {
+ nh[1][i]=c;
+ }
c->prev[i]=r;
r=c;
} else { /* move pixel to left list */
- if (l) l->next[i]=c; else nh[0][i]=c;
+ if (l) {
+ l->next[i]=c;
+ } else {
+ nh[0][i]=c;
+ }
c->prev[i]=l;
l=c;
}
}
- if (l) l->next[i]=NULL;
- if (r) r->next[i]=NULL;
+ if (l) {
+ l->next[i]=NULL;
+ }
+ if (r) {
+ r->next[i]=NULL;
+ }
nt[0][i]=l;
nt[1][i]=r;
}
@@ -661,8 +689,12 @@ static void
free_box_tree(BoxNode *n)
{
PixelList *p,*pp;
- if (n->l) free_box_tree(n->l);
- if (n->r) free_box_tree(n->r);
+ if (n->l) {
+ free_box_tree(n->l);
+ }
+ if (n->r) {
+ free_box_tree(n->r);
+ }
for (p=n->head[0];p;p=pp) {
pp=p->next[0];
free(p);
@@ -720,7 +752,9 @@ annotate_hash_table(BoxNode *n,HashTable *h,uint32_t *box)
return 0;
}
}
- if (n->head[0]) (*box)++;
+ if (n->head[0]) {
+ (*box)++;
+ }
return 1;
}
@@ -756,7 +790,9 @@ resort_distance_tables(uint32_t *avgDist,
for (k=j;k&&(*(skRow[k-1])>*(skRow[k]));k--) {
skRow[k]=skRow[k-1];
}
- if (k!=j) skRow[k]=skElt;
+ if (k!=j) {
+ skRow[k]=skElt;
+ }
}
}
return 1;
@@ -976,7 +1012,9 @@ compute_palette_from_median_cut(
/* malloc check ok, using calloc */
if (!(avg[i]=calloc(nPaletteEntries, sizeof(uint32_t)))) {
for(i=0;i<3;i++) {
- if (avg[i]) free (avg[i]);
+ if (avg[i]) {
+ free (avg[i]);
+ }
}
free(count);
return 0;
@@ -987,7 +1025,9 @@ compute_palette_from_median_cut(
if (!(i%100)) { printf ("%05d\r",i); fflush(stdout); }
if (checkContained(root,pixelData+i)>1) {
printf ("pixel in two boxes\n");
- for(i=0;i<3;i++) free (avg[i]);
+ for(i=0;i<3;i++) {
+ free (avg[i]);
+ }
free(count);
return 0;
}
@@ -996,7 +1036,9 @@ compute_palette_from_median_cut(
#ifndef NO_OUTPUT
printf ("pixel lookup failed\n");
#endif
- for(i=0;i<3;i++) free (avg[i]);
+ for(i=0;i<3;i++) {
+ free (avg[i]);
+ }
free(count);
return 0;
}
@@ -1004,7 +1046,9 @@ compute_palette_from_median_cut(
#ifndef NO_OUTPUT
printf ("panic - paletteEntry>=nPaletteEntries (%d>=%d)\n",(int)paletteEntry,(int)nPaletteEntries);
#endif
- for(i=0;i<3;i++) free (avg[i]);
+ for(i=0;i<3;i++) {
+ free (avg[i]);
+ }
free(count);
return 0;
}
@@ -1016,7 +1060,9 @@ compute_palette_from_median_cut(
/* malloc check ok, using calloc */
p=calloc(nPaletteEntries, sizeof(Pixel));
if (!p) {
- for(i=0;i<3;i++) free (avg[i]);
+ for(i=0;i<3;i++) {
+ free (avg[i]);
+ }
free(count);
return 0;
}
@@ -1026,7 +1072,9 @@ compute_palette_from_median_cut(
p[i].c.b=(int)(.5+(double)avg[2][i]/(double)count[i]);
}
*palette=p;
- for(i=0;i<3;i++) free (avg[i]);
+ for(i=0;i<3;i++) {
+ free (avg[i]);
+ }
free(count);
return 1;
}
@@ -1156,24 +1204,46 @@ k_means(Pixel *pixelData,
#ifndef NO_OUTPUT
printf (".(%d)",changes);fflush(stdout);
#endif
- if (changes<=threshold) break;
+ if (changes<=threshold) {
+ break;
+ }
}
#ifndef NO_OUTPUT
printf("]\n");
#endif
- if (avgDistSortKey) free(avgDistSortKey);
- if (avgDist) free(avgDist);
- for(i=0;i<3;i++) if (avg[i]) free (avg[i]);
- if (count) free(count);
+ if (avgDistSortKey) {
+ free(avgDistSortKey);
+ }
+ if (avgDist) {
+ free(avgDist);
+ }
+ for(i=0;i<3;i++) {
+ if (avg[i]) {
+ free (avg[i]);
+ }
+ }
+ if (count) {
+ free(count);
+ }
return 1;
error_3:
- if (avgDistSortKey) free(avgDistSortKey);
+ if (avgDistSortKey) {
+ free(avgDistSortKey);
+ }
error_2:
- if (avgDist) free(avgDist);
+ if (avgDist) {
+ free(avgDist);
+ }
error_1:
- for(i=0;i<3;i++) if (avg[i]) free (avg[i]);
- if (count) free(count);
+ for(i=0;i<3;i++) {
+ if (avg[i]) {
+ free (avg[i]);
+ }
+ }
+ if (count) {
+ free(count);
+ }
return 0;
}
@@ -1345,7 +1415,9 @@ quantize(Pixel *pixelData,
#ifndef NO_OUTPUT
printf ("k means...\n"); fflush(stdout); timer=clock();
#endif
- if (kmeans) k_means(pixelData,nPixels,p,nPaletteEntries,qp,kmeans-1);
+ if (kmeans) {
+ k_means(pixelData,nPixels,p,nPaletteEntries,qp,kmeans-1);
+ }
#ifndef NO_OUTPUT
printf ("done (%f)\n",(clock()-timer)/(double)CLOCKS_PER_SEC);
#endif
@@ -1357,8 +1429,12 @@ quantize(Pixel *pixelData,
#ifndef NO_OUTPUT
printf ("cleanup..."); fflush(stdout); timer=clock();
#endif
- if (avgDist) free(avgDist);
- if (avgDistSortKey) free(avgDistSortKey);
+ if (avgDist) {
+ free(avgDist);
+ }
+ if (avgDistSortKey) {
+ free(avgDistSortKey);
+ }
destroy_pixel_hash(h);
#ifndef NO_OUTPUT
printf ("done (%f)\n",(clock()-timer)/(double)CLOCKS_PER_SEC);
@@ -1367,15 +1443,25 @@ quantize(Pixel *pixelData,
return 1;
error_7:
- if (avgDistSortKey) free(avgDistSortKey);
+ if (avgDistSortKey) {
+ free(avgDistSortKey);
+ }
error_6:
- if (avgDist) free(avgDist);
+ if (avgDist) {
+ free(avgDist);
+ }
error_5:
- if (qp) free(qp);
+ if (qp) {
+ free(qp);
+ }
error_4:
- if (p) free(p);
+ if (p) {
+ free(p);
+ }
error_3:
- if (root) free_box_tree(root);
+ if (root) {
+ free_box_tree(root);
+ }
error_1:
destroy_pixel_hash(h);
error_0:
@@ -1430,7 +1516,9 @@ quantize2(Pixel *pixelData,
/* malloc check ok, using calloc */
p=calloc(nQuantPixels, sizeof(Pixel));
- if (!p) return 0;
+ if (!p) {
+ return 0;
+ }
mean[0]=mean[1]=mean[2]=0;
h=hashtable_new(unshifted_pixel_hash,unshifted_pixel_cmp);
for (i=0;i 256)
+ }
+ if (colors < 1 || colors > 256) {
/* FIXME: for colors > 256, consider returning an RGB image
instead (see @PIL205) */
return (Imaging) ImagingError_ValueError("bad number of colors");
+ }
if (strcmp(im->mode, "L") != 0 && strcmp(im->mode, "P") != 0 &&
- strcmp(im->mode, "RGB") != 0 && strcmp(im->mode, "RGBA") !=0)
+ strcmp(im->mode, "RGB") != 0 && strcmp(im->mode, "RGBA") !=0) {
return ImagingError_ModeError();
+ }
/* only octree and imagequant supports RGBA */
- if (!strcmp(im->mode, "RGBA") && mode != 2 && mode != 3)
+ if (!strcmp(im->mode, "RGBA") && mode != 2 && mode != 3) {
return ImagingError_ModeError();
+ }
if (im->xsize > INT_MAX / im->ysize) {
return ImagingError_MemoryError();
}
/* malloc check ok, using calloc for final overflow, x*y above */
p = calloc(im->xsize * im->ysize, sizeof(Pixel));
- if (!p)
+ if (!p) {
return ImagingError_MemoryError();
+ }
/* collect statistics */
@@ -1543,18 +1638,19 @@ ImagingQuantize(Imaging im, int colors, int mode, int kmeans)
/* FIXME: converting a "L" image to "P" with 256 colors
should be done by a simple copy... */
- for (i = y = 0; y < im->ysize; y++)
+ for (i = y = 0; y < im->ysize; y++) {
for (x = 0; x < im->xsize; x++, i++) {
p[i].c.r = p[i].c.g = p[i].c.b = im->image8[y][x];
p[i].c.a = 255;
}
+ }
} else if (!strcmp(im->mode, "P")) {
/* palette */
pp = im->palette->palette;
- for (i = y = 0; y < im->ysize; y++)
+ for (i = y = 0; y < im->ysize; y++) {
for (x = 0; x < im->xsize; x++, i++) {
v = im->image8[y][x];
p[i].c.r = pp[v*4+0];
@@ -1562,13 +1658,16 @@ ImagingQuantize(Imaging im, int colors, int mode, int kmeans)
p[i].c.b = pp[v*4+2];
p[i].c.a = pp[v*4+3];
}
+ }
} else if (!strcmp(im->mode, "RGB") || !strcmp(im->mode, "RGBA")) {
/* true colour */
- for (i = y = 0; y < im->ysize; y++)
- for (x = 0; x < im->xsize; x++, i++)
+ for (i = y = 0; y < im->ysize; y++) {
+ for (x = 0; x < im->xsize; x++, i++) {
p[i].v = im->image32[y][x];
+ }
+ }
} else {
free(p);
@@ -1647,9 +1746,11 @@ ImagingQuantize(Imaging im, int colors, int mode, int kmeans)
imOut = ImagingNewDirty("P", im->xsize, im->ysize);
ImagingSectionEnter(&cookie);
- for (i = y = 0; y < im->ysize; y++)
- for (x = 0; x < im->xsize; x++)
+ for (i = y = 0; y < im->ysize; y++) {
+ for (x = 0; x < im->xsize; x++) {
imOut->image8[y][x] = (unsigned char) newData[i++];
+ }
+ }
free(newData);
diff --git a/src/libImaging/QuantHash.c b/src/libImaging/QuantHash.c
index 3fcbf3c02..6ff95d885 100644
--- a/src/libImaging/QuantHash.c
+++ b/src/libImaging/QuantHash.c
@@ -67,7 +67,9 @@ static uint32_t _findPrime(uint32_t start,int dir) {
continue;
}
for (t=2;t=sqrt((double)start)) {
break;
@@ -144,7 +146,9 @@ static int _hashtable_insert_node(HashTable *h,HashNode *node,int resize,int upd
node->next=*n;
*n=node;
h->count++;
- if (resize) _hashtable_resize(h);
+ if (resize) {
+ _hashtable_resize(h);
+ }
return 1;
} else {
return 0;
@@ -169,13 +173,17 @@ static int _hashtable_insert(HashTable *h,HashKey_t key,HashVal_t val,int resize
}
if (!update) {
t=malloc(sizeof(HashNode));
- if (!t) return 0;
+ if (!t) {
+ return 0;
+ }
t->next=*n;
*n=t;
t->key=key;
t->value=val;
h->count++;
- if (resize) _hashtable_resize(h);
+ if (resize) {
+ _hashtable_resize(h);
+ }
return 1;
} else {
return 0;
@@ -206,7 +214,9 @@ int hashtable_insert_or_update_computed(HashTable *h,
}
}
t=malloc(sizeof(HashNode));
- if (!t) return 0;
+ if (!t) {
+ return 0;
+ }
t->key=key;
t->next=*n;
*n=t;
diff --git a/src/libImaging/QuantHeap.c b/src/libImaging/QuantHeap.c
index 498d44b1d..6877e34a3 100644
--- a/src/libImaging/QuantHeap.c
+++ b/src/libImaging/QuantHeap.c
@@ -46,15 +46,21 @@ void ImagingQuantHeapFree(Heap *h) {
static int _heap_grow(Heap *h,unsigned int newsize) {
void *newheap;
- if (!newsize) newsize=h->heapsize<<1;
- if (newsizeheapsize) return 0;
+ if (!newsize) {
+ newsize=h->heapsize<<1;
+ }
+ if (newsizeheapsize) {
+ return 0;
+ }
if (newsize > INT_MAX / sizeof(void *)){
return 0;
}
/* malloc check ok, using calloc for overflow, also checking
above due to memcpy below*/
newheap=calloc(newsize, sizeof(void *));
- if (!newheap) return 0;
+ if (!newheap) {
+ return 0;
+ }
memcpy(newheap,h->heap,sizeof(void *)*h->heapsize);
free(h->heap);
h->heap=newheap;
@@ -140,7 +146,9 @@ Heap *ImagingQuantHeapNew(HeapCmpFunc cf) {
/* malloc check ok, small constant allocation */
h=malloc(sizeof(Heap));
- if (!h) return NULL;
+ if (!h) {
+ return NULL;
+ }
h->heapsize=INITIAL_SIZE;
/* malloc check ok, using calloc for overflow */
h->heap=calloc(h->heapsize, sizeof(void *));
diff --git a/src/libImaging/QuantOctree.c b/src/libImaging/QuantOctree.c
index 83d987544..fa45ae707 100644
--- a/src/libImaging/QuantOctree.c
+++ b/src/libImaging/QuantOctree.c
@@ -56,7 +56,9 @@ new_color_cube(int r, int g, int b, int a) {
/* malloc check ok, small constant allocation */
cube = malloc(sizeof(struct _ColorCube));
- if (!cube) return NULL;
+ if (!cube) {
+ return NULL;
+ }
cube->rBits = MAX(r, 0);
cube->gBits = MAX(g, 0);
@@ -175,7 +177,9 @@ create_sorted_color_palette(const ColorCube cube) {
}
/* malloc check ok, calloc + overflow check above for memcpy */
buckets = calloc(cube->size, sizeof(struct _ColorBucket));
- if (!buckets) return NULL;
+ if (!buckets) {
+ return NULL;
+ }
memcpy(buckets, cube->buckets, sizeof(struct _ColorBucket)*cube->size);
qsort(buckets, cube->size, sizeof(struct _ColorBucket),
@@ -203,7 +207,9 @@ static ColorCube copy_color_cube(const ColorCube cube,
ColorCube result;
result = new_color_cube(rBits, gBits, bBits, aBits);
- if (!result) return NULL;
+ if (!result) {
+ return NULL;
+ }
if (cube->rBits > rBits) {
dst_reduce[0] = cube->rBits - result->rBits;
@@ -268,7 +274,9 @@ subtract_color_buckets(ColorCube cube, ColorBucket buckets, long nBuckets) {
subtrahend = &buckets[i];
// If the subtrahend contains no buckets, there is nothing to subtract.
- if (subtrahend->count == 0) continue;
+ if (subtrahend->count == 0) {
+ continue;
+ }
avg_color_from_color_bucket(subtrahend, &p);
minuend = color_bucket_from_cube(cube, &p);
@@ -325,7 +333,9 @@ create_palette_array(const ColorBucket palette, unsigned int paletteLength) {
/* malloc check ok, calloc for overflow */
paletteArray = calloc(paletteLength, sizeof(Pixel));
- if (!paletteArray) return NULL;
+ if (!paletteArray) {
+ return NULL;
+ }
for (i=0; i nQuantPixels)
+ if (nCoarseColors > nQuantPixels) {
nCoarseColors = nQuantPixels;
+ }
/* how many space do we have in our palette for fine colors? */
nFineColors = nQuantPixels - nCoarseColors;
/* create fine color palette */
paletteBucketsFine = create_sorted_color_palette(fineCube);
- if (!paletteBucketsFine) goto error;
+ if (!paletteBucketsFine) {
+ goto error;
+ }
/* remove the used fine colors from the coarse cube */
subtract_color_buckets(coarseCube, paletteBucketsFine, nFineColors);
@@ -430,7 +447,9 @@ int quantize_octree(Pixel *pixelData,
/* create our palette buckets with fine and coarse combined */
paletteBucketsCoarse = create_sorted_color_palette(coarseCube);
- if (!paletteBucketsCoarse) goto error;
+ if (!paletteBucketsCoarse) {
+ goto error;
+ }
paletteBuckets = combined_palette(paletteBucketsCoarse, nCoarseColors,
paletteBucketsFine, nFineColors);
@@ -438,19 +457,25 @@ int quantize_octree(Pixel *pixelData,
paletteBucketsFine = NULL;
free(paletteBucketsCoarse);
paletteBucketsCoarse = NULL;
- if (!paletteBuckets) goto error;
+ if (!paletteBuckets) {
+ goto error;
+ }
/* add all coarse colors to our coarse lookup cube. */
coarseLookupCube = new_color_cube(cubeBits[4], cubeBits[5],
cubeBits[6], cubeBits[7]);
- if (!coarseLookupCube) goto error;
+ if (!coarseLookupCube) {
+ goto error;
+ }
add_lookup_buckets(coarseLookupCube, paletteBuckets, nCoarseColors, 0);
/* expand coarse cube (64) to larger fine cube (4k). the value of each
coarse bucket is then present in the according 64 fine buckets. */
lookupCube = copy_color_cube(coarseLookupCube, cubeBits[0], cubeBits[1],
cubeBits[2], cubeBits[3]);
- if (!lookupCube) goto error;
+ if (!lookupCube) {
+ goto error;
+ }
/* add fine colors to the lookup cube */
add_lookup_buckets(lookupCube, paletteBuckets, nFineColors, nCoarseColors);
@@ -458,12 +483,16 @@ int quantize_octree(Pixel *pixelData,
/* create result pixels and map palette indices */
/* malloc check ok, calloc for overflow */
qp = calloc(nPixels, sizeof(Pixel));
- if (!qp) goto error;
+ if (!qp) {
+ goto error;
+ }
map_image_pixels(pixelData, nPixels, lookupCube, qp);
/* convert palette buckets to RGB pixel palette */
*palette = create_palette_array(paletteBuckets, nQuantPixels);
- if (!(*palette)) goto error;
+ if (!(*palette)) {
+ goto error;
+ }
*quantizedPixels = qp;
*paletteLength = nQuantPixels;
diff --git a/src/libImaging/QuantPngQuant.c b/src/libImaging/QuantPngQuant.c
index a9a547540..ef40b282b 100644
--- a/src/libImaging/QuantPngQuant.c
+++ b/src/libImaging/QuantPngQuant.c
@@ -95,9 +95,15 @@ quantize_pngquant(
result = 1;
err:
- if (attr) liq_attr_destroy(attr);
- if (image) liq_image_destroy(image);
- if (remap) liq_result_destroy(remap);
+ if (attr) {
+ liq_attr_destroy(attr);
+ }
+ if (image) {
+ liq_image_destroy(image);
+ }
+ if (remap) {
+ liq_result_destroy(remap);
+ }
free(charMatrix);
free(charMatrixRows);
if (!result) {
diff --git a/src/libImaging/RankFilter.c b/src/libImaging/RankFilter.c
index 0164861bb..e4f2679b2 100644
--- a/src/libImaging/RankFilter.c
+++ b/src/libImaging/RankFilter.c
@@ -30,15 +30,23 @@ static type Rank##type(type a[], int n, int k)\
i = l;\
j = m;\
do {\
- while (a[i] < x) i++;\
- while (x < a[j]) j--;\
+ while (a[i] < x) {\
+ i++;\
+ }\
+ while (x < a[j]) {\
+ j--;\
+ }\
if (i <= j) {\
SWAP(type, a[i], a[j]);\
i++; j--;\
}\
} while (i <= j);\
- if (j < k) l = i;\
- if (k < i) m = j;\
+ if (j < k) {\
+ l = i;\
+ }\
+ if (k < i) {\
+ m = j;\
+ }\
}\
return a[k];\
}
@@ -54,11 +62,13 @@ ImagingRankFilter(Imaging im, int size, int rank)
int x, y;
int i, margin, size2;
- if (!im || im->bands != 1 || im->type == IMAGING_TYPE_SPECIAL)
+ if (!im || im->bands != 1 || im->type == IMAGING_TYPE_SPECIAL) {
return (Imaging) ImagingError_ModeError();
+ }
- if (!(size & 1))
+ if (!(size & 1)) {
return (Imaging) ImagingError_ValueError("bad filter size");
+ }
/* malloc check ok, for overflow in the define below */
if (size > INT_MAX / size ||
@@ -69,35 +79,40 @@ ImagingRankFilter(Imaging im, int size, int rank)
size2 = size * size;
margin = (size-1) / 2;
- if (rank < 0 || rank >= size2)
+ if (rank < 0 || rank >= size2) {
return (Imaging) ImagingError_ValueError("bad rank value");
+ }
imOut = ImagingNew(im->mode, im->xsize - 2*margin, im->ysize - 2*margin);
- if (!imOut)
+ if (!imOut) {
return NULL;
+ }
/* malloc check ok, checked above */
#define RANK_BODY(type) do {\
type* buf = malloc(size2 * sizeof(type));\
- if (!buf)\
+ if (!buf) {\
goto nomemory;\
- for (y = 0; y < imOut->ysize; y++)\
+ }\
+ for (y = 0; y < imOut->ysize; y++) {\
for (x = 0; x < imOut->xsize; x++) {\
- for (i = 0; i < size; i++)\
+ for (i = 0; i < size; i++) {\
memcpy(buf + i*size, &IMAGING_PIXEL_##type(im, x, y+i),\
size * sizeof(type));\
+ }\
IMAGING_PIXEL_##type(imOut, x, y) = Rank##type(buf, size2, rank);\
}\
+ }\
free(buf); \
} while (0)
- if (im->image8)
+ if (im->image8) {
RANK_BODY(UINT8);
- else if (im->type == IMAGING_TYPE_INT32)
+ } else if (im->type == IMAGING_TYPE_INT32) {
RANK_BODY(INT32);
- else if (im->type == IMAGING_TYPE_FLOAT32)
+ } else if (im->type == IMAGING_TYPE_FLOAT32) {
RANK_BODY(FLOAT32);
- else {
+ } else {
/* safety net (we shouldn't end up here) */
ImagingDelete(imOut);
return (Imaging) ImagingError_ModeError();
diff --git a/src/libImaging/RawDecode.c b/src/libImaging/RawDecode.c
index c069bdb88..ca3d37149 100644
--- a/src/libImaging/RawDecode.c
+++ b/src/libImaging/RawDecode.c
@@ -5,7 +5,7 @@
* decoder for raw (uncompressed) image data
*
* history:
- * 96-03-07 fl rewritten
+ * 96-03-07 fl rewritten
*
* Copyright (c) Fredrik Lundh 1996.
* Copyright (c) Secret Labs AB 1997.
@@ -29,28 +29,29 @@ ImagingRawDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt
if (state->state == 0) {
- /* Initialize context variables */
+ /* Initialize context variables */
- /* get size of image data and padding */
- state->bytes = (state->xsize * state->bits + 7) / 8;
- if (rawstate->stride) {
- rawstate->skip = rawstate->stride - state->bytes;
- if (rawstate->skip < 0) {
- state->errcode = IMAGING_CODEC_CONFIG;
- return -1;
- }
- } else {
- rawstate->skip = 0;
- }
+ /* get size of image data and padding */
+ state->bytes = (state->xsize * state->bits + 7) / 8;
+ if (rawstate->stride) {
+ rawstate->skip = rawstate->stride - state->bytes;
+ if (rawstate->skip < 0) {
+ state->errcode = IMAGING_CODEC_CONFIG;
+ return -1;
+ }
+ } else {
+ rawstate->skip = 0;
+ }
- /* check image orientation */
- if (state->ystep < 0) {
- state->y = state->ysize-1;
- state->ystep = -1;
- } else
- state->ystep = 1;
+ /* check image orientation */
+ if (state->ystep < 0) {
+ state->y = state->ysize-1;
+ state->ystep = -1;
+ } else {
+ state->ystep = 1;
+ }
- state->state = LINE;
+ state->state = LINE;
}
@@ -58,38 +59,40 @@ ImagingRawDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt
for (;;) {
- if (state->state == SKIP) {
+ if (state->state == SKIP) {
- /* Skip padding between lines */
+ /* Skip padding between lines */
- if (bytes < rawstate->skip)
- return ptr - buf;
+ if (bytes < rawstate->skip) {
+ return ptr - buf;
+ }
- ptr += rawstate->skip;
- bytes -= rawstate->skip;
+ ptr += rawstate->skip;
+ bytes -= rawstate->skip;
- state->state = LINE;
+ state->state = LINE;
- }
+ }
- if (bytes < state->bytes)
- return ptr - buf;
+ if (bytes < state->bytes) {
+ return ptr - buf;
+ }
- /* Unpack data */
- state->shuffle((UINT8*) im->image[state->y + state->yoff] +
- state->xoff * im->pixelsize, ptr, state->xsize);
+ /* Unpack data */
+ state->shuffle((UINT8*) im->image[state->y + state->yoff] +
+ state->xoff * im->pixelsize, ptr, state->xsize);
- ptr += state->bytes;
- bytes -= state->bytes;
+ ptr += state->bytes;
+ bytes -= state->bytes;
- state->y += state->ystep;
+ state->y += state->ystep;
- if (state->y < 0 || state->y >= state->ysize) {
- /* End of file (errcode = 0) */
- return -1;
- }
+ if (state->y < 0 || state->y >= state->ysize) {
+ /* End of file (errcode = 0) */
+ return -1;
+ }
- state->state = SKIP;
+ state->state = SKIP;
}
diff --git a/src/libImaging/RawEncode.c b/src/libImaging/RawEncode.c
index a3b74b8cf..fb4ab3346 100644
--- a/src/libImaging/RawEncode.c
+++ b/src/libImaging/RawEncode.c
@@ -9,8 +9,8 @@
* in ImageFile.py, but it should be solved here instead.
*
* history:
- * 96-04-30 fl created
- * 97-01-03 fl fixed padding
+ * 96-04-30 fl created
+ * 97-01-03 fl fixed padding
*
* Copyright (c) Fredrik Lundh 1996-97.
* Copyright (c) Secret Labs AB 1997.
@@ -27,60 +27,63 @@ ImagingRawEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
if (!state->state) {
- /* The "count" field holds the stride, if specified. Fix
- things up so "bytes" is the full size, and "count" the
- packed size */
+ /* The "count" field holds the stride, if specified. Fix
+ things up so "bytes" is the full size, and "count" the
+ packed size */
- if (state->count > 0) {
- int bytes = state->count;
+ if (state->count > 0) {
+ int bytes = state->count;
- /* stride must not be less than real size */
- if (state->count < state->bytes) {
- state->errcode = IMAGING_CODEC_CONFIG;
- return -1;
- }
- state->count = state->bytes;
- state->bytes = bytes;
- } else
- state->count = state->bytes;
+ /* stride must not be less than real size */
+ if (state->count < state->bytes) {
+ state->errcode = IMAGING_CODEC_CONFIG;
+ return -1;
+ }
+ state->count = state->bytes;
+ state->bytes = bytes;
+ } else {
+ state->count = state->bytes;
+ }
- /* The "ystep" field specifies the orientation */
+ /* The "ystep" field specifies the orientation */
- if (state->ystep < 0) {
- state->y = state->ysize-1;
- state->ystep = -1;
- } else
- state->ystep = 1;
+ if (state->ystep < 0) {
+ state->y = state->ysize-1;
+ state->ystep = -1;
+ } else {
+ state->ystep = 1;
+ }
- state->state = 1;
+ state->state = 1;
}
if (bytes < state->bytes) {
- state->errcode = IMAGING_CODEC_CONFIG;
- return 0;
+ state->errcode = IMAGING_CODEC_CONFIG;
+ return 0;
}
ptr = buf;
while (bytes >= state->bytes) {
- state->shuffle(ptr, (UINT8*) im->image[state->y + state->yoff] +
- state->xoff * im->pixelsize, state->xsize);
+ state->shuffle(ptr, (UINT8*) im->image[state->y + state->yoff] +
+ state->xoff * im->pixelsize, state->xsize);
- if (state->bytes > state->count)
- /* zero-pad the buffer, if necessary */
- memset(ptr + state->count, 0, state->bytes - state->count);
+ if (state->bytes > state->count) {
+ /* zero-pad the buffer, if necessary */
+ memset(ptr + state->count, 0, state->bytes - state->count);
+ }
- ptr += state->bytes;
- bytes -= state->bytes;
+ ptr += state->bytes;
+ bytes -= state->bytes;
- state->y += state->ystep;
+ state->y += state->ystep;
- if (state->y < 0 || state->y >= state->ysize) {
- state->errcode = IMAGING_CODEC_END;
- break;
- }
+ if (state->y < 0 || state->y >= state->ysize) {
+ state->errcode = IMAGING_CODEC_END;
+ break;
+ }
}
diff --git a/src/libImaging/Reduce.c b/src/libImaging/Reduce.c
index d6ef92f5b..f6488deb2 100644
--- a/src/libImaging/Reduce.c
+++ b/src/libImaging/Reduce.c
@@ -1374,11 +1374,13 @@ ImagingReduce(Imaging imIn, int xscale, int yscale, int box[4])
ImagingSectionCookie cookie;
Imaging imOut = NULL;
- if (strcmp(imIn->mode, "P") == 0 || strcmp(imIn->mode, "1") == 0)
+ if (strcmp(imIn->mode, "P") == 0 || strcmp(imIn->mode, "1") == 0) {
return (Imaging) ImagingError_ModeError();
+ }
- if (imIn->type == IMAGING_TYPE_SPECIAL)
+ if (imIn->type == IMAGING_TYPE_SPECIAL) {
return (Imaging) ImagingError_ModeError();
+ }
imOut = ImagingNewDirty(imIn->mode,
(box[2] + xscale - 1) / xscale,
diff --git a/src/libImaging/Resample.c b/src/libImaging/Resample.c
index 0dc08611d..ec35303d8 100644
--- a/src/libImaging/Resample.c
+++ b/src/libImaging/Resample.c
@@ -13,28 +13,34 @@ struct filter {
static inline double box_filter(double x)
{
- if (x > -0.5 && x <= 0.5)
+ if (x > -0.5 && x <= 0.5) {
return 1.0;
+ }
return 0.0;
}
static inline double bilinear_filter(double x)
{
- if (x < 0.0)
+ if (x < 0.0) {
x = -x;
- if (x < 1.0)
+ }
+ if (x < 1.0) {
return 1.0-x;
+ }
return 0.0;
}
static inline double hamming_filter(double x)
{
- if (x < 0.0)
+ if (x < 0.0) {
x = -x;
- if (x == 0.0)
+ }
+ if (x == 0.0) {
return 1.0;
- if (x >= 1.0)
+ }
+ if (x >= 1.0) {
return 0.0;
+ }
x = x * M_PI;
return sin(x) / x * (0.54f + 0.46f * cos(x));
}
@@ -43,20 +49,24 @@ static inline double bicubic_filter(double x)
{
/* https://en.wikipedia.org/wiki/Bicubic_interpolation#Bicubic_convolution_algorithm */
#define a -0.5
- if (x < 0.0)
+ if (x < 0.0) {
x = -x;
- if (x < 1.0)
+ }
+ if (x < 1.0) {
return ((a + 2.0) * x - (a + 3.0)) * x*x + 1;
- if (x < 2.0)
+ }
+ if (x < 2.0) {
return (((x - 5) * x + 8) * x - 4) * a;
+ }
return 0.0;
#undef a
}
static inline double sinc_filter(double x)
{
- if (x == 0.0)
+ if (x == 0.0) {
return 1.0;
+ }
x = x * M_PI;
return sin(x) / x;
}
@@ -64,8 +74,9 @@ static inline double sinc_filter(double x)
static inline double lanczos_filter(double x)
{
/* truncated sinc */
- if (-3.0 <= x && x < 3.0)
+ if (-3.0 <= x && x < 3.0) {
return sinc_filter(x) * sinc_filter(x/3);
+ }
return 0.0;
}
@@ -224,12 +235,14 @@ precompute_coeffs(int inSize, float in0, float in1, int outSize,
ss = 1.0 / filterscale;
// Round the value
xmin = (int) (center - support + 0.5);
- if (xmin < 0)
+ if (xmin < 0) {
xmin = 0;
+ }
// Round the value
xmax = (int) (center + support + 0.5);
- if (xmax > inSize)
+ if (xmax > inSize) {
xmax = inSize;
+ }
xmax -= xmin;
k = &kk[xx * ksize];
for (x = 0; x < xmax; x++) {
@@ -238,8 +251,9 @@ precompute_coeffs(int inSize, float in0, float in1, int outSize,
ww += w;
}
for (x = 0; x < xmax; x++) {
- if (ww != 0.0)
+ if (ww != 0.0) {
k[x] /= ww;
+ }
}
// Remaining values should stay empty if they are used despite of xmax.
for (; x < ksize; x++) {
@@ -295,8 +309,9 @@ ImagingResampleHorizontal_8bpc(Imaging imOut, Imaging imIn, int offset,
xmax = bounds[xx * 2 + 1];
k = &kk[xx * ksize];
ss0 = 1 << (PRECISION_BITS -1);
- for (x = 0; x < xmax; x++)
+ for (x = 0; x < xmax; x++) {
ss0 += ((UINT8) imIn->image8[yy + offset][x + xmin]) * k[x];
+ }
imOut->image8[yy][xx] = clip8(ss0);
}
}
@@ -379,8 +394,9 @@ ImagingResampleVertical_8bpc(Imaging imOut, Imaging imIn, int offset,
ymax = bounds[yy * 2 + 1];
for (xx = 0; xx < imOut->xsize; xx++) {
ss0 = 1 << (PRECISION_BITS -1);
- for (y = 0; y < ymax; y++)
+ for (y = 0; y < ymax; y++) {
ss0 += ((UINT8) imIn->image8[y + ymin][xx]) * k[y];
+ }
imOut->image8[yy][xx] = clip8(ss0);
}
}
@@ -460,8 +476,9 @@ ImagingResampleHorizontal_32bpc(Imaging imOut, Imaging imIn, int offset,
xmax = bounds[xx * 2 + 1];
k = &kk[xx * ksize];
ss = 0.0;
- for (x = 0; x < xmax; x++)
+ for (x = 0; x < xmax; x++) {
ss += IMAGING_PIXEL_I(imIn, x + xmin, yy + offset) * k[x];
+ }
IMAGING_PIXEL_I(imOut, xx, yy) = ROUND_UP(ss);
}
}
@@ -474,8 +491,9 @@ ImagingResampleHorizontal_32bpc(Imaging imOut, Imaging imIn, int offset,
xmax = bounds[xx * 2 + 1];
k = &kk[xx * ksize];
ss = 0.0;
- for (x = 0; x < xmax; x++)
+ for (x = 0; x < xmax; x++) {
ss += IMAGING_PIXEL_F(imIn, x + xmin, yy + offset) * k[x];
+ }
IMAGING_PIXEL_F(imOut, xx, yy) = ss;
}
}
@@ -503,8 +521,9 @@ ImagingResampleVertical_32bpc(Imaging imOut, Imaging imIn, int offset,
k = &kk[yy * ksize];
for (xx = 0; xx < imOut->xsize; xx++) {
ss = 0.0;
- for (y = 0; y < ymax; y++)
+ for (y = 0; y < ymax; y++) {
ss += IMAGING_PIXEL_I(imIn, xx, y + ymin) * k[y];
+ }
IMAGING_PIXEL_I(imOut, xx, yy) = ROUND_UP(ss);
}
}
@@ -517,8 +536,9 @@ ImagingResampleVertical_32bpc(Imaging imOut, Imaging imIn, int offset,
k = &kk[yy * ksize];
for (xx = 0; xx < imOut->xsize; xx++) {
ss = 0.0;
- for (y = 0; y < ymax; y++)
+ for (y = 0; y < ymax; y++) {
ss += IMAGING_PIXEL_F(imIn, xx, y + ymin) * k[y];
+ }
IMAGING_PIXEL_F(imOut, xx, yy) = ss;
}
}
@@ -546,8 +566,9 @@ ImagingResample(Imaging imIn, int xsize, int ysize, int filter, float box[4])
ResampleFunction ResampleHorizontal;
ResampleFunction ResampleVertical;
- if (strcmp(imIn->mode, "P") == 0 || strcmp(imIn->mode, "1") == 0)
+ if (strcmp(imIn->mode, "P") == 0 || strcmp(imIn->mode, "1") == 0) {
return (Imaging) ImagingError_ModeError();
+ }
if (imIn->type == IMAGING_TYPE_SPECIAL) {
return (Imaging) ImagingError_ModeError();
diff --git a/src/libImaging/SgiRleDecode.c b/src/libImaging/SgiRleDecode.c
index 3f9400a5b..a03ecd456 100644
--- a/src/libImaging/SgiRleDecode.c
+++ b/src/libImaging/SgiRleDecode.c
@@ -6,7 +6,7 @@
*
* history:
* 2017-07-28 mb fixed for images larger than 64KB
- * 2017-07-20 mb created
+ * 2017-07-20 mb created
*
* Copyright (c) Mickael Bonfill 2017.
*
@@ -33,11 +33,13 @@ static int expandrow(UINT8* dest, UINT8* src, int n, int z, int xsize)
for (;n > 0; n--)
{
pixel = *src++;
- if (n == 1 && pixel != 0)
+ if (n == 1 && pixel != 0) {
return n;
+ }
count = pixel & RLE_MAX_RUN;
- if (!count)
+ if (!count) {
return count;
+ }
if (x + count > xsize) {
return -1;
}
@@ -71,11 +73,13 @@ static int expandrow2(UINT8* dest, const UINT8* src, int n, int z, int xsize)
{
pixel = src[1];
src+=2;
- if (n == 1 && pixel != 0)
+ if (n == 1 && pixel != 0) {
return n;
+ }
count = pixel & RLE_MAX_RUN;
- if (!count)
+ if (!count) {
return count;
+ }
if (x + count > xsize) {
return -1;
}
@@ -101,7 +105,7 @@ static int expandrow2(UINT8* dest, const UINT8* src, int n, int z, int xsize)
int
ImagingSgiRleDecode(Imaging im, ImagingCodecState state,
- UINT8* buf, Py_ssize_t bytes)
+ UINT8* buf, Py_ssize_t bytes)
{
UINT8 *ptr;
SGISTATE *c;
@@ -151,11 +155,13 @@ ImagingSgiRleDecode(Imaging im, ImagingCodecState state,
goto sgi_finish_decode;
}
/* populate offsets table */
- for (c->tabindex = 0, c->bufindex = 0; c->tabindex < c->tablen; c->tabindex++, c->bufindex+=4)
+ for (c->tabindex = 0, c->bufindex = 0; c->tabindex < c->tablen; c->tabindex++, c->bufindex+=4) {
read4B(&c->starttab[c->tabindex], &ptr[c->bufindex]);
+ }
/* populate lengths table */
- for (c->tabindex = 0, c->bufindex = c->tablen * sizeof(UINT32); c->tabindex < c->tablen; c->tabindex++, c->bufindex+=4)
+ for (c->tabindex = 0, c->bufindex = c->tablen * sizeof(UINT32); c->tabindex < c->tablen; c->tabindex++, c->bufindex+=4) {
read4B(&c->lengthtab[c->tabindex], &ptr[c->bufindex]);
+ }
state->count += c->tablen * sizeof(UINT32) * 2;
diff --git a/src/libImaging/Storage.c b/src/libImaging/Storage.c
index ab476939a..c9a24e6aa 100644
--- a/src/libImaging/Storage.c
+++ b/src/libImaging/Storage.c
@@ -244,17 +244,21 @@ ImagingNewPrologue(const char *mode, int xsize, int ysize)
void
ImagingDelete(Imaging im)
{
- if (!im)
+ if (!im) {
return;
+ }
- if (im->palette)
+ if (im->palette) {
ImagingPaletteDelete(im->palette);
+ }
- if (im->destroy)
+ if (im->destroy) {
im->destroy(im);
+ }
- if (im->image)
+ if (im->image) {
free(im->image);
+ }
free(im);
}
@@ -399,8 +403,9 @@ ImagingAllocateArray(Imaging im, int dirty, int block_size)
aligned_linesize = (im->linesize + arena->alignment - 1) & -arena->alignment;
lines_per_block = (block_size - (arena->alignment - 1)) / aligned_linesize;
- if (lines_per_block == 0)
+ if (lines_per_block == 0) {
lines_per_block = 1;
+ }
blocks_count = (im->ysize + lines_per_block - 1) / lines_per_block;
// printf("NEW size: %dx%d, ls: %d, lpb: %d, blocks: %d\n",
// im->xsize, im->ysize, aligned_linesize, lines_per_block, blocks_count);
@@ -457,8 +462,9 @@ ImagingAllocateArray(Imaging im, int dirty, int block_size)
static void
ImagingDestroyBlock(Imaging im)
{
- if (im->block)
+ if (im->block) {
free(im->block);
+ }
}
Imaging
@@ -510,8 +516,9 @@ ImagingNewInternal(const char* mode, int xsize, int ysize, int dirty)
}
im = ImagingNewPrologue(mode, xsize, ysize);
- if ( ! im)
+ if ( ! im) {
return NULL;
+ }
if (ImagingAllocateArray(im, dirty, ImagingDefaultArena.block_size)) {
return im;
@@ -550,8 +557,9 @@ ImagingNewBlock(const char* mode, int xsize, int ysize)
}
im = ImagingNewPrologue(mode, xsize, ysize);
- if ( ! im)
+ if ( ! im) {
return NULL;
+ }
if (ImagingAllocateBlock(im)) {
return im;
@@ -576,8 +584,9 @@ ImagingNew2Dirty(const char* mode, Imaging imOut, Imaging imIn)
} else {
/* create new image */
imOut = ImagingNewDirty(mode, imIn->xsize, imIn->ysize);
- if (!imOut)
+ if (!imOut) {
return NULL;
+ }
}
return imOut;
@@ -587,8 +596,9 @@ void
ImagingCopyPalette(Imaging destination, Imaging source)
{
if (source->palette) {
- if (destination->palette)
+ if (destination->palette) {
ImagingPaletteDelete(destination->palette);
+ }
destination->palette = ImagingPaletteDuplicate(source->palette);
}
}
diff --git a/src/libImaging/SunRleDecode.c b/src/libImaging/SunRleDecode.c
index e627c2c9a..acb39133a 100644
--- a/src/libImaging/SunRleDecode.c
+++ b/src/libImaging/SunRleDecode.c
@@ -31,13 +31,15 @@ ImagingSunRleDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t
for (;;) {
- if (bytes < 1)
+ if (bytes < 1) {
return ptr - buf;
+ }
if (ptr[0] == 0x80) {
- if (bytes < 2)
+ if (bytes < 2) {
break;
+ }
n = ptr[1];
@@ -55,8 +57,9 @@ ImagingSunRleDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t
} else {
/* Run (3 bytes) */
- if (bytes < 3)
+ if (bytes < 3) {
break;
+ }
/* from (https://www.fileformat.info/format/sunraster/egff.htm)
diff --git a/src/libImaging/TgaRleDecode.c b/src/libImaging/TgaRleDecode.c
index d1971e546..b1364e004 100644
--- a/src/libImaging/TgaRleDecode.c
+++ b/src/libImaging/TgaRleDecode.c
@@ -5,8 +5,8 @@
* decoder for Targa RLE data.
*
* history:
- * 97-01-04 fl created
- * 98-09-11 fl don't one byte per pixel; take orientation into account
+ * 97-01-04 fl created
+ * 98-09-11 fl don't one byte per pixel; take orientation into account
*
* Copyright (c) Fredrik Lundh 1997.
* Copyright (c) Secret Labs AB 1997-98.
@@ -20,7 +20,7 @@
int
ImagingTgaRleDecode(Imaging im, ImagingCodecState state,
- UINT8* buf, Py_ssize_t bytes)
+ UINT8* buf, Py_ssize_t bytes)
{
int n, depth;
UINT8* ptr;
@@ -29,14 +29,15 @@ ImagingTgaRleDecode(Imaging im, ImagingCodecState state,
if (state->state == 0) {
- /* check image orientation */
- if (state->ystep < 0) {
- state->y = state->ysize-1;
- state->ystep = -1;
- } else
- state->ystep = 1;
+ /* check image orientation */
+ if (state->ystep < 0) {
+ state->y = state->ysize-1;
+ state->ystep = -1;
+ } else {
+ state->ystep = 1;
+ }
- state->state = 1;
+ state->state = 1;
}
@@ -44,64 +45,68 @@ ImagingTgaRleDecode(Imaging im, ImagingCodecState state,
for (;;) {
- if (bytes < 1)
- return ptr - buf;
+ if (bytes < 1) {
+ return ptr - buf;
+ }
- if (ptr[0] & 0x80) {
+ if (ptr[0] & 0x80) {
- /* Run (1 + pixelsize bytes) */
+ /* Run (1 + pixelsize bytes) */
- if (bytes < 1 + depth)
- break;
+ if (bytes < 1 + depth) {
+ break;
+ }
- n = depth * ((ptr[0] & 0x7f) + 1);
+ n = depth * ((ptr[0] & 0x7f) + 1);
- if (state->x + n > state->bytes) {
- state->errcode = IMAGING_CODEC_OVERRUN;
- return -1;
- }
+ if (state->x + n > state->bytes) {
+ state->errcode = IMAGING_CODEC_OVERRUN;
+ return -1;
+ }
- if (depth == 1)
+ if (depth == 1) {
memset(state->buffer + state->x, ptr[1], n);
- else {
+ } else {
int i;
- for (i = 0; i < n; i += depth)
+ for (i = 0; i < n; i += depth) {
memcpy(state->buffer + state->x + i, ptr+1, depth);
+ }
}
ptr += 1 + depth;
- bytes -= 1 + depth;
+ bytes -= 1 + depth;
- } else {
+ } else {
- /* Literal (1+n+1 bytes block) */
- n = depth * (ptr[0] + 1);
+ /* Literal (1+n+1 bytes block) */
+ n = depth * (ptr[0] + 1);
- if (bytes < 1 + n)
- break;
+ if (bytes < 1 + n) {
+ break;
+ }
- if (state->x + n > state->bytes) {
- state->errcode = IMAGING_CODEC_OVERRUN;
- return -1;
- }
+ if (state->x + n > state->bytes) {
+ state->errcode = IMAGING_CODEC_OVERRUN;
+ return -1;
+ }
- memcpy(state->buffer + state->x, ptr + 1, n);
+ memcpy(state->buffer + state->x, ptr + 1, n);
- ptr += 1 + n;
- bytes -= 1 + n;
+ ptr += 1 + n;
+ bytes -= 1 + n;
- }
+ }
- state->x += n;
+ state->x += n;
- if (state->x >= state->bytes) {
+ if (state->x >= state->bytes) {
- /* Got a full line, unpack it */
- state->shuffle((UINT8*) im->image[state->y + state->yoff] +
- state->xoff * im->pixelsize, state->buffer,
- state->xsize);
+ /* Got a full line, unpack it */
+ state->shuffle((UINT8*) im->image[state->y + state->yoff] +
+ state->xoff * im->pixelsize, state->buffer,
+ state->xsize);
- state->x = 0;
+ state->x = 0;
state->y += state->ystep;
@@ -110,7 +115,7 @@ ImagingTgaRleDecode(Imaging im, ImagingCodecState state,
return -1;
}
- }
+ }
}
diff --git a/src/libImaging/TgaRleEncode.c b/src/libImaging/TgaRleEncode.c
index 2fb831e6b..c65dcf5ec 100644
--- a/src/libImaging/TgaRleEncode.c
+++ b/src/libImaging/TgaRleEncode.c
@@ -22,8 +22,9 @@ ImagingTgaRleEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
if (state->ystep < 0) {
state->ystep = -1;
state->y = state->ysize - 1;
- } else
+ } else {
state->ystep = 1;
+ }
state->state = 1;
}
@@ -46,8 +47,9 @@ ImagingTgaRleEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
assert(state->x <= state->xsize);
/* Make sure we have space for the descriptor. */
- if (bytes < 1)
+ if (bytes < 1) {
break;
+ }
if (state->x == state->xsize) {
state->x = 0;
@@ -59,12 +61,13 @@ ImagingTgaRleEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
}
}
- if (state->x == 0)
+ if (state->x == 0) {
state->shuffle(
state->buffer,
(UINT8*)im->image[state->y + state->yoff]
+ state->xoff * im->pixelsize,
state->xsize);
+ }
row = state->buffer;
@@ -87,28 +90,32 @@ ImagingTgaRleEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
*/
maxLookup = state->x + 126;
/* A packet must not span multiple rows. */
- if (maxLookup > state->xsize - 1)
+ if (maxLookup > state->xsize - 1) {
maxLookup = state->xsize - 1;
+ }
if (isRaw) {
- while (state->x < maxLookup)
- if (!comparePixels(row, state->x, bytesPerPixel))
+ while (state->x < maxLookup) {
+ if (!comparePixels(row, state->x, bytesPerPixel)) {
++state->x;
- else {
+ } else {
/* Two identical pixels will go to RLE packet. */
--state->x;
break;
}
+ }
state->count += (state->x - startX) * bytesPerPixel;
} else {
descriptor |= 0x80;
- while (state->x < maxLookup)
- if (comparePixels(row, state->x, bytesPerPixel))
+ while (state->x < maxLookup) {
+ if (comparePixels(row, state->x, bytesPerPixel)) {
++state->x;
- else
+ } else {
break;
+ }
+ }
}
}
@@ -132,12 +139,14 @@ ImagingTgaRleEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
assert(state->x > 0);
assert(state->count <= state->x * bytesPerPixel);
- if (bytes == 0)
+ if (bytes == 0) {
break;
+ }
flushCount = state->count;
- if (flushCount > bytes)
+ if (flushCount > bytes) {
flushCount = bytes;
+ }
memcpy(
dst,
diff --git a/src/libImaging/TiffDecode.h b/src/libImaging/TiffDecode.h
index 08ef35cfd..3d27e65b6 100644
--- a/src/libImaging/TiffDecode.h
+++ b/src/libImaging/TiffDecode.h
@@ -28,17 +28,17 @@
#define _PIL_LIBTIFF_
typedef struct {
- tdata_t data; /* tdata_t == void* */
- toff_t loc; /* toff_t == uint32 */
- tsize_t size; /* tsize_t == int32 */
- int fp;
+ tdata_t data; /* tdata_t == void* */
+ toff_t loc; /* toff_t == uint32 */
+ tsize_t size; /* tsize_t == int32 */
+ int fp;
uint32 ifd; /* offset of the ifd, used for multipage
* Should be uint32 for libtiff 3.9.x
* uint64 for libtiff 4.0.x
*/
- TIFF *tiff; /* Used in write */
- toff_t eof;
- int flrealloc;/* may we realloc */
+ TIFF *tiff; /* Used in write */
+ toff_t eof;
+ int flrealloc;/* may we realloc */
} TIFFSTATE;
@@ -55,7 +55,7 @@ extern int ImagingLibTiffSetField(ImagingCodecState state, ttag_t tag, ...);
*/
/*
-#define VA_ARGS(...) __VA_ARGS__
+#define VA_ARGS(...) __VA_ARGS__
#define TRACE(args) fprintf(stderr, VA_ARGS args)
*/
diff --git a/src/libImaging/Unpack.c b/src/libImaging/Unpack.c
index adf2dd277..917da6ab3 100644
--- a/src/libImaging/Unpack.c
+++ b/src/libImaging/Unpack.c
@@ -350,8 +350,9 @@ unpackLI(UINT8* out, const UINT8* in, int pixels)
{
/* negative */
int i;
- for (i = 0; i < pixels; i++)
+ for (i = 0; i < pixels; i++) {
out[i] = ~in[i];
+ }
}
static void
@@ -998,7 +999,7 @@ unpackI16N_I16B(UINT8* out, const UINT8* in, int pixels){
UINT8* tmp = (UINT8*) out;
for (i = 0; i < pixels; i++) {
C16B;
- in += 2; tmp += 2;
+ in += 2; tmp += 2;
}
}
@@ -1008,7 +1009,7 @@ unpackI16N_I16(UINT8* out, const UINT8* in, int pixels){
UINT8* tmp = (UINT8*) out;
for (i = 0; i < pixels; i++) {
C16L;
- in += 2; tmp += 2;
+ in += 2; tmp += 2;
}
}
@@ -1053,7 +1054,7 @@ unpackI12_I16(UINT8* out, const UINT8* in, int pixels){
memcpy(out, &pixel, sizeof(pixel));
#endif
- in += 3; out+=2;
+ in += 3; out+=2;
}
if (i == pixels-1) {
pixel = (((UINT16) in[0]) << 4 ) + (in[1] >>4);
@@ -1115,8 +1116,9 @@ static void NAME(UINT8* out_, const UINT8* in, int pixels)\
{\
int i;\
OUTTYPE* out = (OUTTYPE*) out_;\
- for (i = 0; i < pixels; i++, in += sizeof(INTYPE))\
+ for (i = 0; i < pixels; i++, in += sizeof(INTYPE)) {\
out[i] = (OUTTYPE) ((INTYPE) GET);\
+ }\
}
#define UNPACK(NAME, COPY, INTYPE, OUTTYPE)\
@@ -1306,7 +1308,7 @@ static struct {
/* greyscale w. alpha */
{"LA", "LA", 16, unpackLA},
{"LA", "LA;L", 16, unpackLAL},
-
+
/* greyscale w. alpha premultiplied */
{"La", "La", 16, unpackLA},
@@ -1447,16 +1449,16 @@ static struct {
{"YCbCr", "YCbCrK", 32, copy4},
/* LAB Color */
- {"LAB", "LAB", 24, ImagingUnpackLAB},
- {"LAB", "L", 8, band0},
- {"LAB", "A", 8, band1},
- {"LAB", "B", 8, band2},
+ {"LAB", "LAB", 24, ImagingUnpackLAB},
+ {"LAB", "L", 8, band0},
+ {"LAB", "A", 8, band1},
+ {"LAB", "B", 8, band2},
/* HSV Color */
- {"HSV", "HSV", 24, ImagingUnpackRGB},
- {"HSV", "H", 8, band0},
- {"HSV", "S", 8, band1},
- {"HSV", "V", 8, band2},
+ {"HSV", "HSV", 24, ImagingUnpackRGB},
+ {"HSV", "H", 8, band0},
+ {"HSV", "S", 8, band1},
+ {"HSV", "V", 8, band2},
/* integer variations */
{"I", "I", 32, copy4},
@@ -1505,11 +1507,11 @@ static struct {
{"I;16B", "I;16B", 16, copy2},
{"I;16L", "I;16L", 16, copy2},
- {"I;16", "I;16N", 16, unpackI16N_I16}, // LibTiff native->image endian.
- {"I;16L", "I;16N", 16, unpackI16N_I16}, // LibTiff native->image endian.
- {"I;16B", "I;16N", 16, unpackI16N_I16B},
+ {"I;16", "I;16N", 16, unpackI16N_I16}, // LibTiff native->image endian.
+ {"I;16L", "I;16N", 16, unpackI16N_I16}, // LibTiff native->image endian.
+ {"I;16B", "I;16N", 16, unpackI16N_I16B},
- {"I;16", "I;12", 12, unpackI12_I16}, // 12 bit Tiffs stored in 16bits.
+ {"I;16", "I;12", 12, unpackI12_I16}, // 12 bit Tiffs stored in 16bits.
{NULL} /* sentinel */
};
@@ -1521,13 +1523,15 @@ ImagingFindUnpacker(const char* mode, const char* rawmode, int* bits_out)
int i;
/* find a suitable pixel unpacker */
- for (i = 0; unpackers[i].rawmode; i++)
+ for (i = 0; unpackers[i].rawmode; i++) {
if (strcmp(unpackers[i].mode, mode) == 0 &&
strcmp(unpackers[i].rawmode, rawmode) == 0) {
- if (bits_out)
+ if (bits_out) {
*bits_out = unpackers[i].bits;
+ }
return unpackers[i].unpack;
}
+ }
/* FIXME: configure a general unpacker based on the type codes... */
diff --git a/src/libImaging/UnpackYCC.c b/src/libImaging/UnpackYCC.c
index 19da1f654..d6bce17ad 100644
--- a/src/libImaging/UnpackYCC.c
+++ b/src/libImaging/UnpackYCC.c
@@ -5,7 +5,7 @@
* code to convert and unpack PhotoYCC data
*
* history:
- * 97-01-25 fl Moved from PcdDecode.c
+ * 97-01-25 fl Moved from PcdDecode.c
*
* Copyright (c) Fredrik Lundh 1996-97.
* Copyright (c) Secret Labs AB 1997.
@@ -116,12 +116,12 @@ static INT16 GR[] = { 127, 126, 125, 124, 123, 122, 121, 121, 120, 119,
-85, -86, -87, -88, -89, -90, -91, -92, -93, -94, -94, -95, -96, -97,
-98, -99, -100, -101, -102, -103, -104, -105, -106, -107, -107, -108 };
-#define R 0
-#define G 1
-#define B 2
-#define A 3
+#define R 0
+#define G 1
+#define B 2
+#define A 3
-#define YCC2RGB(rgb, y, cb, cr) {\
+#define YCC2RGB(rgb, y, cb, cr) {\
int l = L[y];\
int r = l + CR[cr];\
int g = l + GR[cr] + GB[cb];\
@@ -137,9 +137,9 @@ ImagingUnpackYCC(UINT8* out, const UINT8* in, int pixels)
int i;
/* PhotoYCC triplets */
for (i = 0; i < pixels; i++) {
- YCC2RGB(out, in[0], in[1], in[2]);
- out[A] = 255;
- out += 4; in += 3;
+ YCC2RGB(out, in[0], in[1], in[2]);
+ out[A] = 255;
+ out += 4; in += 3;
}
}
@@ -149,14 +149,14 @@ ImagingUnpackYCCA(UINT8* out, const UINT8* in, int pixels)
int i;
/* PhotoYCC triplets plus premultiplied alpha */
for (i = 0; i < pixels; i++) {
- /* Divide by alpha */
- UINT8 rgb[3];
- rgb[0] = (in[3] == 0) ? 0 : (((int) in[0] * 255) / in[3]);
- rgb[1] = (in[3] == 0) ? 0 : (((int) in[1] * 255) / in[3]);
- rgb[2] = (in[3] == 0) ? 0 : (((int) in[2] * 255) / in[3]);
- /* Convert non-multiplied data to RGB */
- YCC2RGB(out, rgb[0], rgb[1], rgb[2]);
- out[A] = in[3];
- out += 4; in += 4;
+ /* Divide by alpha */
+ UINT8 rgb[3];
+ rgb[0] = (in[3] == 0) ? 0 : (((int) in[0] * 255) / in[3]);
+ rgb[1] = (in[3] == 0) ? 0 : (((int) in[1] * 255) / in[3]);
+ rgb[2] = (in[3] == 0) ? 0 : (((int) in[2] * 255) / in[3]);
+ /* Convert non-multiplied data to RGB */
+ YCC2RGB(out, rgb[0], rgb[1], rgb[2]);
+ out[A] = in[3];
+ out += 4; in += 4;
}
}
diff --git a/src/libImaging/UnsharpMask.c b/src/libImaging/UnsharpMask.c
index a034bebf2..59e595e82 100644
--- a/src/libImaging/UnsharpMask.c
+++ b/src/libImaging/UnsharpMask.c
@@ -14,10 +14,12 @@ typedef UINT8 pixel[4];
static inline UINT8 clip8(int in)
{
- if (in >= 255)
+ if (in >= 255) {
return 255;
- if (in <= 0)
+ }
+ if (in <= 0) {
return 0;
+ }
return (UINT8) in;
}
@@ -39,8 +41,9 @@ ImagingUnsharpMask(Imaging imOut, Imaging imIn, float radius, int percent,
/* First, do a gaussian blur on the image, putting results in imOut
temporarily. All format checks are in gaussian blur. */
result = ImagingGaussianBlur(imOut, imIn, radius, 3);
- if (!result)
+ if (!result) {
return NULL;
+ }
/* Now, go through each pixel, compare "normal" pixel to blurred
pixel. If the difference is more than threshold values, apply
diff --git a/src/libImaging/XbmDecode.c b/src/libImaging/XbmDecode.c
index 75b4961ab..607f1058a 100644
--- a/src/libImaging/XbmDecode.c
+++ b/src/libImaging/XbmDecode.c
@@ -5,7 +5,7 @@
* decoder for XBM hex image data
*
* history:
- * 96-04-13 fl Created
+ * 96-04-13 fl Created
*
* Copyright (c) Fredrik Lundh 1996.
* Copyright (c) Secret Labs AB 1997.
@@ -16,9 +16,9 @@
#include "Imaging.h"
-#define HEX(v) ((v >= '0' && v <= '9') ? v - '0' :\
- (v >= 'a' && v <= 'f') ? v - 'a' + 10 :\
- (v >= 'A' && v <= 'F') ? v - 'A' + 10 : 0)
+#define HEX(v) ((v >= '0' && v <= '9') ? v - '0' :\
+ (v >= 'a' && v <= 'f') ? v - 'a' + 10 :\
+ (v >= 'A' && v <= 'F') ? v - 'A' + 10 : 0)
int
ImagingXbmDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes)
@@ -27,54 +27,58 @@ ImagingXbmDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt
UINT8* ptr;
- if (!state->state)
- state->state = SKIP;
+ if (!state->state) {
+ state->state = SKIP;
+ }
ptr = buf;
for (;;) {
- if (state->state == SKIP) {
+ if (state->state == SKIP) {
- /* Skip forward until next 'x' */
+ /* Skip forward until next 'x' */
- while (bytes > 0) {
- if (*ptr == 'x')
- break;
- ptr++;
- bytes--;
- }
+ while (bytes > 0) {
+ if (*ptr == 'x') {
+ break;
+ }
+ ptr++;
+ bytes--;
+ }
- if (bytes == 0)
- return ptr - buf;
+ if (bytes == 0) {
+ return ptr - buf;
+ }
- state->state = BYTE;
+ state->state = BYTE;
- }
+ }
- if (bytes < 3)
- return ptr - buf;
+ if (bytes < 3) {
+ return ptr - buf;
+ }
- state->buffer[state->x] = (HEX(ptr[1])<<4) + HEX(ptr[2]);
+ state->buffer[state->x] = (HEX(ptr[1])<<4) + HEX(ptr[2]);
- if (++state->x >= state->bytes) {
+ if (++state->x >= state->bytes) {
- /* Got a full line, unpack it */
- state->shuffle((UINT8*) im->image[state->y], state->buffer,
- state->xsize);
+ /* Got a full line, unpack it */
+ state->shuffle((UINT8*) im->image[state->y], state->buffer,
+ state->xsize);
- state->x = 0;
+ state->x = 0;
- if (++state->y >= state->ysize) {
- /* End of file (errcode = 0) */
- return -1;
- }
- }
+ if (++state->y >= state->ysize) {
+ /* End of file (errcode = 0) */
+ return -1;
+ }
+ }
- ptr += 3;
- bytes -= 3;
+ ptr += 3;
+ bytes -= 3;
- state->state = SKIP;
+ state->state = SKIP;
}
diff --git a/src/libImaging/XbmEncode.c b/src/libImaging/XbmEncode.c
index e066fd6b5..d1bc086db 100644
--- a/src/libImaging/XbmEncode.c
+++ b/src/libImaging/XbmEncode.c
@@ -5,7 +5,7 @@
* encoder for Xbm data
*
* history:
- * 96-11-01 fl created
+ * 96-11-01 fl created
*
* Copyright (c) Fredrik Lundh 1996.
* Copyright (c) Secret Labs AB 1997.
@@ -27,79 +27,80 @@ ImagingXbmEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
if (!state->state) {
- /* 8 pixels are stored in no more than 6 bytes */
- state->bytes = 6*(state->xsize+7)/8;
+ /* 8 pixels are stored in no more than 6 bytes */
+ state->bytes = 6*(state->xsize+7)/8;
- state->state = 1;
+ state->state = 1;
}
if (bytes < state->bytes) {
- state->errcode = IMAGING_CODEC_MEMORY;
- return 0;
+ state->errcode = IMAGING_CODEC_MEMORY;
+ return 0;
}
ptr = buf;
while (bytes >= state->bytes) {
- state->shuffle(state->buffer,
- (UINT8*) im->image[state->y + state->yoff] +
- state->xoff * im->pixelsize, state->xsize);
+ state->shuffle(state->buffer,
+ (UINT8*) im->image[state->y + state->yoff] +
+ state->xoff * im->pixelsize, state->xsize);
- if (state->y < state->ysize-1) {
+ if (state->y < state->ysize-1) {
- /* any line but the last */
- for (n = 0; n < state->xsize; n += 8) {
+ /* any line but the last */
+ for (n = 0; n < state->xsize; n += 8) {
- i = state->buffer[n/8];
+ i = state->buffer[n/8];
- *ptr++ = '0';
- *ptr++ = 'x';
- *ptr++ = hex[(i>>4)&15];
- *ptr++ = hex[i&15];
- *ptr++ = ',';
- bytes -= 5;
+ *ptr++ = '0';
+ *ptr++ = 'x';
+ *ptr++ = hex[(i>>4)&15];
+ *ptr++ = hex[i&15];
+ *ptr++ = ',';
+ bytes -= 5;
- if (++state->count >= 79/5) {
- *ptr++ = '\n';
- bytes--;
- state->count = 0;
- }
+ if (++state->count >= 79/5) {
+ *ptr++ = '\n';
+ bytes--;
+ state->count = 0;
+ }
- }
+ }
- state->y++;
+ state->y++;
- } else {
+ } else {
- /* last line */
- for (n = 0; n < state->xsize; n += 8) {
+ /* last line */
+ for (n = 0; n < state->xsize; n += 8) {
- i = state->buffer[n/8];
+ i = state->buffer[n/8];
- *ptr++ = '0';
- *ptr++ = 'x';
- *ptr++ = hex[(i>>4)&15];
- *ptr++ = hex[i&15];
+ *ptr++ = '0';
+ *ptr++ = 'x';
+ *ptr++ = hex[(i>>4)&15];
+ *ptr++ = hex[i&15];
- if (n < state->xsize-8) {
- *ptr++ = ',';
- if (++state->count >= 79/5) {
- *ptr++ = '\n';
- bytes--;
- state->count = 0;
- }
- } else
- *ptr++ = '\n';
+ if (n < state->xsize-8) {
+ *ptr++ = ',';
+ if (++state->count >= 79/5) {
+ *ptr++ = '\n';
+ bytes--;
+ state->count = 0;
+ }
+ } else {
+ *ptr++ = '\n';
+ }
- bytes -= 5;
+ bytes -= 5;
- }
+ }
- state->errcode = IMAGING_CODEC_END;
- break;
- }
+ state->errcode = IMAGING_CODEC_END;
+ break;
+ }
}
return ptr - buf;
diff --git a/src/libImaging/Zip.h b/src/libImaging/Zip.h
index 21a336f90..b05c93bb4 100644
--- a/src/libImaging/Zip.h
+++ b/src/libImaging/Zip.h
@@ -12,10 +12,10 @@
/* modes */
-#define ZIP_PNG 0 /* continuous, filtered image data */
-#define ZIP_PNG_PALETTE 1 /* non-continuous data, disable filtering */
-#define ZIP_TIFF_PREDICTOR 2 /* TIFF, with predictor */
-#define ZIP_TIFF 3 /* TIFF, without predictor */
+#define ZIP_PNG 0 /* continuous, filtered image data */
+#define ZIP_PNG_PALETTE 1 /* non-continuous data, disable filtering */
+#define ZIP_TIFF_PREDICTOR 2 /* TIFF, with predictor */
+#define ZIP_TIFF 3 /* TIFF, without predictor */
typedef struct {
@@ -39,24 +39,24 @@ typedef struct {
/* PRIVATE CONTEXT (set by decoder/encoder) */
- z_stream z_stream; /* (de)compression stream */
+ z_stream z_stream; /* (de)compression stream */
- UINT8* previous; /* previous line (allocated) */
+ UINT8* previous; /* previous line (allocated) */
- int last_output; /* # bytes last output by inflate */
+ int last_output; /* # bytes last output by inflate */
/* Compressor specific stuff */
- UINT8* prior; /* filter storage (allocated) */
+ UINT8* prior; /* filter storage (allocated) */
UINT8* up;
UINT8* average;
UINT8* paeth;
- UINT8* output; /* output data */
+ UINT8* output; /* output data */
- int prefix; /* size of filter prefix (0 for TIFF data) */
+ int prefix; /* size of filter prefix (0 for TIFF data) */
- int interlaced; /* is the image interlaced? (PNG) */
+ int interlaced; /* is the image interlaced? (PNG) */
- int pass; /* current pass of the interlaced image (PNG) */
+ int pass; /* current pass of the interlaced image (PNG) */
} ZIPSTATE;
diff --git a/src/libImaging/ZipDecode.c b/src/libImaging/ZipDecode.c
index 43601c38e..b0f8ad326 100644
--- a/src/libImaging/ZipDecode.c
+++ b/src/libImaging/ZipDecode.c
@@ -53,8 +53,9 @@ ImagingZipDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt
if (!state->state) {
/* Initialization */
- if (context->mode == ZIP_PNG || context->mode == ZIP_PNG_PALETTE)
+ if (context->mode == ZIP_PNG || context->mode == ZIP_PNG_PALETTE) {
context->prefix = 1; /* PNG */
+ }
/* overflow check for malloc */
if (state->bytes > INT_MAX - 1) {
@@ -121,12 +122,13 @@ ImagingZipDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt
if (err < 0) {
/* Something went wrong inside the compression library */
- if (err == Z_DATA_ERROR)
+ if (err == Z_DATA_ERROR) {
state->errcode = IMAGING_CODEC_BROKEN;
- else if (err == Z_MEM_ERROR)
+ } else if (err == Z_MEM_ERROR) {
state->errcode = IMAGING_CODEC_MEMORY;
- else
+ } else {
state->errcode = IMAGING_CODEC_CONFIG;
+ }
free(context->previous);
context->previous = NULL;
inflateEnd(&context->z_stream);
@@ -149,28 +151,33 @@ ImagingZipDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt
case 1:
/* prior */
bpp = (state->bits + 7) / 8;
- for (i = bpp+1; i <= row_len; i++)
+ for (i = bpp+1; i <= row_len; i++) {
state->buffer[i] += state->buffer[i-bpp];
+ }
break;
case 2:
/* up */
- for (i = 1; i <= row_len; i++)
+ for (i = 1; i <= row_len; i++) {
state->buffer[i] += context->previous[i];
+ }
break;
case 3:
/* average */
bpp = (state->bits + 7) / 8;
- for (i = 1; i <= bpp; i++)
+ for (i = 1; i <= bpp; i++) {
state->buffer[i] += context->previous[i]/2;
- for (; i <= row_len; i++)
+ }
+ for (; i <= row_len; i++) {
state->buffer[i] +=
(state->buffer[i-bpp] + context->previous[i])/2;
+ }
break;
case 4:
/* paeth filtering */
bpp = (state->bits + 7) / 8;
- for (i = 1; i <= bpp; i++)
+ for (i = 1; i <= bpp; i++) {
state->buffer[i] += context->previous[i];
+ }
for (; i <= row_len; i++) {
int a, b, c;
int pa, pb, pc;
@@ -201,8 +208,9 @@ ImagingZipDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt
break;
case ZIP_TIFF_PREDICTOR:
bpp = (state->bits + 7) / 8;
- for (i = bpp+1; i <= row_len; i++)
+ for (i = bpp+1; i <= row_len; i++) {
state->buffer[i] += state->buffer[i-bpp];
+ }
break;
}
diff --git a/src/libImaging/ZipEncode.c b/src/libImaging/ZipEncode.c
index fa1c4e728..0b4435678 100644
--- a/src/libImaging/ZipEncode.c
+++ b/src/libImaging/ZipEncode.c
@@ -128,12 +128,13 @@ ImagingZipEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
if (err < 0) {
/* Something went wrong inside the compression library */
- if (err == Z_DATA_ERROR)
+ if (err == Z_DATA_ERROR) {
state->errcode = IMAGING_CODEC_BROKEN;
- else if (err == Z_MEM_ERROR)
+ } else if (err == Z_MEM_ERROR) {
state->errcode = IMAGING_CODEC_MEMORY;
- else
+ } else {
state->errcode = IMAGING_CODEC_CONFIG;
+ }
free(context->paeth);
free(context->average);
free(context->up);
@@ -282,12 +283,13 @@ ImagingZipEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
if (err < 0) {
/* Something went wrong inside the compression library */
- if (err == Z_DATA_ERROR)
+ if (err == Z_DATA_ERROR) {
state->errcode = IMAGING_CODEC_BROKEN;
- else if (err == Z_MEM_ERROR)
+ } else if (err == Z_MEM_ERROR) {
state->errcode = IMAGING_CODEC_MEMORY;
- else
+ } else {
state->errcode = IMAGING_CODEC_CONFIG;
+ }
free(context->paeth);
free(context->average);
free(context->up);
@@ -305,8 +307,9 @@ ImagingZipEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
}
- if (context->z_stream.avail_out == 0)
+ if (context->z_stream.avail_out == 0) {
break; /* Buffer full */
+ }
case 2:
@@ -331,8 +334,9 @@ ImagingZipEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)
break;
}
- if (context->z_stream.avail_out == 0)
+ if (context->z_stream.avail_out == 0) {
break; /* Buffer full */
+ }
}
diff --git a/src/map.c b/src/map.c
index 54e0fdb22..ef29062cc 100644
--- a/src/map.c
+++ b/src/map.c
@@ -47,12 +47,14 @@ PyImaging_MapperNew(const char* filename, int readonly)
{
ImagingMapperObject *mapper;
- if (PyType_Ready(&ImagingMapperType) < 0)
+ if (PyType_Ready(&ImagingMapperType) < 0) {
return NULL;
+ }
mapper = PyObject_New(ImagingMapperObject, &ImagingMapperType);
- if (mapper == NULL)
+ if (mapper == NULL) {
return NULL;
+ }
mapper->base = NULL;
mapper->size = mapper->offset = 0;
@@ -70,7 +72,7 @@ PyImaging_MapperNew(const char* filename, int readonly)
FILE_ATTRIBUTE_NORMAL,
NULL);
if (mapper->hFile == (HANDLE)-1) {
- PyErr_SetString(PyExc_IOError, "cannot open file");
+ PyErr_SetString(PyExc_OSError, "cannot open file");
Py_DECREF(mapper);
return NULL;
}
@@ -81,7 +83,7 @@ PyImaging_MapperNew(const char* filename, int readonly)
0, 0, NULL);
if (mapper->hMap == (HANDLE)-1) {
CloseHandle(mapper->hFile);
- PyErr_SetString(PyExc_IOError, "cannot map file");
+ PyErr_SetString(PyExc_OSError, "cannot map file");
Py_DECREF(mapper);
return NULL;
}
@@ -101,12 +103,15 @@ static void
mapping_dealloc(ImagingMapperObject* mapper)
{
#ifdef _WIN32
- if (mapper->base != 0)
+ if (mapper->base != 0) {
UnmapViewOfFile(mapper->base);
- if (mapper->hMap != (HANDLE)-1)
+ }
+ if (mapper->hMap != (HANDLE)-1) {
CloseHandle(mapper->hMap);
- if (mapper->hFile != (HANDLE)-1)
+ }
+ if (mapper->hFile != (HANDLE)-1) {
CloseHandle(mapper->hFile);
+ }
mapper->base = 0;
mapper->hMap = mapper->hFile = (HANDLE)-1;
#endif
@@ -122,18 +127,22 @@ mapping_read(ImagingMapperObject* mapper, PyObject* args)
PyObject* buf;
int size = -1;
- if (!PyArg_ParseTuple(args, "|i", &size))
+ if (!PyArg_ParseTuple(args, "|i", &size)) {
return NULL;
+ }
/* check size */
- if (size < 0 || mapper->offset + size > mapper->size)
+ if (size < 0 || mapper->offset + size > mapper->size) {
size = mapper->size - mapper->offset;
- if (size < 0)
+ }
+ if (size < 0) {
size = 0;
+ }
buf = PyBytes_FromStringAndSize(NULL, size);
- if (!buf)
+ if (!buf) {
return NULL;
+ }
if (size > 0) {
memcpy(PyBytes_AsString(buf), mapper->base + mapper->offset, size);
@@ -148,8 +157,9 @@ mapping_seek(ImagingMapperObject* mapper, PyObject* args)
{
int offset;
int whence = 0;
- if (!PyArg_ParseTuple(args, "i|i", &offset, &whence))
+ if (!PyArg_ParseTuple(args, "i|i", &offset, &whence)) {
return NULL;
+ }
switch (whence) {
case 0: /* SEEK_SET */
@@ -193,37 +203,43 @@ mapping_readimage(ImagingMapperObject* mapper, PyObject* args)
int stride;
int orientation;
if (!PyArg_ParseTuple(args, "s(ii)ii", &mode, &xsize, &ysize,
- &stride, &orientation))
+ &stride, &orientation)) {
return NULL;
+ }
if (stride <= 0) {
/* FIXME: maybe we should call ImagingNewPrologue instead */
- if (!strcmp(mode, "L") || !strcmp(mode, "P"))
+ if (!strcmp(mode, "L") || !strcmp(mode, "P")) {
stride = xsize;
- else if (!strcmp(mode, "I;16") || !strcmp(mode, "I;16B"))
+ } else if (!strcmp(mode, "I;16") || !strcmp(mode, "I;16B")) {
stride = xsize * 2;
- else
+ } else {
stride = xsize * 4;
+ }
}
size = ysize * stride;
if (mapper->offset + size > mapper->size) {
- PyErr_SetString(PyExc_IOError, "image file truncated");
+ PyErr_SetString(PyExc_OSError, "image file truncated");
return NULL;
}
im = ImagingNewPrologue(mode, xsize, ysize);
- if (!im)
+ if (!im) {
return NULL;
+ }
/* setup file pointers */
- if (orientation > 0)
- for (y = 0; y < ysize; y++)
+ if (orientation > 0) {
+ for (y = 0; y < ysize; y++) {
im->image[y] = mapper->base + mapper->offset + y * stride;
- else
- for (y = 0; y < ysize; y++)
+ }
+ } else {
+ for (y = 0; y < ysize; y++) {
im->image[ysize-y-1] = mapper->base + mapper->offset + y * stride;
+ }
+ }
im->destroy = ImagingDestroyMap;
@@ -279,8 +295,9 @@ PyObject*
PyImaging_Mapper(PyObject* self, PyObject* args)
{
char* filename;
- if (!PyArg_ParseTuple(args, "s", &filename))
+ if (!PyArg_ParseTuple(args, "s", &filename)) {
return NULL;
+ }
return (PyObject*) PyImaging_MapperNew(filename, 1);
}
@@ -319,8 +336,9 @@ PyImaging_MapBuffer(PyObject* self, PyObject* args)
int ystep;
if (!PyArg_ParseTuple(args, "O(ii)sn(sii)", &target, &xsize, &ysize,
- &codec, &offset, &mode, &stride, &ystep))
+ &codec, &offset, &mode, &stride, &ystep)) {
return NULL;
+ }
if (!PyImaging_CheckBuffer(target)) {
PyErr_SetString(PyExc_TypeError, "expected string or buffer");
@@ -328,12 +346,13 @@ PyImaging_MapBuffer(PyObject* self, PyObject* args)
}
if (stride <= 0) {
- if (!strcmp(mode, "L") || !strcmp(mode, "P"))
+ if (!strcmp(mode, "L") || !strcmp(mode, "P")) {
stride = xsize;
- else if (!strncmp(mode, "I;16", 4))
+ } else if (!strncmp(mode, "I;16", 4)) {
stride = xsize * 2;
- else
+ } else {
stride = xsize * 4;
+ }
}
if (stride > 0 && ysize > PY_SSIZE_T_MAX / stride) {
@@ -349,8 +368,9 @@ PyImaging_MapBuffer(PyObject* self, PyObject* args)
}
/* check buffer size */
- if (PyImaging_GetBuffer(target, &view) < 0)
+ if (PyImaging_GetBuffer(target, &view) < 0) {
return NULL;
+ }
if (view.len < 0) {
PyErr_SetString(PyExc_ValueError, "buffer has negative size");
@@ -371,12 +391,15 @@ PyImaging_MapBuffer(PyObject* self, PyObject* args)
}
/* setup file pointers */
- if (ystep > 0)
- for (y = 0; y < ysize; y++)
+ if (ystep > 0) {
+ for (y = 0; y < ysize; y++) {
im->image[y] = (char*)view.buf + offset + y * stride;
- else
- for (y = 0; y < ysize; y++)
+ }
+ } else {
+ for (y = 0; y < ysize; y++) {
im->image[ysize-y-1] = (char*)view.buf + offset + y * stride;
+ }
+ }
im->destroy = mapping_destroy_buffer;
diff --git a/src/outline.c b/src/outline.c
index 25e63aeaf..d082febaa 100644
--- a/src/outline.c
+++ b/src/outline.c
@@ -23,7 +23,7 @@
/* -------------------------------------------------------------------- */
-/* Class */
+/* Class */
typedef struct {
PyObject_HEAD
@@ -39,12 +39,14 @@ _outline_new(void)
{
OutlineObject *self;
- if (PyType_Ready(&OutlineType) < 0)
+ if (PyType_Ready(&OutlineType) < 0) {
return NULL;
+ }
self = PyObject_New(OutlineObject, &OutlineType);
- if (self == NULL)
- return NULL;
+ if (self == NULL) {
+ return NULL;
+ }
self->outline = ImagingOutlineNew();
@@ -61,35 +63,38 @@ _outline_dealloc(OutlineObject* self)
ImagingOutline
PyOutline_AsOutline(PyObject* outline)
{
- if (PyOutline_Check(outline))
+ if (PyOutline_Check(outline)) {
return ((OutlineObject*) outline)->outline;
+ }
return NULL;
}
/* -------------------------------------------------------------------- */
-/* Factories */
+/* Factories */
PyObject*
PyOutline_Create(PyObject* self, PyObject* args)
{
- if (!PyArg_ParseTuple(args, ":outline"))
+ if (!PyArg_ParseTuple(args, ":outline")) {
return NULL;
+ }
return (PyObject*) _outline_new();
}
/* -------------------------------------------------------------------- */
-/* Methods */
+/* Methods */
static PyObject*
_outline_move(OutlineObject* self, PyObject* args)
{
float x0, y0;
- if (!PyArg_ParseTuple(args, "ff", &x0, &y0))
- return NULL;
+ if (!PyArg_ParseTuple(args, "ff", &x0, &y0)) {
+ return NULL;
+ }
ImagingOutlineMove(self->outline, x0, y0);
@@ -101,8 +106,9 @@ static PyObject*
_outline_line(OutlineObject* self, PyObject* args)
{
float x1, y1;
- if (!PyArg_ParseTuple(args, "ff", &x1, &y1))
- return NULL;
+ if (!PyArg_ParseTuple(args, "ff", &x1, &y1)) {
+ return NULL;
+ }
ImagingOutlineLine(self->outline, x1, y1);
@@ -114,8 +120,9 @@ static PyObject*
_outline_curve(OutlineObject* self, PyObject* args)
{
float x1, y1, x2, y2, x3, y3;
- if (!PyArg_ParseTuple(args, "ffffff", &x1, &y1, &x2, &y2, &x3, &y3))
- return NULL;
+ if (!PyArg_ParseTuple(args, "ffffff", &x1, &y1, &x2, &y2, &x3, &y3)) {
+ return NULL;
+ }
ImagingOutlineCurve(self->outline, x1, y1, x2, y2, x3, y3);
@@ -126,8 +133,9 @@ _outline_curve(OutlineObject* self, PyObject* args)
static PyObject*
_outline_close(OutlineObject* self, PyObject* args)
{
- if (!PyArg_ParseTuple(args, ":close"))
+ if (!PyArg_ParseTuple(args, ":close")) {
return NULL;
+ }
ImagingOutlineClose(self->outline);
@@ -139,8 +147,9 @@ static PyObject*
_outline_transform(OutlineObject* self, PyObject* args)
{
double a[6];
- if (!PyArg_ParseTuple(args, "(dddddd)", a+0, a+1, a+2, a+3, a+4, a+5))
+ if (!PyArg_ParseTuple(args, "(dddddd)", a+0, a+1, a+2, a+3, a+4, a+5)) {
return NULL;
+ }
ImagingOutlineTransform(self->outline, a);
@@ -158,35 +167,35 @@ static struct PyMethodDef _outline_methods[] = {
};
static PyTypeObject OutlineType = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "Outline", /*tp_name*/
- sizeof(OutlineObject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)_outline_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number */
- 0, /*tp_as_sequence */
- 0, /*tp_as_mapping */
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- _outline_methods, /*tp_methods*/
- 0, /*tp_members*/
- 0, /*tp_getset*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "Outline", /*tp_name*/
+ sizeof(OutlineObject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)_outline_dealloc,/*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number */
+ 0, /*tp_as_sequence */
+ 0, /*tp_as_mapping */
+ 0, /*tp_hash*/
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ _outline_methods, /*tp_methods*/
+ 0, /*tp_members*/
+ 0, /*tp_getset*/
};
diff --git a/src/path.c b/src/path.c
index f69755d16..3cbdd5d44 100644
--- a/src/path.c
+++ b/src/path.c
@@ -61,8 +61,9 @@ alloc_array(Py_ssize_t count)
return NULL;
}
xy = malloc(2 * count * sizeof(double) + 1);
- if (!xy)
+ if (!xy) {
PyErr_NoMemory();
+ }
return xy;
}
@@ -74,8 +75,9 @@ path_new(Py_ssize_t count, double* xy, int duplicate)
if (duplicate) {
/* duplicate path */
double* p = alloc_array(count);
- if (!p)
+ if (!p) {
return NULL;
+ }
memcpy(p, xy, count * 2 * sizeof(double));
xy = p;
}
@@ -120,8 +122,9 @@ PyPath_Flatten(PyObject* data, double **pxy)
/* This was another path object. */
PyPathObject *path = (PyPathObject*) data;
xy = alloc_array(path->count);
- if (!xy)
+ if (!xy) {
return -1;
+ }
memcpy(xy, path->xy, 2 * path->count * sizeof(double));
*pxy = xy;
return path->count;
@@ -134,10 +137,12 @@ PyPath_Flatten(PyObject* data, double **pxy)
float *ptr = (float*) buffer.buf;
n = buffer.len / (2 * sizeof(float));
xy = alloc_array(n);
- if (!xy)
+ if (!xy) {
return -1;
- for (i = 0; i < n+n; i++)
+ }
+ for (i = 0; i < n+n; i++) {
xy[i] = ptr[i];
+ }
*pxy = xy;
PyBuffer_Release(&buffer);
return n;
@@ -153,26 +158,28 @@ PyPath_Flatten(PyObject* data, double **pxy)
j = 0;
n = PyObject_Length(data);
/* Just in case __len__ breaks (or doesn't exist) */
- if (PyErr_Occurred())
+ if (PyErr_Occurred()) {
return -1;
+ }
/* Allocate for worst case */
xy = alloc_array(n);
- if (!xy)
+ if (!xy) {
return -1;
+ }
/* Copy table to path array */
if (PyList_Check(data)) {
for (i = 0; i < n; i++) {
double x, y;
PyObject *op = PyList_GET_ITEM(data, i);
- if (PyFloat_Check(op))
+ if (PyFloat_Check(op)) {
xy[j++] = PyFloat_AS_DOUBLE(op);
- else if (PyLong_Check(op))
+ } else if (PyLong_Check(op)) {
xy[j++] = (float) PyLong_AS_LONG(op);
- else if (PyNumber_Check(op))
+ } else if (PyNumber_Check(op)) {
xy[j++] = PyFloat_AsDouble(op);
- else if (PyArg_ParseTuple(op, "dd", &x, &y)) {
+ } else if (PyArg_ParseTuple(op, "dd", &x, &y)) {
xy[j++] = x;
xy[j++] = y;
} else {
@@ -184,13 +191,13 @@ PyPath_Flatten(PyObject* data, double **pxy)
for (i = 0; i < n; i++) {
double x, y;
PyObject *op = PyTuple_GET_ITEM(data, i);
- if (PyFloat_Check(op))
+ if (PyFloat_Check(op)) {
xy[j++] = PyFloat_AS_DOUBLE(op);
- else if (PyLong_Check(op))
+ } else if (PyLong_Check(op)) {
xy[j++] = (float) PyLong_AS_LONG(op);
- else if (PyNumber_Check(op))
+ } else if (PyNumber_Check(op)) {
xy[j++] = PyFloat_AsDouble(op);
- else if (PyArg_ParseTuple(op, "dd", &x, &y)) {
+ } else if (PyArg_ParseTuple(op, "dd", &x, &y)) {
xy[j++] = x;
xy[j++] = y;
} else {
@@ -213,13 +220,13 @@ PyPath_Flatten(PyObject* data, double **pxy)
return -1;
}
}
- if (PyFloat_Check(op))
+ if (PyFloat_Check(op)) {
xy[j++] = PyFloat_AS_DOUBLE(op);
- else if (PyLong_Check(op))
+ } else if (PyLong_Check(op)) {
xy[j++] = (float) PyLong_AS_LONG(op);
- else if (PyNumber_Check(op))
+ } else if (PyNumber_Check(op)) {
xy[j++] = PyFloat_AsDouble(op);
- else if (PyArg_ParseTuple(op, "dd", &x, &y)) {
+ } else if (PyArg_ParseTuple(op, "dd", &x, &y)) {
xy[j++] = x;
xy[j++] = y;
} else {
@@ -257,19 +264,22 @@ PyPath_Create(PyObject* self, PyObject* args)
/* number of vertices */
xy = alloc_array(count);
- if (!xy)
+ if (!xy) {
return NULL;
+ }
} else {
/* sequence or other path */
PyErr_Clear();
- if (!PyArg_ParseTuple(args, "O", &data))
+ if (!PyArg_ParseTuple(args, "O", &data)) {
return NULL;
+ }
count = PyPath_Flatten(data, &xy);
- if (count < 0)
+ if (count < 0) {
return NULL;
+ }
}
return (PyObject*) path_new(count, xy, 0);
@@ -291,8 +301,9 @@ path_compact(PyPathObject* self, PyObject* args)
double cityblock = 2.0;
- if (!PyArg_ParseTuple(args, "|d:compact", &cityblock))
+ if (!PyArg_ParseTuple(args, "|d:compact", &cityblock)) {
return NULL;
+ }
xy = self->xy;
@@ -323,8 +334,9 @@ path_getbbox(PyPathObject* self, PyObject* args)
double *xy;
double x0, y0, x1, y1;
- if (!PyArg_ParseTuple(args, ":getbbox"))
+ if (!PyArg_ParseTuple(args, ":getbbox")) {
return NULL;
+ }
xy = self->xy;
@@ -332,14 +344,18 @@ path_getbbox(PyPathObject* self, PyObject* args)
y0 = y1 = xy[1];
for (i = 1; i < self->count; i++) {
- if (xy[i+i] < x0)
+ if (xy[i+i] < x0) {
x0 = xy[i+i];
- if (xy[i+i] > x1)
+ }
+ if (xy[i+i] > x1) {
x1 = xy[i+i];
- if (xy[i+i+1] < y0)
+ }
+ if (xy[i+i+1] < y0) {
y0 = xy[i+i+1];
- if (xy[i+i+1] > y1)
+ }
+ if (xy[i+i+1] > y1) {
y1 = xy[i+i+1];
+ }
}
return Py_BuildValue("dddd", x0, y0, x1, y1);
@@ -348,8 +364,9 @@ path_getbbox(PyPathObject* self, PyObject* args)
static PyObject*
path_getitem(PyPathObject* self, Py_ssize_t i)
{
- if (i < 0)
+ if (i < 0) {
i = self->count + i;
+ }
if (i < 0 || i >= self->count) {
PyErr_SetString(PyExc_IndexError, "path index out of range");
return NULL;
@@ -362,16 +379,19 @@ static PyObject*
path_getslice(PyPathObject* self, Py_ssize_t ilow, Py_ssize_t ihigh)
{
/* adjust arguments */
- if (ilow < 0)
+ if (ilow < 0) {
ilow = 0;
- else if (ilow >= self->count)
+ } else if (ilow >= self->count) {
ilow = self->count;
- if (ihigh < 0)
+ }
+ if (ihigh < 0) {
ihigh = 0;
- if (ihigh < ilow)
+ }
+ if (ihigh < ilow) {
ihigh = ilow;
- else if (ihigh > self->count)
+ } else if (ihigh > self->count) {
ihigh = self->count;
+ }
return (PyObject*) path_new(ihigh - ilow, self->xy + ilow * 2, 1);
}
@@ -390,8 +410,9 @@ path_map(PyPathObject* self, PyObject* args)
double *xy;
PyObject* function;
- if (!PyArg_ParseTuple(args, "O:map", &function))
+ if (!PyArg_ParseTuple(args, "O:map", &function)) {
return NULL;
+ }
xy = self->xy;
@@ -432,8 +453,9 @@ path_setitem(PyPathObject* self, Py_ssize_t i, PyObject* op)
xy = &self->xy[i+i];
- if (!PyArg_ParseTuple(op, "dd", &xy[0], &xy[1]))
+ if (!PyArg_ParseTuple(op, "dd", &xy[0], &xy[1])) {
return -1;
+ }
return 0;
}
@@ -445,16 +467,18 @@ path_tolist(PyPathObject* self, PyObject* args)
Py_ssize_t i;
int flat = 0;
- if (!PyArg_ParseTuple(args, "|i:tolist", &flat))
+ if (!PyArg_ParseTuple(args, "|i:tolist", &flat)) {
return NULL;
+ }
if (flat) {
list = PyList_New(self->count*2);
for (i = 0; i < self->count*2; i++) {
PyObject* item;
item = PyFloat_FromDouble(self->xy[i]);
- if (!item)
+ if (!item) {
goto error;
+ }
PyList_SetItem(list, i, item);
}
} else {
@@ -462,8 +486,9 @@ path_tolist(PyPathObject* self, PyObject* args)
for (i = 0; i < self->count; i++) {
PyObject* item;
item = Py_BuildValue("dd", self->xy[i+i], self->xy[i+i+1]);
- if (!item)
+ if (!item) {
goto error;
+ }
PyList_SetItem(list, i, item);
}
}
@@ -487,19 +512,20 @@ path_transform(PyPathObject* self, PyObject* args)
if (!PyArg_ParseTuple(args, "(dddddd)|d:transform",
&a, &b, &c, &d, &e, &f,
- &wrap))
+ &wrap)) {
return NULL;
+ }
xy = self->xy;
/* transform the coordinate set */
- if (b == 0.0 && d == 0.0)
+ if (b == 0.0 && d == 0.0) {
/* scaling */
for (i = 0; i < self->count; i++) {
xy[i+i] = a*xy[i+i]+c;
xy[i+i+1] = e*xy[i+i+1]+f;
}
- else
+ } else {
/* affine transform */
for (i = 0; i < self->count; i++) {
double x = xy[i+i];
@@ -507,11 +533,14 @@ path_transform(PyPathObject* self, PyObject* args)
xy[i+i] = a*x+b*y+c;
xy[i+i+1] = d*x+e*y+f;
}
+ }
/* special treatment of geographical map data */
- if (wrap != 0.0)
- for (i = 0; i < self->count; i++)
+ if (wrap != 0.0) {
+ for (i = 0; i < self->count; i++) {
xy[i+i] = fmod(xy[i+i], wrap);
+ }
+ }
Py_INCREF(Py_None);
return Py_None;
@@ -542,16 +571,18 @@ path_subscript(PyPathObject* self, PyObject* item) {
if (PyIndex_Check(item)) {
Py_ssize_t i;
i = PyNumber_AsSsize_t(item, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred())
+ if (i == -1 && PyErr_Occurred()) {
return NULL;
+ }
return path_getitem(self, i);
}
if (PySlice_Check(item)) {
int len = 4;
Py_ssize_t start, stop, step, slicelength;
- if (PySlice_GetIndicesEx(item, len, &start, &stop, &step, &slicelength) < 0)
+ if (PySlice_GetIndicesEx(item, len, &start, &stop, &step, &slicelength) < 0) {
return NULL;
+ }
if (slicelength <= 0) {
double *xy = alloc_array(0);
diff --git a/winbuild/README.md b/winbuild/README.md
index 471b61a57..d46361c9e 100644
--- a/winbuild/README.md
+++ b/winbuild/README.md
@@ -1,18 +1,30 @@
-Quick README
-------------
-
-For more extensive info, see the [Windows build instructions](build.rst).
-
-* See https://github.com/python-pillow/Pillow/issues/553#issuecomment-37877416 and https://github.com/matplotlib/matplotlib/issues/1717#issuecomment-13343859
-
-* Works best with Python 3.4, due to virtualenv and pip batteries included. Python3+ required for fetch command.
-* Check config.py for virtual env paths, suffix for 64-bit releases. Defaults to `x64`, set `X64_EXT` to change.
-* When running in CI with one Python per invocation, set the `PYTHON` env variable to the Python folder. (e.g. `PYTHON`=`c:\Python27\`) This overrides the matrix in config.py and will just build and test for the specific Python.
-* `python get_pythons.py` downloads all the Python releases, and their signatures. (Manually) Install in `c:\PythonXX[x64]\`.
-* `python build_dep.py` downloads and creates a build script for all the dependencies, in 32 and 64-bit versions, and with both compiler versions.
-* (in powershell) `build_deps.cmd` invokes the dependency build.
-* `python build.py --clean` makes Pillow for the matrix of Pythons.
-* `python test.py` runs the tests on Pillow in all the virtual envs.
-* Currently working with zlib, libjpeg, freetype, and libtiff on Python 2.7, and 3.4, both 32 and 64-bit, on a local win7 pro machine and appveyor.com
-* WebP is built, not detected.
-* LCMS, OpenJPEG and libimagequant are not building.
+Quick README
+------------
+
+For more extensive info, see the [Windows build instructions](build.rst).
+
+* See [Current Windows Build/Testing process (Pillow#553)](https://github.com/python-pillow/Pillow/issues/553#issuecomment-37877416),
+ [Definitive docs for how to compile on Windows (matplotlib#1717)](https://github.com/matplotlib/matplotlib/issues/1717#issuecomment-13343859),
+ [Test Windows with GitHub Actions (Pillow#4084)](https://github.com/python-pillow/Pillow/pull/4084).
+
+
+* Requires Microsoft Visual Studio 2017 or newer with C++ component.
+* Requires NASM for libjpeg-turbo, a required dependency when using this script.
+* Requires CMake 3.12 or newer (available as Visual Studio component).
+* Python 3.6+ is required to generate valid scripts, but builds targeting Python 3.5+ are supported.
+* Tested on Windows Server 2016 with Visual Studio 2017 Community (AppVeyor).
+* Tested on Windows Server 2019 with Visual Studio 2019 Enterprise (GitHub Actions).
+
+The following is a simplified version of the script used on AppVeyor:
+```
+set PYTHON=C:\Python35\bin
+cd /D C:\Pillow\winbuild
+C:\Python37\bin\python.exe build_prepare.py -v --depends=C:\pillow-depends
+build\build_dep_all.cmd
+build\build_pillow.cmd install
+cd ..
+path C:\Pillow\winbuild\build\bin;%PATH%
+%PYTHON%\python.exe selftest.py
+%PYTHON%\python.exe -m pytest -vx --cov PIL --cov Tests --cov-report term --cov-report xml Tests
+build\build_pillow.cmd bdist_wheel
+```
diff --git a/winbuild/appveyor_install_pypy3.cmd b/winbuild/appveyor_install_pypy3.cmd
deleted file mode 100644
index 75a22ca59..000000000
--- a/winbuild/appveyor_install_pypy3.cmd
+++ /dev/null
@@ -1,3 +0,0 @@
-curl -fsSL -o pypy3.zip https://bitbucket.org/pypy/pypy/downloads/pypy3.6-v7.3.0-win32.zip
-7z x pypy3.zip -oc:\
-c:\Python37\Scripts\virtualenv.exe -p c:\pypy3.6-v7.3.0-win32\pypy3.exe c:\vp\pypy3
diff --git a/winbuild/build.py b/winbuild/build.py
deleted file mode 100755
index e565226bd..000000000
--- a/winbuild/build.py
+++ /dev/null
@@ -1,205 +0,0 @@
-#!/usr/bin/env python3
-
-import getopt
-import os
-import shutil
-import subprocess
-import sys
-
-from config import (
- VIRT_BASE,
- X64_EXT,
- bit_from_env,
- compiler_from_env,
- compilers,
- pythons,
- pyversion_from_env,
-)
-
-
-def setup_vms():
- ret = []
- for py in pythons:
- for arch in ("", X64_EXT):
- ret.append(
- "virtualenv -p c:/Python%s%s/python.exe --clear %s%s%s"
- % (py, arch, VIRT_BASE, py, arch)
- )
- ret.append(
- r"%s%s%s\Scripts\pip.exe install pytest pytest-cov"
- % (VIRT_BASE, py, arch)
- )
- return "\n".join(ret)
-
-
-def run_script(params):
- (version, script) = params
- try:
- print("Running %s" % version)
- filename = "build_pillow_%s.cmd" % version
- with open(filename, "w") as f:
- f.write(script)
-
- command = ["powershell", "./%s" % filename]
- proc = subprocess.Popen(
- command,
- stdin=subprocess.PIPE,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- )
- (trace, stderr) = proc.communicate()
- status = proc.returncode
- print("-- stderr --")
- print(stderr.decode())
- print("-- stdout --")
- print(trace.decode())
- print("Done with {}: {}".format(version, status))
- return (version, status, trace, stderr)
- except Exception as msg:
- print("Error with {}: {}".format(version, str(msg)))
- return (version, -1, "", str(msg))
-
-
-def header(op):
- return r"""
-setlocal
-set MPLSRC=%%~dp0\..
-set INCLIB=%%~dp0\depends
-set BLDOPT=%s
-cd /D %%MPLSRC%%
-""" % (
- op
- )
-
-
-def footer():
- return """endlocal
-exit
-"""
-
-
-def vc_setup(compiler, bit):
- script = ""
- if compiler["vc_version"] == "2015":
- arch = "x86" if bit == 32 else "x86_amd64"
- script = (
- r"""
-call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" %s
-echo on"""
- % arch
- )
- return script
-
-
-def build_one(py_ver, compiler, bit):
- # UNDONE virtual envs if we're not running on AppVeyor
- args = {}
- args.update(compiler)
- if "PYTHON" in os.environ:
- args["python_path"] = "%PYTHON%"
- else:
- args["python_path"] = "{}{}\\Scripts".format(VIRT_BASE, py_ver)
-
- args["executable"] = "python.exe"
- if "EXECUTABLE" in os.environ:
- args["executable"] = "%EXECUTABLE%"
-
- args["py_ver"] = py_ver
- args["tcl_ver"] = "86"
-
- if compiler["vc_version"] == "2015":
- args["imaging_libs"] = " build_ext --add-imaging-libs=msvcrt"
- else:
- args["imaging_libs"] = ""
-
- args["vc_setup"] = vc_setup(compiler, bit)
-
- script = r"""
-setlocal EnableDelayedExpansion
-call "%%ProgramFiles%%\Microsoft SDKs\Windows\%(env_version)s\Bin\SetEnv.Cmd" /Release %(env_flags)s
-set DISTUTILS_USE_SDK=1
-set LIB=%%LIB%%;%%INCLIB%%\%(inc_dir)s
-set INCLUDE=%%INCLUDE%%;%%INCLIB%%\%(inc_dir)s;%%INCLIB%%\tcl%(tcl_ver)s\include
-
-setlocal
-set LIB=%%LIB%%;C:\Python%(py_ver)s\tcl%(vc_setup)s
-call %(python_path)s\%(executable)s setup.py %(imaging_libs)s %%BLDOPT%%
-call %(python_path)s\%(executable)s -c "from PIL import _webp;import os, shutil;shutil.copy(r'%%INCLIB%%\freetype.dll', os.path.dirname(_webp.__file__));"
-endlocal
-
-endlocal
-""" # noqa: E501
- return script % args
-
-
-def clean():
- try:
- shutil.rmtree("../build")
- except Exception:
- # could already be removed
- pass
- run_script(("virtualenvs", setup_vms()))
-
-
-def main(op):
- scripts = []
-
- for py_version, py_info in pythons.items():
- py_compilers = compilers[py_info["compiler"]][py_info["vc"]]
- scripts.append(
- (
- py_version,
- "\n".join(
- [header(op), build_one(py_version, py_compilers[32], 32), footer()]
- ),
- )
- )
-
- scripts.append(
- (
- "{}{}".format(py_version, X64_EXT),
- "\n".join(
- [
- header(op),
- build_one("%sx64" % py_version, py_compilers[64], 64),
- footer(),
- ]
- ),
- )
- )
-
- results = map(run_script, scripts)
-
- for (version, status, trace, err) in results:
- print("Compiled {}: {}".format(version, status and "ERR" or "OK"))
-
-
-def run_one(op):
-
- compiler = compiler_from_env()
- py_version = pyversion_from_env()
- bit = bit_from_env()
-
- run_script(
- (
- py_version,
- "\n".join([header(op), build_one(py_version, compiler, bit), footer()]),
- )
- )
-
-
-if __name__ == "__main__":
- opts, args = getopt.getopt(sys.argv[1:], "", ["clean", "wheel"])
- opts = dict(opts)
-
- if "--clean" in opts:
- clean()
-
- op = "install"
- if "--wheel" in opts:
- op = "bdist_wheel"
-
- if "PYTHON" in os.environ:
- run_one(op)
- else:
- main(op)
diff --git a/winbuild/build.rst b/winbuild/build.rst
index 1d2084044..517843a66 100644
--- a/winbuild/build.rst
+++ b/winbuild/build.rst
@@ -5,89 +5,112 @@ Building Pillow on Windows
<../docs/installation.rst#windows-installation>`_ should
be sufficient.
-This page will describe a build setup to build Pillow against the
-supported Python versions in 32 and 64-bit modes, using freely
-available Microsoft compilers. This has been developed and tested
-against 64-bit Windows 7 Professional and Windows Server 2012
-64-bit version on Amazon EC2.
+This page describes the steps necessary to build Pillow using the same
+scripts used on GitHub Actions and AppVeyor CIs.
Prerequisites
-------------
-Extra Build Helpers
-^^^^^^^^^^^^^^^^^^^
-* Powershell (available by default on Windows Server)
-* GitHub client (provides git+bash shell)
-
-Optional:
-* GPG (for checking signatures) (UNDONE -- Python signature checking)
-
-
-Pythons
-^^^^^^^
-
-The build routines expect Python to be installed at C:\PythonXX for
-32-bit versions or C:\PythonXXx64 for the 64-bit versions.
-
-Download Python 3.4, install it, and add it to the path. This is the
-Python that we will use to bootstrap the build process. (The download
-routines are using 3 features, and installing 3.4 gives us pip and
-virtualenv as well, reducing the number of packages that we need to
-install.)
-
-Download the rest of the Pythons by opening a command window, changing
-to the ``winbuild`` directory, and running ``python
-get_pythons.py``.
-
-UNDONE -- gpg verify the signatures (note that we can download from
-https)
-
-Run each installer and set the proper path to the installation. Don't
-set any of them as the default Python, or add them to the path.
+Python
+^^^^^^
+While the scripts can target any version of Python supported by Pillow,
+Python 3.6+ is required to generate valid build scripts.
Compilers
^^^^^^^^^
Download and install:
-* `Microsoft Windows SDK for Windows 7 and .NET Framework
- 4 `_
+* `Microsoft Visual Studio 2017 or newer or Build Tools for Visual Studio 2017 or newer
+ `_
+ (MSVC C++ build tools, and any Windows SDK version required)
-* `CMake-2.8.10.2-win32-x86.exe
- `_
+* `CMake 3.12 or newer `_
+ (also available as Visual Studio component C++ CMake tools for Windows)
-The samples and the .NET SDK portions aren't required, just the
-compilers and other tools. UNDONE -- check exact wording.
+* `NASM `_
+
+Any version of Visual Studio 2017 or newer should be supported,
+including Visual Studio 2017 Community, or Build Tools for Visual Studio 2019.
+
+Paths to CMake (if standalone) and NASM must be added to the ``PATH`` environment variable.
+Visual Studio is found automatically with ``vswhere.exe``.
+
+Build configuration
+-------------------
+
+The following environment variables, if set, will override the default
+behaviour of ``build_prepare.py``:
+
+* ``PYTHON`` + ``EXECUTABLE`` point to the target version of Python.
+ If ``PYTHON`` is unset, the version of Python used to run
+ ``build_prepare.py`` will be used. If only ``PYTHON`` is set,
+ ``EXECUTABLE`` defaults to ``python.exe``.
+* ``ARCHITECTURE`` is used to select a ``x86`` or ``x64`` build. By default,
+ uses same architecture as the version of Python used to run ``build_prepare.py``.
+ is used.
+* ``PILLOW_BUILD`` can be used to override the ``winbuild\build`` directory
+ path, used to store generated build scripts and compiled libraries.
+ **Warning:** This directory is wiped when ``build_prepare.py`` is run.
+* ``PILLOW_DEPS`` points to the directory used to store downloaded
+ dependencies. By default ``winbuild\depends`` is used.
+
+``build_prepare.py`` also supports the following command line parameters:
+
+* ``-v`` will print generated scripts.
+* ``--no-imagequant`` will skip GPL-licensed ``libimagequant`` optional dependency
+* ``--no-raqm`` will skip optional dependency Raqm (which itself depends on
+ LGPL-licensed ``fribidi``).
+* ``--python=`` and ``--executable=`` override ``PYTHON`` and ``EXECUTABLE``.
+* ``--architecture=`` overrides ``ARCHITECTURE``.
+* ``--dir=`` and ``--depends=`` override ``PILLOW_BUILD``
+ and ``PILLOW_DEPS``.
Dependencies
------------
-The script 'build_dep.py' downloads and builds the dependencies. Open
-a command window, change directory into ``winbuild`` and run ``python
-build_dep.py``.
+Dependencies will be automatically downloaded by ``build_prepare.py``.
+By default, downloaded dependencies are stored in ``winbuild\depends``;
+set the ``PILLOW_DEPS`` environment variable to override this location.
-This will download libjpeg, libtiff, libz, and freetype. It will then
-compile 32 and 64-bit versions of the libraries, with both versions of
-the compilers.
-
-UNDONE -- lcms fails.
-UNDONE -- webp, jpeg2k not recognized
+To build all dependencies, run ``winbuild\build\build_dep_all.cmd``,
+or run the individual scripts to build each dependency separately.
Building Pillow
---------------
-Once the dependencies are built, run ``python build.py --clean`` to
-build and install Pillow in virtualenvs for each Python
-build. ``build.py --wheel`` will build wheels instead of
-installing into virtualenvs.
-
-UNDONE -- suppressed output, what about failures.
+Once the dependencies are built, run
+``winbuild\build\build_pillow.cmd install`` to build and install
+Pillow for the selected version of Python.
+``winbuild\build\build_pillow.cmd bdist_wheel`` will build wheels
+instead of installing Pillow.
Testing Pillow
--------------
-Build and install Pillow, then run ``python test.py`` from the
-``winbuild`` directory.
+Some binary dependencies (e.g. ``libraqm.dll``) will be stored in the
+``winbuild\build\bin`` directory; this directory should be added to ``PATH``
+before running tests.
+Build and install Pillow, then run ``python -m pytest Tests``
+from the root Pillow directory.
+
+Example
+-------
+
+The following is a simplified version of the script used on AppVeyor:
+
+.. code-block::
+
+ set PYTHON=C:\Python35\bin
+ cd /D C:\Pillow\winbuild
+ C:\Python37\bin\python.exe build_prepare.py -v --depends=C:\pillow-depends
+ build\build_dep_all.cmd
+ build\build_pillow.cmd install
+ cd ..
+ path C:\Pillow\winbuild\build\bin;%PATH%
+ %PYTHON%\python.exe selftest.py
+ %PYTHON%\python.exe -m pytest -vx --cov PIL --cov Tests --cov-report term --cov-report xml Tests
+ build\build_pillow.cmd bdist_wheel
diff --git a/winbuild/build_dep.py b/winbuild/build_dep.py
deleted file mode 100644
index 778570139..000000000
--- a/winbuild/build_dep.py
+++ /dev/null
@@ -1,328 +0,0 @@
-import os
-
-from build import vc_setup
-from config import all_compilers, bit_from_env, compiler_from_env, compilers, libs
-from fetch import fetch
-from untar import untar
-from unzip import unzip
-
-
-def _relpath(*args):
- return os.path.join(os.getcwd(), *args)
-
-
-build_dir = _relpath("build")
-inc_dir = _relpath("depends")
-
-
-def check_sig(filename, signame):
- # UNDONE -- need gpg
- return filename
-
-
-def mkdirs():
- try:
- os.mkdir(build_dir)
- except OSError:
- pass
- try:
- os.mkdir(inc_dir)
- except OSError:
- pass
- for compiler in all_compilers():
- try:
- os.mkdir(os.path.join(inc_dir, compiler["inc_dir"]))
- except OSError:
- pass
-
-
-def extract(src, dest):
- if ".zip" in src:
- return unzip(src, dest)
- if ".tar.gz" in src or ".tgz" in src:
- return untar(src, dest)
-
-
-def extract_libs():
- for name, lib in libs.items():
- filename = fetch(lib["url"])
- if name == "openjpeg":
- for compiler in all_compilers():
- if not os.path.exists(
- os.path.join(build_dir, lib["dir"] + compiler["inc_dir"])
- ):
- extract(filename, build_dir)
- os.rename(
- os.path.join(build_dir, lib["dir"]),
- os.path.join(build_dir, lib["dir"] + compiler["inc_dir"]),
- )
- else:
- extract(filename, build_dir)
-
-
-def extract_openjpeg(compiler):
- return (
- r"""
-rem build openjpeg
-setlocal
-cd %%BUILD%%
-mkdir %%INCLIB%%\openjpeg-2.0
-copy /Y /B openjpeg-2.0.0-win32-x86\include\openjpeg-2.0 %%INCLIB%%\openjpeg-2.0
-copy /Y /B openjpeg-2.0.0-win32-x86\bin\ %%INCLIB%%
-copy /Y /B openjpeg-2.0.0-win32-x86\lib\ %%INCLIB%%
-endlocal
-"""
- % compiler
- )
-
-
-def cp_tk(ver_85, ver_86):
- versions = {"ver_85": ver_85, "ver_86": ver_86}
- return (
- r"""
-mkdir %%INCLIB%%\tcl85\include\X11
-copy /Y /B %%BUILD%%\tcl%(ver_85)s\generic\*.h %%INCLIB%%\tcl85\include\
-copy /Y /B %%BUILD%%\tk%(ver_85)s\generic\*.h %%INCLIB%%\tcl85\include\
-copy /Y /B %%BUILD%%\tk%(ver_85)s\xlib\X11\* %%INCLIB%%\tcl85\include\X11\
-
-mkdir %%INCLIB%%\tcl86\include\X11
-copy /Y /B %%BUILD%%\tcl%(ver_86)s\generic\*.h %%INCLIB%%\tcl86\include\
-copy /Y /B %%BUILD%%\tk%(ver_86)s\generic\*.h %%INCLIB%%\tcl86\include\
-copy /Y /B %%BUILD%%\tk%(ver_86)s\xlib\X11\* %%INCLIB%%\tcl86\include\X11\
-"""
- % versions
- )
-
-
-def header():
- return r"""setlocal
-set MSBUILD=C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe
-set CMAKE="cmake.exe"
-set INCLIB=%~dp0\depends
-set BUILD=%~dp0\build
-""" + "\n".join(
- r"set {}=%BUILD%\{}".format(k.upper(), v["dir"])
- for (k, v) in libs.items()
- if v["dir"]
- )
-
-
-def setup_compiler(compiler):
- return (
- r"""setlocal EnableDelayedExpansion
-call "%%ProgramFiles%%\Microsoft SDKs\Windows\%(env_version)s\Bin\SetEnv.Cmd" /Release %(env_flags)s
-echo on
-set INCLIB=%%INCLIB%%\%(inc_dir)s
-""" # noqa: E501
- % compiler
- )
-
-
-def end_compiler():
- return """
-endlocal
-"""
-
-
-def nmake_openjpeg(compiler, bit):
- if compiler["env_version"] == "v7.0":
- return ""
-
- atts = {"op_ver": "2.3.1"}
- atts.update(compiler)
- return (
- r"""
-rem build openjpeg
-setlocal
-"""
- + vc_setup(compiler, bit)
- + r"""
-cd /D %%OPENJPEG%%%(inc_dir)s
-
-%%CMAKE%% -DBUILD_THIRDPARTY:BOOL=OFF -DBUILD_SHARED_LIBS:BOOL=OFF -DCMAKE_BUILD_TYPE=Release -G "NMake Makefiles" .
-nmake -nologo -f Makefile clean
-nmake -nologo -f Makefile
-copy /Y /B bin\* %%INCLIB%%
-mkdir %%INCLIB%%\openjpeg-%(op_ver)s
-copy /Y /B src\lib\openjp2\*.h %%INCLIB%%\openjpeg-%(op_ver)s
-endlocal
-""" # noqa: E501
- % atts
- )
-
-
-def nmake_libs(compiler, bit):
- # undone -- pre, makes, headers, libs
- script = (
- r"""
-rem Build libjpeg
-setlocal
-"""
- + vc_setup(compiler, bit)
- + r"""
-cd /D %%JPEG%%
-nmake -nologo -f makefile.vc setup-vc6
-nmake -nologo -f makefile.vc clean
-nmake -nologo -f makefile.vc nodebug=1 libjpeg.lib
-copy /Y /B *.dll %%INCLIB%%
-copy /Y /B *.lib %%INCLIB%%
-copy /Y /B j*.h %%INCLIB%%
-endlocal
-
-rem Build zlib
-setlocal
-cd /D %%ZLIB%%
-nmake -nologo -f win32\Makefile.msc clean
-nmake -nologo -f win32\Makefile.msc zlib.lib
-copy /Y /B *.dll %%INCLIB%%
-copy /Y /B *.lib %%INCLIB%%
-copy /Y /B zlib.lib %%INCLIB%%\z.lib
-copy /Y /B zlib.h %%INCLIB%%
-copy /Y /B zconf.h %%INCLIB%%
-endlocal
-
-rem Build webp
-setlocal
-"""
- + vc_setup(compiler, bit)
- + r"""
-cd /D %%WEBP%%
-rd /S /Q %%WEBP%%\output\release-static
-nmake -nologo -f Makefile.vc CFG=release-static RTLIBCFG=static OBJDIR=output all
-copy /Y /B output\release-static\%(webp_platform)s\lib\* %%INCLIB%%
-mkdir %%INCLIB%%\webp
-copy /Y /B src\webp\*.h %%INCLIB%%\\webp
-endlocal
-
-rem Build libtiff
-setlocal
-"""
- + vc_setup(compiler, bit)
- + r"""
-rem do after building jpeg and zlib
-copy %%~dp0\tiff.opt %%TIFF%%\nmake.opt
-
-cd /D %%TIFF%%
-nmake -nologo -f makefile.vc clean
-nmake -nologo -f makefile.vc lib
-copy /Y /B libtiff\*.dll %%INCLIB%%
-copy /Y /B libtiff\*.lib %%INCLIB%%
-copy /Y /B libtiff\tiff*.h %%INCLIB%%
-endlocal
-"""
- )
- return script % compiler
-
-
-def msbuild_freetype(compiler, bit):
- script = r"""
-rem Build freetype
-setlocal
-rd /S /Q %%FREETYPE%%\objs
-set DefaultPlatformToolset=v100
-"""
- properties = r"""/p:Configuration="Release" /p:Platform=%(platform)s"""
- if bit == 64:
- script += (
- r"copy /Y /B "
- r'"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Lib\x64\*.Lib" '
- r"%%FREETYPE%%\builds\windows\vc2010"
- )
- properties += r" /p:_IsNativeEnvironment=false"
- script += (
- r"""
-%%MSBUILD%% %%FREETYPE%%\builds\windows\vc2010\freetype.sln /t:Clean;Build """
- + properties
- + r""" /m
-xcopy /Y /E /Q %%FREETYPE%%\include %%INCLIB%%
-"""
- )
- freetypeReleaseDir = r"%%FREETYPE%%\objs\%(platform)s\Release"
- script += (
- r"""
-copy /Y /B """
- + freetypeReleaseDir
- + r"""\freetype.lib %%INCLIB%%\freetype.lib
-copy /Y /B """
- + freetypeReleaseDir
- + r"""\freetype.dll %%INCLIB%%\..\freetype.dll
-endlocal
-"""
- )
- return script % compiler
-
-
-def build_lcms2(compiler):
- if compiler["env_version"] == "v7.1":
- return build_lcms_71(compiler)
- return build_lcms_70(compiler)
-
-
-def build_lcms_70(compiler):
- """Link error here on x64"""
- if compiler["platform"] == "x64":
- return ""
-
- """Build LCMS on VC2008. This version is only 32bit/Win32"""
- return (
- r"""
-rem Build lcms2
-setlocal
-set LCMS=%%LCMS-2.7%%
-rd /S /Q %%LCMS%%\Lib
-rd /S /Q %%LCMS%%\Projects\VC%(vc_version)s\Release
-%%MSBUILD%% %%LCMS%%\Projects\VC%(vc_version)s\lcms2.sln /t:Clean /p:Configuration="Release" /p:Platform=Win32 /m
-%%MSBUILD%% %%LCMS%%\Projects\VC%(vc_version)s\lcms2.sln /t:lcms2_static /p:Configuration="Release" /p:Platform=Win32 /p:PlatformToolset=v90 /m
-xcopy /Y /E /Q %%LCMS%%\include %%INCLIB%%
-copy /Y /B %%LCMS%%\Lib\MS\*.lib %%INCLIB%%
-endlocal
-""" # noqa: E501
- % compiler
- )
-
-
-def build_lcms_71(compiler):
- return (
- r"""
-rem Build lcms2
-setlocal
-set LCMS=%%LCMS-2.8%%
-rd /S /Q %%LCMS%%\Lib
-rd /S /Q %%LCMS%%\Projects\VC%(vc_version)s\Release
-powershell -Command "(gc Projects\VC2015\lcms2_static\lcms2_static.vcxproj) -replace 'MultiThreadedDLL', 'MultiThreaded' | Out-File -encoding ASCII Projects\VC2015\lcms2_static\lcms2_static.vcxproj"
-%%MSBUILD%% %%LCMS%%\Projects\VC%(vc_version)s\lcms2.sln /t:Clean /p:Configuration="Release" /p:Platform=%(platform)s /m
-%%MSBUILD%% %%LCMS%%\Projects\VC%(vc_version)s\lcms2.sln /t:lcms2_static /p:Configuration="Release" /p:Platform=%(platform)s /m
-xcopy /Y /E /Q %%LCMS%%\include %%INCLIB%%
-copy /Y /B %%LCMS%%\Lib\MS\*.lib %%INCLIB%%
-endlocal
-""" # noqa: E501
- % compiler
- )
-
-
-def add_compiler(compiler, bit):
- script.append(setup_compiler(compiler))
- script.append(nmake_libs(compiler, bit))
-
- # script.append(extract_openjpeg(compiler))
-
- script.append(msbuild_freetype(compiler, bit))
- script.append(build_lcms2(compiler))
- script.append(nmake_openjpeg(compiler, bit))
- script.append(end_compiler())
-
-
-mkdirs()
-extract_libs()
-script = [header(), cp_tk(libs["tk-8.5"]["version"], libs["tk-8.6"]["version"])]
-
-
-if "PYTHON" in os.environ:
- add_compiler(compiler_from_env(), bit_from_env())
-else:
- # for compiler in all_compilers():
- # add_compiler(compiler)
- add_compiler(compilers[7.0][2010][32], 32)
-
-with open("build_deps.cmd", "w") as f:
- f.write("\n".join(script))
diff --git a/winbuild/build_prepare.py b/winbuild/build_prepare.py
new file mode 100644
index 000000000..0ba8a135c
--- /dev/null
+++ b/winbuild/build_prepare.py
@@ -0,0 +1,557 @@
+import os
+import shutil
+import struct
+import subprocess
+import sys
+
+
+def cmd_cd(path):
+ return "cd /D {path}".format(**locals())
+
+
+def cmd_set(name, value):
+ return "set {name}={value}".format(**locals())
+
+
+def cmd_append(name, value):
+ op = "path " if name == "PATH" else "set {name}="
+ return (op + "%{name}%;{value}").format(**locals())
+
+
+def cmd_copy(src, tgt):
+ return 'copy /Y /B "{src}" "{tgt}"'.format(**locals())
+
+
+def cmd_xcopy(src, tgt):
+ return 'xcopy /Y /E "{src}" "{tgt}"'.format(**locals())
+
+
+def cmd_mkdir(path):
+ return 'mkdir "{path}"'.format(**locals())
+
+
+def cmd_rmdir(path):
+ return 'rmdir /S /Q "{path}"'.format(**locals())
+
+
+def cmd_nmake(makefile=None, target="", params=None):
+ if params is None:
+ params = ""
+ elif isinstance(params, list) or isinstance(params, tuple):
+ params = " ".join(params)
+ else:
+ params = str(params)
+
+ return " ".join(
+ [
+ "{{nmake}}",
+ "-nologo",
+ '-f "{makefile}"' if makefile is not None else "",
+ "{params}",
+ '"{target}"',
+ ]
+ ).format(**locals())
+
+
+def cmd_cmake(params=None, file="."):
+ if params is None:
+ params = ""
+ elif isinstance(params, list) or isinstance(params, tuple):
+ params = " ".join(params)
+ else:
+ params = str(params)
+ return " ".join(
+ [
+ "{{cmake}}",
+ "-DCMAKE_VERBOSE_MAKEFILE=ON",
+ "-DCMAKE_RULE_MESSAGES:BOOL=OFF",
+ "-DCMAKE_BUILD_TYPE=Release",
+ "{params}",
+ '-G "NMake Makefiles"',
+ '"{file}"',
+ ]
+ ).format(**locals())
+
+
+def cmd_msbuild(
+ file, configuration="Release", target="Build", platform="{msbuild_arch}"
+):
+ return " ".join(
+ [
+ "{{msbuild}}",
+ "{file}",
+ '/t:"{target}"',
+ '/p:Configuration="{configuration}"',
+ "/p:Platform={platform}",
+ "/m",
+ ]
+ ).format(**locals())
+
+
+SF_MIRROR = "http://iweb.dl.sourceforge.net"
+
+architectures = {
+ "x86": {"vcvars_arch": "x86", "msbuild_arch": "Win32"},
+ "x64": {"vcvars_arch": "x86_amd64", "msbuild_arch": "x64"},
+}
+
+header = [
+ cmd_set("INCLUDE", "{inc_dir}"),
+ cmd_set("INCLIB", "{lib_dir}"),
+ cmd_set("LIB", "{lib_dir}"),
+ cmd_append("PATH", "{bin_dir}"),
+]
+
+# dependencies, listed in order of compilation
+deps = {
+ "libjpeg": {
+ "url": SF_MIRROR + "/project/libjpeg-turbo/2.0.3/libjpeg-turbo-2.0.3.tar.gz",
+ "filename": "libjpeg-turbo-2.0.3.tar.gz",
+ "dir": "libjpeg-turbo-2.0.3",
+ "build": [
+ cmd_cmake(
+ [
+ "-DENABLE_SHARED:BOOL=FALSE",
+ "-DWITH_JPEG8:BOOL=TRUE",
+ "-DWITH_CRT_DLL:BOOL=TRUE",
+ ]
+ ),
+ cmd_nmake(target="clean"),
+ cmd_nmake(target="jpeg-static"),
+ cmd_copy("jpeg-static.lib", "libjpeg.lib"),
+ cmd_nmake(target="cjpeg-static"),
+ cmd_copy("cjpeg-static.exe", "cjpeg.exe"),
+ cmd_nmake(target="djpeg-static"),
+ cmd_copy("djpeg-static.exe", "djpeg.exe"),
+ ],
+ "headers": ["j*.h"],
+ "libs": ["libjpeg.lib"],
+ "bins": ["cjpeg.exe", "djpeg.exe"],
+ },
+ "zlib": {
+ "url": "http://zlib.net/zlib1211.zip",
+ "filename": "zlib1211.zip",
+ "dir": "zlib-1.2.11",
+ "build": [
+ cmd_nmake(r"win32\Makefile.msc", "clean"),
+ cmd_nmake(r"win32\Makefile.msc", "zlib.lib"),
+ cmd_copy("zlib.lib", "z.lib"),
+ ],
+ "headers": [r"z*.h"],
+ "libs": [r"*.lib"],
+ },
+ "libtiff": {
+ "url": "https://download.osgeo.org/libtiff/tiff-4.1.0.tar.gz",
+ "filename": "tiff-4.1.0.tar.gz",
+ "dir": "tiff-4.1.0",
+ "build": [
+ cmd_copy(r"{winbuild_dir}\tiff.opt", "nmake.opt"),
+ cmd_nmake("makefile.vc", "clean"),
+ cmd_nmake("makefile.vc", "lib"),
+ ],
+ "headers": [r"libtiff\tiff*.h"],
+ "libs": [r"libtiff\*.lib"],
+ # "bins": [r"libtiff\*.dll"],
+ },
+ "libwebp": {
+ "url": "http://downloads.webmproject.org/releases/webp/libwebp-1.1.0.tar.gz",
+ "filename": "libwebp-1.1.0.tar.gz",
+ "dir": "libwebp-1.1.0",
+ "build": [
+ cmd_rmdir(r"output\release-static"), # clean
+ cmd_nmake(
+ "Makefile.vc",
+ "all",
+ ["CFG=release-static", "OBJDIR=output", "ARCH={architecture}"],
+ ),
+ cmd_mkdir(r"{inc_dir}\webp"),
+ cmd_copy(r"src\webp\*.h", r"{inc_dir}\webp"),
+ ],
+ "libs": [r"output\release-static\{architecture}\lib\*.lib"],
+ },
+ "freetype": {
+ "url": "https://download.savannah.gnu.org/releases/freetype/freetype-2.10.2.tar.gz", # noqa: E501
+ "filename": "freetype-2.10.2.tar.gz",
+ "dir": "freetype-2.10.2",
+ "patch": {
+ r"builds\windows\vc2010\freetype.vcxproj": {
+ # freetype setting is /MD for .dll and /MT for .lib, we need /MD
+ "MultiThreaded": "MultiThreadedDLL", # noqa: E501
+ # freetype doesn't specify SDK version, MSBuild may guess incorrectly
+ '': '\n $(WindowsSDKVersion)', # noqa: E501
+ }
+ },
+ "build": [
+ cmd_rmdir("objs"),
+ cmd_msbuild(
+ r"builds\windows\vc2010\freetype.sln", "Release Static", "Clean"
+ ),
+ cmd_msbuild(
+ r"builds\windows\vc2010\freetype.sln", "Release Static", "Build"
+ ),
+ cmd_xcopy("include", "{inc_dir}"),
+ ],
+ "libs": [r"objs\{msbuild_arch}\Release Static\freetype.lib"],
+ # "bins": [r"objs\{msbuild_arch}\Release\freetype.dll"],
+ },
+ "lcms2": {
+ "url": SF_MIRROR + "/project/lcms/lcms/2.10/lcms2-2.10.tar.gz",
+ "filename": "lcms2-2.10.tar.gz",
+ "dir": "lcms2-2.10",
+ "patch": {
+ r"Projects\VC2017\lcms2_static\lcms2_static.vcxproj": {
+ # default is /MD for x86 and /MT for x64, we need /MD always
+ "MultiThreaded": "MultiThreadedDLL", # noqa: E501
+ # retarget to default toolset (selected by vcvarsall.bat)
+ "v141": "$(DefaultPlatformToolset)", # noqa: E501
+ # retarget to latest (selected by vcvarsall.bat)
+ "8.1": "$(WindowsSDKVersion)", # noqa: E501
+ }
+ },
+ "build": [
+ cmd_rmdir("Lib"),
+ cmd_rmdir(r"Projects\VC2017\Release"),
+ cmd_msbuild(r"Projects\VC2017\lcms2.sln", "Release", "Clean"),
+ cmd_msbuild(r"Projects\VC2017\lcms2.sln", "Release", "lcms2_static"),
+ cmd_xcopy("include", "{inc_dir}"),
+ ],
+ "libs": [r"Lib\MS\*.lib"],
+ },
+ "openjpeg": {
+ "url": "https://github.com/uclouvain/openjpeg/archive/v2.3.1.tar.gz",
+ "filename": "openjpeg-2.3.1.tar.gz",
+ "dir": "openjpeg-2.3.1",
+ "build": [
+ cmd_cmake(("-DBUILD_THIRDPARTY:BOOL=OFF", "-DBUILD_SHARED_LIBS:BOOL=OFF")),
+ cmd_nmake(target="clean"),
+ cmd_nmake(target="openjp2"),
+ cmd_mkdir(r"{inc_dir}\openjpeg-2.3.1"),
+ cmd_copy(r"src\lib\openjp2\*.h", r"{inc_dir}\openjpeg-2.3.1"),
+ ],
+ "libs": [r"bin\*.lib"],
+ },
+ "libimagequant": {
+ # e5d454b: Merge tag '2.12.6' into msvc
+ "url": "https://github.com/ImageOptim/libimagequant/archive/e5d454bc7f5eb63ee50c84a83a7fa5ac94f68ec4.zip", # noqa: E501
+ "filename": "libimagequant-e5d454bc7f5eb63ee50c84a83a7fa5ac94f68ec4.zip",
+ "dir": "libimagequant-e5d454bc7f5eb63ee50c84a83a7fa5ac94f68ec4",
+ "patch": {
+ "CMakeLists.txt": {
+ "add_library": "add_compile_options(-openmp-)\r\nadd_library",
+ " SHARED": " STATIC",
+ }
+ },
+ "build": [
+ # lint: do not inline
+ cmd_cmake(),
+ cmd_nmake(target="clean"),
+ cmd_nmake(),
+ ],
+ "headers": [r"*.h"],
+ "libs": [r"*.lib"],
+ },
+ "harfbuzz": {
+ "url": "https://github.com/harfbuzz/harfbuzz/archive/2.6.7.zip",
+ "filename": "harfbuzz-2.6.7.zip",
+ "dir": "harfbuzz-2.6.7",
+ "build": [
+ cmd_cmake("-DHB_HAVE_FREETYPE:BOOL=TRUE"),
+ cmd_nmake(target="clean"),
+ cmd_nmake(target="harfbuzz"),
+ ],
+ "headers": [r"src\*.h"],
+ "libs": [r"*.lib"],
+ },
+ "fribidi": {
+ "url": "https://github.com/fribidi/fribidi/archive/v1.0.9.zip",
+ "filename": "fribidi-1.0.9.zip",
+ "dir": "fribidi-1.0.9",
+ "build": [
+ cmd_copy(r"{winbuild_dir}\fribidi.cmake", r"CMakeLists.txt"),
+ cmd_cmake(),
+ cmd_nmake(target="clean"),
+ cmd_nmake(target="fribidi"),
+ ],
+ "headers": [r"lib\*.h"],
+ "libs": [r"*.lib"],
+ },
+ "libraqm": {
+ "url": "https://github.com/HOST-Oman/libraqm/archive/v0.7.0.zip",
+ "filename": "libraqm-0.7.0.zip",
+ "dir": "libraqm-0.7.0",
+ "build": [
+ cmd_copy(r"{winbuild_dir}\raqm.cmake", r"CMakeLists.txt"),
+ cmd_cmake(),
+ cmd_nmake(target="clean"),
+ cmd_nmake(target="libraqm"),
+ ],
+ "headers": [r"src\*.h"],
+ "bins": [r"libraqm.dll"],
+ },
+}
+
+
+# based on distutils._msvccompiler from CPython 3.7.4
+def find_msvs():
+ root = os.environ.get("ProgramFiles(x86)") or os.environ.get("ProgramFiles")
+ if not root:
+ print("Program Files not found")
+ return None
+
+ try:
+ vspath = (
+ subprocess.check_output(
+ [
+ os.path.join(
+ root, "Microsoft Visual Studio", "Installer", "vswhere.exe"
+ ),
+ "-latest",
+ "-prerelease",
+ "-requires",
+ "Microsoft.VisualStudio.Component.VC.Tools.x86.x64",
+ "-property",
+ "installationPath",
+ "-products",
+ "*",
+ ]
+ )
+ .decode(encoding="mbcs")
+ .strip()
+ )
+ except (subprocess.CalledProcessError, OSError, UnicodeDecodeError):
+ print("vswhere not found")
+ return None
+
+ if not os.path.isdir(os.path.join(vspath, "VC", "Auxiliary", "Build")):
+ print("Visual Studio seems to be missing C compiler")
+ return None
+
+ vs = {
+ "header": [],
+ # nmake selected by vcvarsall
+ "nmake": "nmake.exe",
+ "vs_dir": vspath,
+ }
+
+ # vs2017
+ msbuild = os.path.join(vspath, "MSBuild", "15.0", "Bin", "MSBuild.exe")
+ if os.path.isfile(msbuild):
+ vs["msbuild"] = '"{}"'.format(msbuild)
+ else:
+ # vs2019
+ msbuild = os.path.join(vspath, "MSBuild", "Current", "Bin", "MSBuild.exe")
+ if os.path.isfile(msbuild):
+ vs["msbuild"] = '"{}"'.format(msbuild)
+ else:
+ print("Visual Studio MSBuild not found")
+ return None
+
+ vcvarsall = os.path.join(vspath, "VC", "Auxiliary", "Build", "vcvarsall.bat")
+ if not os.path.isfile(vcvarsall):
+ print("Visual Studio vcvarsall not found")
+ return None
+ vs["header"].append('call "{}" {{vcvars_arch}}'.format(vcvarsall))
+
+ return vs
+
+
+def extract_dep(url, filename):
+ import urllib.request
+ import tarfile
+ import zipfile
+
+ file = os.path.join(depends_dir, filename)
+ if not os.path.exists(file):
+ ex = None
+ for i in range(3):
+ try:
+ print("Fetching %s (attempt %d)..." % (url, i + 1))
+ content = urllib.request.urlopen(url).read()
+ with open(file, "wb") as f:
+ f.write(content)
+ break
+ except urllib.error.URLError as e:
+ ex = e
+ else:
+ raise RuntimeError(ex)
+
+ print("Extracting " + filename)
+ if filename.endswith(".zip"):
+ with zipfile.ZipFile(file) as zf:
+ zf.extractall(build_dir)
+ elif filename.endswith(".tar.gz") or filename.endswith(".tgz"):
+ with tarfile.open(file, "r:gz") as tgz:
+ tgz.extractall(build_dir)
+ else:
+ raise RuntimeError("Unknown archive type: " + filename)
+
+
+def write_script(name, lines):
+ name = os.path.join(build_dir, name)
+ lines = [line.format(**prefs) for line in lines]
+ print("Writing " + name)
+ with open(name, "w") as f:
+ f.write("\n\r".join(lines))
+ if verbose:
+ for line in lines:
+ print(" " + line)
+
+
+def get_footer(dep):
+ lines = []
+ for out in dep.get("headers", []):
+ lines.append(cmd_copy(out, "{inc_dir}"))
+ for out in dep.get("libs", []):
+ lines.append(cmd_copy(out, "{lib_dir}"))
+ for out in dep.get("bins", []):
+ lines.append(cmd_copy(out, "{bin_dir}"))
+ return lines
+
+
+def build_dep(name):
+ dep = deps[name]
+ dir = dep["dir"]
+ file = "build_dep_{name}.cmd".format(**locals())
+
+ extract_dep(dep["url"], dep["filename"])
+
+ for patch_file, patch_list in dep.get("patch", {}).items():
+ patch_file = os.path.join(build_dir, dir, patch_file.format(**prefs))
+ with open(patch_file, "r") as f:
+ text = f.read()
+ for patch_from, patch_to in patch_list.items():
+ text = text.replace(patch_from.format(**prefs), patch_to.format(**prefs))
+ with open(patch_file, "w") as f:
+ f.write(text)
+
+ banner = "Building {name} ({dir})".format(**locals())
+ lines = [
+ "@echo " + ("=" * 70),
+ "@echo ==== {:<60} ====".format(banner),
+ "@echo " + ("=" * 70),
+ "cd /D %s" % os.path.join(build_dir, dir),
+ *prefs["header"],
+ *dep.get("build", []),
+ *get_footer(dep),
+ ]
+
+ write_script(file, lines)
+ return file
+
+
+def build_dep_all():
+ lines = ["@echo on"]
+ for dep_name in deps:
+ if dep_name in disabled:
+ continue
+ lines.append(r'cmd.exe /c "{{build_dir}}\{}"'.format(build_dep(dep_name)))
+ lines.append("if errorlevel 1 echo Build failed! && exit /B 1")
+ lines.append("@echo All Pillow dependencies built successfully!")
+ write_script("build_dep_all.cmd", lines)
+
+
+def build_pillow():
+ lines = [
+ "@echo ---- Building Pillow (build_ext %*) ----",
+ cmd_cd("{pillow_dir}"),
+ *prefs["header"],
+ cmd_set("DISTUTILS_USE_SDK", "1"), # use same compiler to build Pillow
+ cmd_set("MSSdk", "1"), # for Python 3.5 and PyPy3.6
+ cmd_set("py_vcruntime_redist", "true"), # use /MD, not /MT
+ r'"{python_dir}\{python_exe}" setup.py build_ext %*',
+ ]
+
+ write_script("build_pillow.cmd", lines)
+
+
+if __name__ == "__main__":
+ # winbuild directory
+ winbuild_dir = os.path.dirname(os.path.realpath(__file__))
+
+ verbose = False
+ disabled = []
+ depends_dir = os.environ.get("PILLOW_DEPS", os.path.join(winbuild_dir, "depends"))
+ python_dir = os.environ.get("PYTHON")
+ python_exe = os.environ.get("EXECUTABLE", "python.exe")
+ architecture = os.environ.get(
+ "ARCHITECTURE", "x86" if struct.calcsize("P") == 4 else "x64"
+ )
+ build_dir = os.environ.get("PILLOW_BUILD", os.path.join(winbuild_dir, "build"))
+ for arg in sys.argv[1:]:
+ if arg == "-v":
+ verbose = True
+ elif arg == "--no-imagequant":
+ disabled += ["libimagequant"]
+ elif arg == "--no-raqm":
+ disabled += ["harfbuzz", "fribidi", "libraqm"]
+ elif arg.startswith("--depends="):
+ depends_dir = arg[10:]
+ elif arg.startswith("--python="):
+ python_dir = arg[9:]
+ elif arg.startswith("--executable="):
+ python_exe = arg[13:]
+ elif arg.startswith("--architecture="):
+ architecture = arg[15:]
+ elif arg.startswith("--dir="):
+ build_dir = arg[6:]
+ else:
+ raise ValueError("Unknown parameter: " + arg)
+
+ # dependency cache directory
+ os.makedirs(depends_dir, exist_ok=True)
+ print("Caching dependencies in:", depends_dir)
+
+ if python_dir is None:
+ python_dir = os.path.dirname(os.path.realpath(sys.executable))
+ python_exe = os.path.basename(sys.executable)
+ print("Target Python:", os.path.join(python_dir, python_exe))
+
+ arch_prefs = architectures[architecture]
+ print("Target Architecture:", architecture)
+
+ msvs = find_msvs()
+ if msvs is None:
+ raise RuntimeError(
+ "Visual Studio not found. Please install Visual Studio 2017 or newer."
+ )
+ print("Found Visual Studio at:", msvs["vs_dir"])
+
+ print("Using output directory:", build_dir)
+
+ # build directory for *.h files
+ inc_dir = os.path.join(build_dir, "inc")
+ # build directory for *.lib files
+ lib_dir = os.path.join(build_dir, "lib")
+ # build directory for *.bin files
+ bin_dir = os.path.join(build_dir, "bin")
+
+ shutil.rmtree(build_dir, ignore_errors=True)
+ for path in [build_dir, inc_dir, lib_dir, bin_dir]:
+ os.makedirs(path)
+
+ prefs = {
+ # Python paths / preferences
+ "python_dir": python_dir,
+ "python_exe": python_exe,
+ "architecture": architecture,
+ **arch_prefs,
+ # Pillow paths
+ "pillow_dir": os.path.realpath(os.path.join(winbuild_dir, "..")),
+ "winbuild_dir": winbuild_dir,
+ # Build paths
+ "build_dir": build_dir,
+ "inc_dir": inc_dir,
+ "lib_dir": lib_dir,
+ "bin_dir": bin_dir,
+ # Compilers / Tools
+ **msvs,
+ "cmake": "cmake.exe", # TODO find CMAKE automatically
+ # TODO find NASM automatically
+ # script header
+ "header": sum([header, msvs["header"], ["@echo on"]], []),
+ }
+
+ print()
+
+ build_dep_all()
+ build_pillow()
diff --git a/winbuild/config.py b/winbuild/config.py
deleted file mode 100644
index 93413d1e5..000000000
--- a/winbuild/config.py
+++ /dev/null
@@ -1,199 +0,0 @@
-import os
-
-SF_MIRROR = "https://iweb.dl.sourceforge.net"
-
-pythons = {
- "pypy3": {"compiler": 7.1, "vc": 2015},
- # for AppVeyor
- "35": {"compiler": 7.1, "vc": 2015},
- "36": {"compiler": 7.1, "vc": 2015},
- "37": {"compiler": 7.1, "vc": 2015},
- "38": {"compiler": 7.1, "vc": 2015},
- # for GitHub Actions
- "3.5": {"compiler": 7.1, "vc": 2015},
- "3.6": {"compiler": 7.1, "vc": 2015},
- "3.7": {"compiler": 7.1, "vc": 2015},
- "3.8": {"compiler": 7.1, "vc": 2015},
-}
-
-VIRT_BASE = "c:/vp/"
-X64_EXT = os.environ.get("X64_EXT", "x64")
-
-libs = {
- # 'openjpeg': {
- # 'filename': 'openjpeg-2.0.0-win32-x86.zip',
- # 'version': '2.0'
- # },
- "zlib": {
- "url": "http://zlib.net/zlib1211.zip",
- "filename": "zlib1211.zip",
- "dir": "zlib-1.2.11",
- },
- "jpeg": {
- "url": "http://www.ijg.org/files/jpegsr9d.zip",
- "filename": "jpegsr9d.zip",
- "dir": "jpeg-9d",
- },
- "tiff": {
- "url": "ftp://download.osgeo.org/libtiff/tiff-4.1.0.tar.gz",
- "filename": "tiff-4.1.0.tar.gz",
- "dir": "tiff-4.1.0",
- },
- "freetype": {
- "url": "https://download.savannah.gnu.org/releases/freetype/freetype-2.10.1.tar.gz", # noqa: E501
- "filename": "freetype-2.10.1.tar.gz",
- "dir": "freetype-2.10.1",
- },
- "lcms-2.7": {
- "url": SF_MIRROR + "/project/lcms/lcms/2.7/lcms2-2.7.zip",
- "filename": "lcms2-2.7.zip",
- "dir": "lcms2-2.7",
- },
- "lcms-2.8": {
- "url": SF_MIRROR + "/project/lcms/lcms/2.8/lcms2-2.8.zip",
- "filename": "lcms2-2.8.zip",
- "dir": "lcms2-2.8",
- },
- "tcl-8.5": {
- "url": SF_MIRROR + "/project/tcl/Tcl/8.5.19/tcl8519-src.zip",
- "filename": "tcl8519-src.zip",
- "dir": "",
- },
- "tk-8.5": {
- "url": SF_MIRROR + "/project/tcl/Tcl/8.5.19/tk8519-src.zip",
- "filename": "tk8519-src.zip",
- "dir": "",
- "version": "8.5.19",
- },
- "tcl-8.6": {
- "url": SF_MIRROR + "/project/tcl/Tcl/8.6.10/tcl8610-src.zip",
- "filename": "tcl8610-src.zip",
- "dir": "",
- },
- "tk-8.6": {
- "url": SF_MIRROR + "/project/tcl/Tcl/8.6.10/tk8610-src.zip",
- "filename": "tk8610-src.zip",
- "dir": "",
- "version": "8.6.10",
- },
- "webp": {
- "url": "http://downloads.webmproject.org/releases/webp/libwebp-1.1.0.tar.gz",
- "filename": "libwebp-1.1.0.tar.gz",
- "dir": "libwebp-1.1.0",
- },
- "openjpeg": {
- "url": "https://github.com/uclouvain/openjpeg/archive/v2.3.1.tar.gz",
- "filename": "openjpeg-2.3.1.tar.gz",
- "dir": "openjpeg-2.3.1",
- },
- "jpeg-turbo": {
- "url": SF_MIRROR + "/project/libjpeg-turbo/2.0.3/libjpeg-turbo-2.0.3.tar.gz",
- "filename": "libjpeg-turbo-2.0.3.tar.gz",
- "dir": "libjpeg-turbo-2.0.3",
- },
- # e5d454b: Merge tag '2.12.6' into msvc
- "imagequant": {
- "url": "https://github.com/ImageOptim/libimagequant/archive/e5d454bc7f5eb63ee50c84a83a7fa5ac94f68ec4.zip", # noqa: E501
- "filename": "libimagequant-e5d454bc7f5eb63ee50c84a83a7fa5ac94f68ec4.zip",
- "dir": "libimagequant-e5d454bc7f5eb63ee50c84a83a7fa5ac94f68ec4",
- },
- "harfbuzz": {
- "url": "https://github.com/harfbuzz/harfbuzz/archive/2.6.4.zip",
- "filename": "harfbuzz-2.6.4.zip",
- "dir": "harfbuzz-2.6.4",
- },
- "fribidi": {
- "url": "https://github.com/fribidi/fribidi/archive/v1.0.9.zip",
- "filename": "fribidi-1.0.9.zip",
- "dir": "fribidi-1.0.9",
- },
- "libraqm": {
- "url": "https://github.com/HOST-Oman/libraqm/archive/v0.7.0.zip",
- "filename": "libraqm-0.7.0.zip",
- "dir": "libraqm-0.7.0",
- },
-}
-
-compilers = {
- 7: {
- 2010: {
- 64: {
- "env_version": "v7.0",
- "vc_version": "2010",
- "env_flags": "/x64 /xp",
- "inc_dir": "msvcr90-x64",
- "platform": "x64",
- "webp_platform": "x64",
- },
- 32: {
- "env_version": "v7.0",
- "vc_version": "2010",
- "env_flags": "/x86 /xp",
- "inc_dir": "msvcr90-x32",
- "platform": "Win32",
- "webp_platform": "x86",
- },
- }
- },
- 7.1: {
- 2015: {
- 64: {
- "env_version": "v7.1",
- "vc_version": "2015",
- "env_flags": "/x64 /vista",
- "inc_dir": "msvcr10-x64",
- "platform": "x64",
- "webp_platform": "x64",
- },
- 32: {
- "env_version": "v7.1",
- "vc_version": "2015",
- "env_flags": "/x86 /vista",
- "inc_dir": "msvcr10-x32",
- "platform": "Win32",
- "webp_platform": "x86",
- },
- }
- },
-}
-
-
-def pyversion_from_env():
- py = os.environ["PYTHON"]
-
- py_version = "35"
- for k in pythons:
- if k in py:
- py_version = k
- break
-
- if "64" in py:
- py_version = "{}{}".format(py_version, X64_EXT)
-
- return py_version
-
-
-def compiler_from_env():
- py = os.environ["PYTHON"]
-
- for k, v in pythons.items():
- if k in py:
- py_info = v
- break
-
- bit = bit_from_env()
- return compilers[py_info["compiler"]][py_info["vc"]][bit]
-
-
-def bit_from_env():
- py = os.environ["PYTHON"]
-
- return 64 if "64" in py else 32
-
-
-def all_compilers():
- all = []
- for vc_compilers in compilers.values():
- for bit_compilers in vc_compilers.values():
- all += bit_compilers.values()
- return all
diff --git a/winbuild/fetch.py b/winbuild/fetch.py
deleted file mode 100644
index adc45429a..000000000
--- a/winbuild/fetch.py
+++ /dev/null
@@ -1,44 +0,0 @@
-import os
-import sys
-import urllib.parse
-import urllib.request
-
-from config import libs
-
-
-def fetch(url):
- depends_filename = None
- for lib in libs.values():
- if lib["url"] == url:
- depends_filename = lib["filename"]
- break
- if depends_filename and os.path.exists(depends_filename):
- return depends_filename
- name = urllib.parse.urlsplit(url)[2].split("/")[-1]
-
- if not os.path.exists(name):
-
- def retrieve(request_url):
- print("Fetching", request_url)
- try:
- return urllib.request.urlopen(request_url)
- except urllib.error.URLError:
- return urllib.request.urlopen(request_url)
-
- try:
- r = retrieve(url)
- except urllib.error.HTTPError:
- if depends_filename:
- r = retrieve(
- "https://github.com/python-pillow/pillow-depends/raw/master/"
- + depends_filename
- )
- name = depends_filename
- content = r.read()
- with open(name, "wb") as fd:
- fd.write(content)
- return name
-
-
-if __name__ == "__main__":
- fetch(sys.argv[1])
diff --git a/winbuild/fribidi.cmake b/winbuild/fribidi.cmake
index 247e79e4c..112174731 100644
--- a/winbuild/fribidi.cmake
+++ b/winbuild/fribidi.cmake
@@ -1,4 +1,4 @@
-cmake_minimum_required(VERSION 3.13)
+cmake_minimum_required(VERSION 3.12)
project(fribidi)
diff --git a/winbuild/get_pythons.py b/winbuild/get_pythons.py
deleted file mode 100644
index a853fc6f7..000000000
--- a/winbuild/get_pythons.py
+++ /dev/null
@@ -1,15 +0,0 @@
-import os
-
-from fetch import fetch
-
-if __name__ == "__main__":
- for version in ["3.4.4"]:
- for platform in ["", ".amd64"]:
- for extension in ["", ".asc"]:
- fetch(
- "https://www.python.org/ftp/python/%s/python-%s%s.msi%s"
- % (version, version, platform, extension)
- )
-
- # find pip, if it's not in the path!
- os.system("pip install virtualenv")
diff --git a/winbuild/lcms2_patch.ps1 b/winbuild/lcms2_patch.ps1
deleted file mode 100644
index 7fc48c034..000000000
--- a/winbuild/lcms2_patch.ps1
+++ /dev/null
@@ -1,9 +0,0 @@
-
-Get-ChildItem .\Projects\VC2015\ *.vcxproj -recurse |
- Foreach-Object {
- $c = ($_ | Get-Content)
- $c = $c -replace 'MultiThreaded<','MultiThreadedDLL<'
- $c = $c -replace '8.1','10'
- $c = $c -replace 'v140','v142'
- [IO.File]::WriteAllText($_.FullName, ($c -join "`r`n"))
- }
diff --git a/winbuild/raqm.cmake b/winbuild/raqm.cmake
index 88eb7f284..e8e71800e 100644
--- a/winbuild/raqm.cmake
+++ b/winbuild/raqm.cmake
@@ -1,4 +1,4 @@
-cmake_minimum_required(VERSION 3.13)
+cmake_minimum_required(VERSION 3.12)
project(libraqm)
diff --git a/winbuild/test.py b/winbuild/test.py
deleted file mode 100755
index a05a20b18..000000000
--- a/winbuild/test.py
+++ /dev/null
@@ -1,45 +0,0 @@
-#!/usr/bin/env python3
-
-import glob
-import os
-import subprocess
-import sys
-
-from config import VIRT_BASE, X64_EXT, pythons
-
-
-def test_one(params):
- python, architecture = params
- try:
- print("Running: %s, %s" % params)
- command = [
- r"{}\{}{}\Scripts\python.exe".format(VIRT_BASE, python, architecture),
- "test-installed.py",
- "--processes=-0",
- "--process-timeout=30",
- ]
- command.extend(glob.glob("Tests/test*.py"))
- proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
- (trace, stderr) = proc.communicate()
- status = proc.returncode
- print("Done with {}, {} -- {}".format(python, architecture, status))
- return (python, architecture, status, trace)
- except Exception as msg:
- print("Error with {}, {}: {}".format(python, architecture, msg))
- return (python, architecture, -1, str(msg))
-
-
-if __name__ == "__main__":
-
- os.chdir("..")
- matrix = [
- (python, architecture) for python in pythons for architecture in ("", X64_EXT)
- ]
-
- results = map(test_one, matrix)
-
- for (python, architecture, status, trace) in results:
- print("{}{}: {}".format(python, architecture, status and "ERR" or "PASS"))
-
- res = all(status for (python, architecture, status, trace) in results)
- sys.exit(res)
diff --git a/winbuild/untar.py b/winbuild/untar.py
deleted file mode 100644
index f2713b2f2..000000000
--- a/winbuild/untar.py
+++ /dev/null
@@ -1,11 +0,0 @@
-import sys
-import tarfile
-
-
-def untar(src, dest):
- with tarfile.open(src, "r:gz") as tgz:
- tgz.extractall(dest)
-
-
-if __name__ == "__main__":
- untar(sys.argv[1], sys.argv[2])
diff --git a/winbuild/unzip.py b/winbuild/unzip.py
deleted file mode 100644
index eb17a2e63..000000000
--- a/winbuild/unzip.py
+++ /dev/null
@@ -1,11 +0,0 @@
-import sys
-import zipfile
-
-
-def unzip(src, dest):
- with zipfile.ZipFile(src) as zf:
- zf.extractall(dest)
-
-
-if __name__ == "__main__":
- unzip(sys.argv[1], sys.argv[2])