Merge branch 'main' into type-annotations

This commit is contained in:
Andrew Murray 2024-05-21 22:44:03 +10:00 committed by GitHub
commit c0ee645d0d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
50 changed files with 682 additions and 559 deletions

View File

@ -1 +1 @@
cibuildwheel==2.18.0 cibuildwheel==2.18.1

View File

@ -9,6 +9,7 @@ BinPackParameters: false
BreakBeforeBraces: Attach BreakBeforeBraces: Attach
ColumnLimit: 88 ColumnLimit: 88
DerivePointerAlignment: false DerivePointerAlignment: false
IndentGotoLabels: false
IndentWidth: 4 IndentWidth: 4
Language: Cpp Language: Cpp
PointerAlignment: Right PointerAlignment: Right

View File

@ -23,6 +23,13 @@ repos:
- id: remove-tabs - id: remove-tabs
exclude: (Makefile$|\.bat$|\.cmake$|\.eps$|\.fits$|\.gd$|\.opt$) exclude: (Makefile$|\.bat$|\.cmake$|\.eps$|\.fits$|\.gd$|\.opt$)
- repo: https://github.com/pre-commit/mirrors-clang-format
rev: v18.1.4
hooks:
- id: clang-format
types: [c]
exclude: ^src/thirdparty/
- repo: https://github.com/pre-commit/pygrep-hooks - repo: https://github.com/pre-commit/pygrep-hooks
rev: v1.10.0 rev: v1.10.0
hooks: hooks:

View File

@ -23,8 +23,7 @@ from setuptools.command.build_ext import build_ext
def get_version(): def get_version():
version_file = "src/PIL/_version.py" version_file = "src/PIL/_version.py"
with open(version_file, encoding="utf-8") as f: with open(version_file, encoding="utf-8") as f:
exec(compile(f.read(), version_file, "exec")) return f.read().split('"')[1]
return locals()["__version__"]
configuration = {} configuration = {}

View File

@ -472,7 +472,7 @@ class DdsImageFile(ImageFile.ImageFile):
else: else:
self.tile = [ImageFile._Tile("raw", extents, 0, rawmode or self.mode)] self.tile = [ImageFile._Tile("raw", extents, 0, rawmode or self.mode)]
def load_seek(self, pos): def load_seek(self, pos: int) -> None:
pass pass

View File

@ -42,7 +42,7 @@ gs_binary: str | bool | None = None
gs_windows_binary = None gs_windows_binary = None
def has_ghostscript(): def has_ghostscript() -> bool:
global gs_binary, gs_windows_binary global gs_binary, gs_windows_binary
if gs_binary is None: if gs_binary is None:
if sys.platform.startswith("win"): if sys.platform.startswith("win"):
@ -404,7 +404,7 @@ class EpsImageFile(ImageFile.ImageFile):
self.tile = [] self.tile = []
return Image.Image.load(self) return Image.Image.load(self)
def load_seek(self, pos): def load_seek(self, pos: int) -> None:
# we can't incrementally load, so force ImageFile.parser to # we can't incrementally load, so force ImageFile.parser to
# use our custom load method by defining this method. # use our custom load method by defining this method.
pass pass

View File

@ -103,7 +103,7 @@ class FtexImageFile(ImageFile.ImageFile):
self.fp.close() self.fp.close()
self.fp = BytesIO(data) self.fp = BytesIO(data)
def load_seek(self, pos): def load_seek(self, pos: int) -> None:
pass pass

View File

@ -341,7 +341,7 @@ class IcoImageFile(ImageFile.ImageFile):
self.size = im.size self.size = im.size
def load_seek(self, pos): def load_seek(self, pos: int) -> None:
# Flag the ImageFile.Parser so that it # Flag the ImageFile.Parser so that it
# just does all the decode at the end. # just does all the decode at the end.
pass pass

View File

@ -324,11 +324,11 @@ class ImageFile(Image.Image):
pass pass
# may be defined for contained formats # may be defined for contained formats
# def load_seek(self, pos): # def load_seek(self, pos: int) -> None:
# pass # pass
# may be defined for blocked formats (e.g. PNG) # may be defined for blocked formats (e.g. PNG)
# def load_read(self, read_bytes): # def load_read(self, read_bytes: int) -> bytes:
# pass # pass
def _seek_check(self, frame): def _seek_check(self, frame):

View File

@ -408,7 +408,7 @@ class JpegImageFile(ImageFile.ImageFile):
msg = "no marker found" msg = "no marker found"
raise SyntaxError(msg) raise SyntaxError(msg)
def load_read(self, read_bytes): def load_read(self, read_bytes: int) -> bytes:
""" """
internal: read more image data internal: read more image data
For premature EOF and LOAD_TRUNCATED_IMAGES adds EOI marker For premature EOF and LOAD_TRUNCATED_IMAGES adds EOI marker

View File

@ -124,7 +124,7 @@ class MpoImageFile(JpegImagePlugin.JpegImageFile):
# for now we can only handle reading and individual frame extraction # for now we can only handle reading and individual frame extraction
self.readonly = 1 self.readonly = 1
def load_seek(self, pos): def load_seek(self, pos: int) -> None:
self._fp.seek(pos) self._fp.seek(pos)
def seek(self, frame: int) -> None: def seek(self, frame: int) -> None:

View File

@ -39,6 +39,7 @@ import struct
import warnings import warnings
import zlib import zlib
from enum import IntEnum from enum import IntEnum
from typing import IO
from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence
from ._binary import i16be as i16 from ._binary import i16be as i16
@ -149,14 +150,15 @@ def _crc32(data, seed=0):
class ChunkStream: class ChunkStream:
def __init__(self, fp): def __init__(self, fp: IO[bytes]) -> None:
self.fp = fp self.fp: IO[bytes] | None = fp
self.queue = [] self.queue: list[tuple[bytes, int, int]] | None = []
def read(self): def read(self) -> tuple[bytes, int, int]:
"""Fetch a new chunk. Returns header information.""" """Fetch a new chunk. Returns header information."""
cid = None cid = None
assert self.fp is not None
if self.queue: if self.queue:
cid, pos, length = self.queue.pop() cid, pos, length = self.queue.pop()
self.fp.seek(pos) self.fp.seek(pos)
@ -173,7 +175,7 @@ class ChunkStream:
return cid, pos, length return cid, pos, length
def __enter__(self): def __enter__(self) -> ChunkStream:
return self return self
def __exit__(self, *args): def __exit__(self, *args):
@ -182,7 +184,8 @@ class ChunkStream:
def close(self) -> None: def close(self) -> None:
self.queue = self.fp = None self.queue = self.fp = None
def push(self, cid, pos, length): def push(self, cid: bytes, pos: int, length: int) -> None:
assert self.queue is not None
self.queue.append((cid, pos, length)) self.queue.append((cid, pos, length))
def call(self, cid, pos, length): def call(self, cid, pos, length):
@ -191,7 +194,7 @@ class ChunkStream:
logger.debug("STREAM %r %s %s", cid, pos, length) logger.debug("STREAM %r %s %s", cid, pos, length)
return getattr(self, f"chunk_{cid.decode('ascii')}")(pos, length) return getattr(self, f"chunk_{cid.decode('ascii')}")(pos, length)
def crc(self, cid, data): def crc(self, cid: bytes, data: bytes) -> None:
"""Read and verify checksum""" """Read and verify checksum"""
# Skip CRC checks for ancillary chunks if allowed to load truncated # Skip CRC checks for ancillary chunks if allowed to load truncated
@ -201,6 +204,7 @@ class ChunkStream:
self.crc_skip(cid, data) self.crc_skip(cid, data)
return return
assert self.fp is not None
try: try:
crc1 = _crc32(data, _crc32(cid)) crc1 = _crc32(data, _crc32(cid))
crc2 = i32(self.fp.read(4)) crc2 = i32(self.fp.read(4))
@ -211,12 +215,13 @@ class ChunkStream:
msg = f"broken PNG file (incomplete checksum in {repr(cid)})" msg = f"broken PNG file (incomplete checksum in {repr(cid)})"
raise SyntaxError(msg) from e raise SyntaxError(msg) from e
def crc_skip(self, cid, data): def crc_skip(self, cid: bytes, data: bytes) -> None:
"""Read checksum""" """Read checksum"""
assert self.fp is not None
self.fp.read(4) self.fp.read(4)
def verify(self, endchunk=b"IEND"): def verify(self, endchunk: bytes = b"IEND") -> list[bytes]:
# Simple approach; just calculate checksum for all remaining # Simple approach; just calculate checksum for all remaining
# blocks. Must be called directly after open. # blocks. Must be called directly after open.
@ -361,7 +366,7 @@ class PngStream(ChunkStream):
self.text_memory = 0 self.text_memory = 0
def check_text_memory(self, chunklen): def check_text_memory(self, chunklen: int) -> None:
self.text_memory += chunklen self.text_memory += chunklen
if self.text_memory > MAX_TEXT_MEMORY: if self.text_memory > MAX_TEXT_MEMORY:
msg = ( msg = (
@ -382,7 +387,7 @@ class PngStream(ChunkStream):
self.im_tile = self.rewind_state["tile"] self.im_tile = self.rewind_state["tile"]
self._seq_num = self.rewind_state["seq_num"] self._seq_num = self.rewind_state["seq_num"]
def chunk_iCCP(self, pos, length): def chunk_iCCP(self, pos: int, length: int) -> bytes:
# ICC profile # ICC profile
s = ImageFile._safe_read(self.fp, length) s = ImageFile._safe_read(self.fp, length)
# according to PNG spec, the iCCP chunk contains: # according to PNG spec, the iCCP chunk contains:
@ -409,7 +414,7 @@ class PngStream(ChunkStream):
self.im_info["icc_profile"] = icc_profile self.im_info["icc_profile"] = icc_profile
return s return s
def chunk_IHDR(self, pos, length): def chunk_IHDR(self, pos: int, length: int) -> bytes:
# image header # image header
s = ImageFile._safe_read(self.fp, length) s = ImageFile._safe_read(self.fp, length)
if length < 13: if length < 13:
@ -446,14 +451,14 @@ class PngStream(ChunkStream):
msg = "end of PNG image" msg = "end of PNG image"
raise EOFError(msg) raise EOFError(msg)
def chunk_PLTE(self, pos, length): def chunk_PLTE(self, pos: int, length: int) -> bytes:
# palette # palette
s = ImageFile._safe_read(self.fp, length) s = ImageFile._safe_read(self.fp, length)
if self.im_mode == "P": if self.im_mode == "P":
self.im_palette = "RGB", s self.im_palette = "RGB", s
return s return s
def chunk_tRNS(self, pos, length): def chunk_tRNS(self, pos: int, length: int) -> bytes:
# transparency # transparency
s = ImageFile._safe_read(self.fp, length) s = ImageFile._safe_read(self.fp, length)
if self.im_mode == "P": if self.im_mode == "P":
@ -473,13 +478,13 @@ class PngStream(ChunkStream):
self.im_info["transparency"] = i16(s), i16(s, 2), i16(s, 4) self.im_info["transparency"] = i16(s), i16(s, 2), i16(s, 4)
return s return s
def chunk_gAMA(self, pos, length): def chunk_gAMA(self, pos: int, length: int) -> bytes:
# gamma setting # gamma setting
s = ImageFile._safe_read(self.fp, length) s = ImageFile._safe_read(self.fp, length)
self.im_info["gamma"] = i32(s) / 100000.0 self.im_info["gamma"] = i32(s) / 100000.0
return s return s
def chunk_cHRM(self, pos, length): def chunk_cHRM(self, pos: int, length: int) -> bytes:
# chromaticity, 8 unsigned ints, actual value is scaled by 100,000 # chromaticity, 8 unsigned ints, actual value is scaled by 100,000
# WP x,y, Red x,y, Green x,y Blue x,y # WP x,y, Red x,y, Green x,y Blue x,y
@ -488,7 +493,7 @@ class PngStream(ChunkStream):
self.im_info["chromaticity"] = tuple(elt / 100000.0 for elt in raw_vals) self.im_info["chromaticity"] = tuple(elt / 100000.0 for elt in raw_vals)
return s return s
def chunk_sRGB(self, pos, length): def chunk_sRGB(self, pos: int, length: int) -> bytes:
# srgb rendering intent, 1 byte # srgb rendering intent, 1 byte
# 0 perceptual # 0 perceptual
# 1 relative colorimetric # 1 relative colorimetric
@ -504,7 +509,7 @@ class PngStream(ChunkStream):
self.im_info["srgb"] = s[0] self.im_info["srgb"] = s[0]
return s return s
def chunk_pHYs(self, pos, length): def chunk_pHYs(self, pos: int, length: int) -> bytes:
# pixels per unit # pixels per unit
s = ImageFile._safe_read(self.fp, length) s = ImageFile._safe_read(self.fp, length)
if length < 9: if length < 9:
@ -521,7 +526,7 @@ class PngStream(ChunkStream):
self.im_info["aspect"] = px, py self.im_info["aspect"] = px, py
return s return s
def chunk_tEXt(self, pos, length): def chunk_tEXt(self, pos: int, length: int) -> bytes:
# text # text
s = ImageFile._safe_read(self.fp, length) s = ImageFile._safe_read(self.fp, length)
try: try:
@ -540,7 +545,7 @@ class PngStream(ChunkStream):
return s return s
def chunk_zTXt(self, pos, length): def chunk_zTXt(self, pos: int, length: int) -> bytes:
# compressed text # compressed text
s = ImageFile._safe_read(self.fp, length) s = ImageFile._safe_read(self.fp, length)
try: try:
@ -574,7 +579,7 @@ class PngStream(ChunkStream):
return s return s
def chunk_iTXt(self, pos, length): def chunk_iTXt(self, pos: int, length: int) -> bytes:
# international text # international text
r = s = ImageFile._safe_read(self.fp, length) r = s = ImageFile._safe_read(self.fp, length)
try: try:
@ -614,13 +619,13 @@ class PngStream(ChunkStream):
return s return s
def chunk_eXIf(self, pos, length): def chunk_eXIf(self, pos: int, length: int) -> bytes:
s = ImageFile._safe_read(self.fp, length) s = ImageFile._safe_read(self.fp, length)
self.im_info["exif"] = b"Exif\x00\x00" + s self.im_info["exif"] = b"Exif\x00\x00" + s
return s return s
# APNG chunks # APNG chunks
def chunk_acTL(self, pos, length): def chunk_acTL(self, pos: int, length: int) -> bytes:
s = ImageFile._safe_read(self.fp, length) s = ImageFile._safe_read(self.fp, length)
if length < 8: if length < 8:
if ImageFile.LOAD_TRUNCATED_IMAGES: if ImageFile.LOAD_TRUNCATED_IMAGES:
@ -640,7 +645,7 @@ class PngStream(ChunkStream):
self.im_custom_mimetype = "image/apng" self.im_custom_mimetype = "image/apng"
return s return s
def chunk_fcTL(self, pos, length): def chunk_fcTL(self, pos: int, length: int) -> bytes:
s = ImageFile._safe_read(self.fp, length) s = ImageFile._safe_read(self.fp, length)
if length < 26: if length < 26:
if ImageFile.LOAD_TRUNCATED_IMAGES: if ImageFile.LOAD_TRUNCATED_IMAGES:
@ -669,7 +674,7 @@ class PngStream(ChunkStream):
self.im_info["blend"] = s[25] self.im_info["blend"] = s[25]
return s return s
def chunk_fdAT(self, pos, length): def chunk_fdAT(self, pos: int, length: int) -> bytes:
if length < 4: if length < 4:
if ImageFile.LOAD_TRUNCATED_IMAGES: if ImageFile.LOAD_TRUNCATED_IMAGES:
s = ImageFile._safe_read(self.fp, length) s = ImageFile._safe_read(self.fp, length)
@ -701,7 +706,7 @@ class PngImageFile(ImageFile.ImageFile):
format = "PNG" format = "PNG"
format_description = "Portable network graphics" format_description = "Portable network graphics"
def _open(self): def _open(self) -> None:
if not _accept(self.fp.read(8)): if not _accept(self.fp.read(8)):
msg = "not a PNG file" msg = "not a PNG file"
raise SyntaxError(msg) raise SyntaxError(msg)
@ -711,8 +716,8 @@ class PngImageFile(ImageFile.ImageFile):
# #
# Parse headers up to the first IDAT or fDAT chunk # Parse headers up to the first IDAT or fDAT chunk
self.private_chunks = [] self.private_chunks: list[tuple[bytes, bytes] | tuple[bytes, bytes, bool]] = []
self.png = PngStream(self.fp) self.png: PngStream | None = PngStream(self.fp)
while True: while True:
# #
@ -793,6 +798,7 @@ class PngImageFile(ImageFile.ImageFile):
# back up to beginning of IDAT block # back up to beginning of IDAT block
self.fp.seek(self.tile[0][2] - 8) self.fp.seek(self.tile[0][2] - 8)
assert self.png is not None
self.png.verify() self.png.verify()
self.png.close() self.png.close()
@ -921,9 +927,10 @@ class PngImageFile(ImageFile.ImageFile):
self.__idat = self.__prepare_idat # used by load_read() self.__idat = self.__prepare_idat # used by load_read()
ImageFile.ImageFile.load_prepare(self) ImageFile.ImageFile.load_prepare(self)
def load_read(self, read_bytes): def load_read(self, read_bytes: int) -> bytes:
"""internal: read more image data""" """internal: read more image data"""
assert self.png is not None
while self.__idat == 0: while self.__idat == 0:
# end of chunk, skip forward to next one # end of chunk, skip forward to next one
@ -956,6 +963,7 @@ class PngImageFile(ImageFile.ImageFile):
def load_end(self) -> None: def load_end(self) -> None:
"""internal: finished reading image data""" """internal: finished reading image data"""
assert self.png is not None
if self.__idat != 0: if self.__idat != 0:
self.fp.read(self.__idat) self.fp.read(self.__idat)
while True: while True:
@ -1079,7 +1087,7 @@ class _idat:
self.fp = fp self.fp = fp
self.chunk = chunk self.chunk = chunk
def write(self, data): def write(self, data: bytes) -> None:
self.chunk(self.fp, b"IDAT", data) self.chunk(self.fp, b"IDAT", data)
@ -1091,7 +1099,7 @@ class _fdat:
self.chunk = chunk self.chunk = chunk
self.seq_num = seq_num self.seq_num = seq_num
def write(self, data): def write(self, data: bytes) -> None:
self.chunk(self.fp, b"fdAT", o32(self.seq_num), data) self.chunk(self.fp, b"fdAT", o32(self.seq_num), data)
self.seq_num += 1 self.seq_num += 1
@ -1436,10 +1444,10 @@ def getchunks(im, **params):
class collector: class collector:
data = [] data = []
def write(self, data): def write(self, data: bytes) -> None:
pass pass
def append(self, chunk): def append(self, chunk: bytes) -> None:
self.data.append(chunk) self.data.append(chunk)
def append(fp, cid, *data): def append(fp, cid, *data):

View File

@ -171,7 +171,7 @@ class WebPImageFile(ImageFile.ImageFile):
return super().load() return super().load()
def load_seek(self, pos): def load_seek(self, pos: int) -> None:
pass pass
def tell(self) -> int: def tell(self) -> int:

View File

@ -103,16 +103,13 @@ class XpmImageFile(ImageFile.ImageFile):
self.tile = [("raw", (0, 0) + self.size, self.fp.tell(), ("P", 0, 1))] self.tile = [("raw", (0, 0) + self.size, self.fp.tell(), ("P", 0, 1))]
def load_read(self, read_bytes): def load_read(self, read_bytes: int) -> bytes:
# #
# load all image data in one chunk # load all image data in one chunk
xsize, ysize = self.size xsize, ysize = self.size
s = [None] * ysize s = [self.fp.readline()[1 : xsize + 1].ljust(xsize) for i in range(ysize)]
for i in range(ysize):
s[i] = self.fp.readline()[1 : xsize + 1].ljust(xsize)
return b"".join(s) return b"".join(s)

View File

@ -18,7 +18,7 @@ modules = {
} }
def check_module(feature): def check_module(feature: str) -> bool:
""" """
Checks if a module is available. Checks if a module is available.
@ -42,7 +42,7 @@ def check_module(feature):
return False return False
def version_module(feature): def version_module(feature: str) -> str | None:
""" """
:param feature: The module to check for. :param feature: The module to check for.
:returns: :returns:
@ -54,13 +54,10 @@ def version_module(feature):
module, ver = modules[feature] module, ver = modules[feature]
if ver is None:
return None
return getattr(__import__(module, fromlist=[ver]), ver) return getattr(__import__(module, fromlist=[ver]), ver)
def get_supported_modules(): def get_supported_modules() -> list[str]:
""" """
:returns: A list of all supported modules. :returns: A list of all supported modules.
""" """
@ -75,7 +72,7 @@ codecs = {
} }
def check_codec(feature): def check_codec(feature: str) -> bool:
""" """
Checks if a codec is available. Checks if a codec is available.
@ -92,7 +89,7 @@ def check_codec(feature):
return f"{codec}_encoder" in dir(Image.core) return f"{codec}_encoder" in dir(Image.core)
def version_codec(feature): def version_codec(feature: str) -> str | None:
""" """
:param feature: The codec to check for. :param feature: The codec to check for.
:returns: :returns:
@ -113,7 +110,7 @@ def version_codec(feature):
return version return version
def get_supported_codecs(): def get_supported_codecs() -> list[str]:
""" """
:returns: A list of all supported codecs. :returns: A list of all supported codecs.
""" """
@ -133,7 +130,7 @@ features = {
} }
def check_feature(feature): def check_feature(feature: str) -> bool | None:
""" """
Checks if a feature is available. Checks if a feature is available.
@ -157,7 +154,7 @@ def check_feature(feature):
return None return None
def version_feature(feature): def version_feature(feature: str) -> str | None:
""" """
:param feature: The feature to check for. :param feature: The feature to check for.
:returns: The version number as a string, or ``None`` if not available. :returns: The version number as a string, or ``None`` if not available.
@ -174,14 +171,14 @@ def version_feature(feature):
return getattr(__import__(module, fromlist=[ver]), ver) return getattr(__import__(module, fromlist=[ver]), ver)
def get_supported_features(): def get_supported_features() -> list[str]:
""" """
:returns: A list of all supported features. :returns: A list of all supported features.
""" """
return [f for f in features if check_feature(f)] return [f for f in features if check_feature(f)]
def check(feature): def check(feature: str) -> bool | None:
""" """
:param feature: A module, codec, or feature name. :param feature: A module, codec, or feature name.
:returns: :returns:
@ -199,7 +196,7 @@ def check(feature):
return False return False
def version(feature): def version(feature: str) -> str | None:
""" """
:param feature: :param feature:
The module, codec, or feature to check for. The module, codec, or feature to check for.
@ -215,7 +212,7 @@ def version(feature):
return None return None
def get_supported(): def get_supported() -> list[str]:
""" """
:returns: A list of all supported modules, features, and codecs. :returns: A list of all supported modules, features, and codecs.
""" """

View File

@ -128,14 +128,7 @@ PyImagingPhotoPut(
block.pixelPtr = (unsigned char *)im->block; block.pixelPtr = (unsigned char *)im->block;
TK_PHOTO_PUT_BLOCK( TK_PHOTO_PUT_BLOCK(
interp, interp, photo, &block, 0, 0, block.width, block.height, TK_PHOTO_COMPOSITE_SET);
photo,
&block,
0,
0,
block.width,
block.height,
TK_PHOTO_COMPOSITE_SET);
return TCL_OK; return TCL_OK;
} }
@ -287,7 +280,7 @@ load_tkinter_funcs(void) {
* Return 0 for success, non-zero for failure. * Return 0 for success, non-zero for failure.
*/ */
HMODULE* hMods = NULL; HMODULE *hMods = NULL;
HANDLE hProcess; HANDLE hProcess;
DWORD cbNeeded; DWORD cbNeeded;
unsigned int i; unsigned int i;
@ -313,7 +306,7 @@ load_tkinter_funcs(void) {
#endif #endif
return 1; return 1;
} }
if (!(hMods = (HMODULE*) malloc(cbNeeded))) { if (!(hMods = (HMODULE *)malloc(cbNeeded))) {
PyErr_NoMemory(); PyErr_NoMemory();
return 1; return 1;
} }
@ -345,7 +338,7 @@ load_tkinter_funcs(void) {
} else if (found_tk == 0) { } else if (found_tk == 0) {
PyErr_SetString(PyExc_RuntimeError, "Could not find Tk routines"); PyErr_SetString(PyExc_RuntimeError, "Could not find Tk routines");
} }
return (int) ((found_tcl != 1) || (found_tk != 1)); return (int)((found_tcl != 1) || (found_tk != 1));
} }
#else /* not Windows */ #else /* not Windows */
@ -400,8 +393,8 @@ _func_loader(void *lib) {
return 1; return 1;
} }
return ( return (
(TK_PHOTO_PUT_BLOCK = (TK_PHOTO_PUT_BLOCK = (Tk_PhotoPutBlock_t)_dfunc(lib, "Tk_PhotoPutBlock")) ==
(Tk_PhotoPutBlock_t)_dfunc(lib, "Tk_PhotoPutBlock")) == NULL); NULL);
} }
int int

View File

@ -110,7 +110,7 @@
#define B16(p, i) ((((int)p[(i)]) << 8) + p[(i) + 1]) #define B16(p, i) ((((int)p[(i)]) << 8) + p[(i) + 1])
#define L16(p, i) ((((int)p[(i) + 1]) << 8) + p[(i)]) #define L16(p, i) ((((int)p[(i) + 1]) << 8) + p[(i)])
#define S16(v) ((v) < 32768 ? (v) : ((v)-65536)) #define S16(v) ((v) < 32768 ? (v) : ((v) - 65536))
/* -------------------------------------------------------------------- */ /* -------------------------------------------------------------------- */
/* OBJECT ADMINISTRATION */ /* OBJECT ADMINISTRATION */
@ -533,7 +533,9 @@ getink(PyObject *color, Imaging im, char *ink) {
/* unsigned integer, single layer */ /* unsigned integer, single layer */
if (rIsInt != 1) { if (rIsInt != 1) {
if (tupleSize != 1) { if (tupleSize != 1) {
PyErr_SetString(PyExc_TypeError, "color must be int or single-element tuple"); PyErr_SetString(
PyExc_TypeError,
"color must be int or single-element tuple");
return NULL; return NULL;
} else if (!PyArg_ParseTuple(color, "L", &r)) { } else if (!PyArg_ParseTuple(color, "L", &r)) {
return NULL; return NULL;
@ -552,7 +554,9 @@ getink(PyObject *color, Imaging im, char *ink) {
a = 255; a = 255;
if (im->bands == 2) { if (im->bands == 2) {
if (tupleSize != 1 && tupleSize != 2) { if (tupleSize != 1 && tupleSize != 2) {
PyErr_SetString(PyExc_TypeError, "color must be int, or tuple of one or two elements"); PyErr_SetString(
PyExc_TypeError,
"color must be int, or tuple of one or two elements");
return NULL; return NULL;
} else if (!PyArg_ParseTuple(color, "L|i", &r, &a)) { } else if (!PyArg_ParseTuple(color, "L|i", &r, &a)) {
return NULL; return NULL;
@ -560,7 +564,10 @@ getink(PyObject *color, Imaging im, char *ink) {
g = b = r; g = b = r;
} else { } else {
if (tupleSize != 3 && tupleSize != 4) { if (tupleSize != 3 && tupleSize != 4) {
PyErr_SetString(PyExc_TypeError, "color must be int, or tuple of one, three or four elements"); PyErr_SetString(
PyExc_TypeError,
"color must be int, or tuple of one, three or four "
"elements");
return NULL; return NULL;
} else if (!PyArg_ParseTuple(color, "Lii|i", &r, &g, &b, &a)) { } else if (!PyArg_ParseTuple(color, "Lii|i", &r, &g, &b, &a)) {
return NULL; return NULL;
@ -599,7 +606,9 @@ getink(PyObject *color, Imaging im, char *ink) {
g = (UINT8)(r >> 8); g = (UINT8)(r >> 8);
r = (UINT8)r; r = (UINT8)r;
} else if (tupleSize != 3) { } else if (tupleSize != 3) {
PyErr_SetString(PyExc_TypeError, "color must be int, or tuple of one or three elements"); PyErr_SetString(
PyExc_TypeError,
"color must be int, or tuple of one or three elements");
return NULL; return NULL;
} else if (!PyArg_ParseTuple(color, "iiL", &b, &g, &r)) { } else if (!PyArg_ParseTuple(color, "iiL", &b, &g, &r)) {
return NULL; return NULL;
@ -1537,14 +1546,14 @@ _putdata(ImagingObject *self, PyObject *args) {
return NULL; return NULL;
} }
#define set_value_to_item(seq, i) \ #define set_value_to_item(seq, i) \
op = PySequence_Fast_GET_ITEM(seq, i); \ op = PySequence_Fast_GET_ITEM(seq, i); \
if (PySequence_Check(op)) { \ if (PySequence_Check(op)) { \
PyErr_SetString(PyExc_TypeError, "sequence must be flattened"); \ PyErr_SetString(PyExc_TypeError, "sequence must be flattened"); \
return NULL; \ return NULL; \
} else { \ } else { \
value = PyFloat_AsDouble(op); \ value = PyFloat_AsDouble(op); \
} }
if (image->image8) { if (image->image8) {
if (PyBytes_Check(data)) { if (PyBytes_Check(data)) {
unsigned char *p; unsigned char *p;
@ -1596,8 +1605,10 @@ if (PySequence_Check(op)) { \
value = value * scale + offset; value = value * scale + offset;
} }
if (image->type == IMAGING_TYPE_SPECIAL) { if (image->type == IMAGING_TYPE_SPECIAL) {
image->image8[y][x * 2 + (bigendian ? 1 : 0)] = CLIP8((int)value % 256); image->image8[y][x * 2 + (bigendian ? 1 : 0)] =
image->image8[y][x * 2 + (bigendian ? 0 : 1)] = CLIP8((int)value >> 8); CLIP8((int)value % 256);
image->image8[y][x * 2 + (bigendian ? 0 : 1)] =
CLIP8((int)value >> 8);
} else { } else {
image->image8[y][x] = (UINT8)CLIP8(value); image->image8[y][x] = (UINT8)CLIP8(value);
} }
@ -1639,8 +1650,7 @@ if (PySequence_Check(op)) { \
for (i = x = y = 0; i < n; i++) { for (i = x = y = 0; i < n; i++) {
double value; double value;
set_value_to_item(seq, i); set_value_to_item(seq, i);
IMAGING_PIXEL_INT32(image, x, y) = IMAGING_PIXEL_INT32(image, x, y) = (INT32)(value * scale + offset);
(INT32)(value * scale + offset);
if (++x >= (int)image->xsize) { if (++x >= (int)image->xsize) {
x = 0, y++; x = 0, y++;
} }
@ -2785,8 +2795,8 @@ _font_getmask(ImagingFontObject *self, PyObject *args) {
glyph = &self->glyphs[text[i]]; glyph = &self->glyphs[text[i]];
if (i == 0 || text[i] != text[i - 1]) { if (i == 0 || text[i] != text[i - 1]) {
ImagingDelete(bitmap); ImagingDelete(bitmap);
bitmap = bitmap = ImagingCrop(
ImagingCrop(self->bitmap, glyph->sx0, glyph->sy0, glyph->sx1, glyph->sy1); self->bitmap, glyph->sx0, glyph->sy0, glyph->sx1, glyph->sy1);
if (!bitmap) { if (!bitmap) {
goto failed; goto failed;
} }
@ -3315,7 +3325,8 @@ _draw_polygon(ImagingDrawObject *self, PyObject *args) {
free(xy); free(xy);
if (ImagingDrawPolygon(self->image->image, n, ixy, &ink, fill, width, self->blend) < 0) { if (ImagingDrawPolygon(self->image->image, n, ixy, &ink, fill, width, self->blend) <
0) {
free(ixy); free(ixy);
return NULL; return NULL;
} }
@ -4411,7 +4422,8 @@ setup_module(PyObject *m) {
PyModule_AddObject(m, "HAVE_XCB", have_xcb); PyModule_AddObject(m, "HAVE_XCB", have_xcb);
PyObject *pillow_version = PyUnicode_FromString(version); PyObject *pillow_version = PyUnicode_FromString(version);
PyDict_SetItemString(d, "PILLOW_VERSION", pillow_version ? pillow_version : Py_None); PyDict_SetItemString(
d, "PILLOW_VERSION", pillow_version ? pillow_version : Py_None);
Py_XDECREF(pillow_version); Py_XDECREF(pillow_version);
return 0; return 0;

View File

@ -213,11 +213,8 @@ cms_transform_dealloc(CmsTransformObject *self) {
static cmsUInt32Number static cmsUInt32Number
findLCMStype(char *PILmode) { findLCMStype(char *PILmode) {
if ( if (strcmp(PILmode, "RGB") == 0 || strcmp(PILmode, "RGBA") == 0 ||
strcmp(PILmode, "RGB") == 0 || strcmp(PILmode, "RGBX") == 0) {
strcmp(PILmode, "RGBA") == 0 ||
strcmp(PILmode, "RGBX") == 0
) {
return TYPE_RGBA_8; return TYPE_RGBA_8;
} }
if (strcmp(PILmode, "RGBA;16B") == 0) { if (strcmp(PILmode, "RGBA;16B") == 0) {
@ -232,10 +229,7 @@ findLCMStype(char *PILmode) {
if (strcmp(PILmode, "L;16B") == 0) { if (strcmp(PILmode, "L;16B") == 0) {
return TYPE_GRAY_16_SE; return TYPE_GRAY_16_SE;
} }
if ( if (strcmp(PILmode, "YCCA") == 0 || strcmp(PILmode, "YCC") == 0) {
strcmp(PILmode, "YCCA") == 0 ||
strcmp(PILmode, "YCC") == 0
) {
return TYPE_YCbCr_8; return TYPE_YCbCr_8;
} }
if (strcmp(PILmode, "LAB") == 0) { if (strcmp(PILmode, "LAB") == 0) {
@ -391,7 +385,7 @@ _buildTransform(
iRenderingIntent, iRenderingIntent,
cmsFLAGS); cmsFLAGS);
Py_END_ALLOW_THREADS Py_END_ALLOW_THREADS;
if (!hTransform) { if (!hTransform) {
PyErr_SetString(PyExc_ValueError, "cannot build transform"); PyErr_SetString(PyExc_ValueError, "cannot build transform");
@ -425,7 +419,7 @@ _buildProofTransform(
iProofIntent, iProofIntent,
cmsFLAGS); cmsFLAGS);
Py_END_ALLOW_THREADS Py_END_ALLOW_THREADS;
if (!hTransform) { if (!hTransform) {
PyErr_SetString(PyExc_ValueError, "cannot build proof transform"); PyErr_SetString(PyExc_ValueError, "cannot build proof transform");
@ -622,7 +616,7 @@ cms_profile_is_intent_supported(CmsProfileObject *self, PyObject *args) {
static PyObject * static PyObject *
cms_get_display_profile_win32(PyObject *self, PyObject *args) { cms_get_display_profile_win32(PyObject *self, PyObject *args) {
char filename[MAX_PATH]; char filename[MAX_PATH];
cmsUInt32Number filename_size; DWORD filename_size;
BOOL ok; BOOL ok;
HANDLE handle = 0; HANDLE handle = 0;

View File

@ -47,17 +47,17 @@
; ;
#ifdef HAVE_RAQM #ifdef HAVE_RAQM
# ifdef HAVE_RAQM_SYSTEM #ifdef HAVE_RAQM_SYSTEM
# include <raqm.h> #include <raqm.h>
# else #else
# include "thirdparty/raqm/raqm.h" #include "thirdparty/raqm/raqm.h"
# ifdef HAVE_FRIBIDI_SYSTEM #ifdef HAVE_FRIBIDI_SYSTEM
# include <fribidi.h> #include <fribidi.h>
# else #else
# include "thirdparty/fribidi-shim/fribidi.h" #include "thirdparty/fribidi-shim/fribidi.h"
# include <hb.h> #include <hb.h>
# endif #endif
# endif #endif
#endif #endif
static int have_raqm = 0; static int have_raqm = 0;
@ -490,8 +490,7 @@ text_layout(
size_t count; size_t count;
#ifdef HAVE_RAQM #ifdef HAVE_RAQM
if (have_raqm && self->layout_engine == LAYOUT_RAQM) { if (have_raqm && self->layout_engine == LAYOUT_RAQM) {
count = text_layout_raqm( count = text_layout_raqm(string, self, dir, features, lang, glyph_info);
string, self, dir, features, lang, glyph_info);
} else } else
#endif #endif
{ {
@ -550,7 +549,17 @@ font_getlength(FontObject *self, PyObject *args) {
} }
static int static int
bounding_box_and_anchors(FT_Face face, const char *anchor, int horizontal_dir, GlyphInfo *glyph_info, size_t count, int load_flags, int *width, int *height, int *x_offset, int *y_offset) { bounding_box_and_anchors(
FT_Face face,
const char *anchor,
int horizontal_dir,
GlyphInfo *glyph_info,
size_t count,
int load_flags,
int *width,
int *height,
int *x_offset,
int *y_offset) {
int position; /* pen position along primary axis, in 26.6 precision */ int position; /* pen position along primary axis, in 26.6 precision */
int advanced; /* pen position along primary axis, in pixels */ int advanced; /* pen position along primary axis, in pixels */
int px, py; /* position of current glyph, in pixels */ int px, py; /* position of current glyph, in pixels */
@ -558,8 +567,8 @@ bounding_box_and_anchors(FT_Face face, const char *anchor, int horizontal_dir, G
int x_anchor, y_anchor; /* offset of point drawn at (0, 0), in pixels */ int x_anchor, y_anchor; /* offset of point drawn at (0, 0), in pixels */
int error; int error;
FT_Glyph glyph; FT_Glyph glyph;
FT_BBox bbox; /* glyph bounding box */ FT_BBox bbox; /* glyph bounding box */
size_t i; /* glyph_info index */ size_t i; /* glyph_info index */
/* /*
* text bounds are given by: * text bounds are given by:
* - bounding boxes of individual glyphs * - bounding boxes of individual glyphs
@ -654,8 +663,7 @@ bounding_box_and_anchors(FT_Face face, const char *anchor, int horizontal_dir, G
break; break;
case 'm': // middle (ascender + descender) / 2 case 'm': // middle (ascender + descender) / 2
y_anchor = PIXEL( y_anchor = PIXEL(
(face->size->metrics.ascender + (face->size->metrics.ascender + face->size->metrics.descender) /
face->size->metrics.descender) /
2); 2);
break; break;
case 's': // horizontal baseline case 's': // horizontal baseline
@ -719,7 +727,7 @@ bad_anchor:
static PyObject * static PyObject *
font_getsize(FontObject *self, PyObject *args) { font_getsize(FontObject *self, PyObject *args) {
int width, height, x_offset, y_offset; int width, height, x_offset, y_offset;
int load_flags; /* FreeType load_flags parameter */ int load_flags; /* FreeType load_flags parameter */
int error; int error;
GlyphInfo *glyph_info = NULL; /* computed text layout */ GlyphInfo *glyph_info = NULL; /* computed text layout */
size_t count; /* glyph_info length */ size_t count; /* glyph_info length */
@ -758,7 +766,17 @@ font_getsize(FontObject *self, PyObject *args) {
load_flags |= FT_LOAD_COLOR; load_flags |= FT_LOAD_COLOR;
} }
error = bounding_box_and_anchors(self->face, anchor, horizontal_dir, glyph_info, count, load_flags, &width, &height, &x_offset, &y_offset); error = bounding_box_and_anchors(
self->face,
anchor,
horizontal_dir,
glyph_info,
count,
load_flags,
&width,
&height,
&x_offset,
&y_offset);
if (glyph_info) { if (glyph_info) {
PyMem_Free(glyph_info); PyMem_Free(glyph_info);
glyph_info = NULL; glyph_info = NULL;
@ -767,12 +785,7 @@ font_getsize(FontObject *self, PyObject *args) {
return NULL; return NULL;
} }
return Py_BuildValue( return Py_BuildValue("(ii)(ii)", width, height, x_offset, y_offset);
"(ii)(ii)",
width,
height,
x_offset,
y_offset);
} }
static PyObject * static PyObject *
@ -869,7 +882,17 @@ font_render(FontObject *self, PyObject *args) {
horizontal_dir = dir && strcmp(dir, "ttb") == 0 ? 0 : 1; horizontal_dir = dir && strcmp(dir, "ttb") == 0 ? 0 : 1;
error = bounding_box_and_anchors(self->face, anchor, horizontal_dir, glyph_info, count, load_flags, &width, &height, &x_offset, &y_offset); error = bounding_box_and_anchors(
self->face,
anchor,
horizontal_dir,
glyph_info,
count,
load_flags,
&width,
&height,
&x_offset,
&y_offset);
if (error) { if (error) {
PyMem_Del(glyph_info); PyMem_Del(glyph_info);
return NULL; return NULL;
@ -1066,17 +1089,26 @@ font_render(FontObject *self, PyObject *args) {
/* paste only if source has data */ /* paste only if source has data */
if (src_alpha > 0) { if (src_alpha > 0) {
/* unpremultiply BGRa */ /* unpremultiply BGRa */
int src_red = CLIP8((255 * (int)source[k * 4 + 2]) / src_alpha); int src_red =
int src_green = CLIP8((255 * (int)source[k * 4 + 1]) / src_alpha); CLIP8((255 * (int)source[k * 4 + 2]) / src_alpha);
int src_blue = CLIP8((255 * (int)source[k * 4 + 0]) / src_alpha); int src_green =
CLIP8((255 * (int)source[k * 4 + 1]) / src_alpha);
int src_blue =
CLIP8((255 * (int)source[k * 4 + 0]) / src_alpha);
/* blend required if target has data */ /* blend required if target has data */
if (target[k * 4 + 3] > 0) { if (target[k * 4 + 3] > 0) {
/* blend RGBA colors */ /* blend RGBA colors */
target[k * 4 + 0] = BLEND(src_alpha, target[k * 4 + 0], src_red, tmp); target[k * 4 + 0] =
target[k * 4 + 1] = BLEND(src_alpha, target[k * 4 + 1], src_green, tmp); BLEND(src_alpha, target[k * 4 + 0], src_red, tmp);
target[k * 4 + 2] = BLEND(src_alpha, target[k * 4 + 2], src_blue, tmp); target[k * 4 + 1] =
target[k * 4 + 3] = CLIP8(src_alpha + MULDIV255(target[k * 4 + 3], (255 - src_alpha), tmp)); BLEND(src_alpha, target[k * 4 + 1], src_green, tmp);
target[k * 4 + 2] =
BLEND(src_alpha, target[k * 4 + 2], src_blue, tmp);
target[k * 4 + 3] = CLIP8(
src_alpha +
MULDIV255(
target[k * 4 + 3], (255 - src_alpha), tmp));
} else { } else {
/* paste unpremultiplied RGBA values */ /* paste unpremultiplied RGBA values */
target[k * 4 + 0] = src_red; target[k * 4 + 0] = src_red;
@ -1093,10 +1125,16 @@ font_render(FontObject *self, PyObject *args) {
unsigned int src_alpha = source[k] * convert_scale; unsigned int src_alpha = source[k] * convert_scale;
if (src_alpha > 0) { if (src_alpha > 0) {
if (target[k * 4 + 3] > 0) { if (target[k * 4 + 3] > 0) {
target[k * 4 + 0] = BLEND(src_alpha, target[k * 4 + 0], ink[0], tmp); target[k * 4 + 0] = BLEND(
target[k * 4 + 1] = BLEND(src_alpha, target[k * 4 + 1], ink[1], tmp); src_alpha, target[k * 4 + 0], ink[0], tmp);
target[k * 4 + 2] = BLEND(src_alpha, target[k * 4 + 2], ink[2], tmp); target[k * 4 + 1] = BLEND(
target[k * 4 + 3] = CLIP8(src_alpha + MULDIV255(target[k * 4 + 3], (255 - src_alpha), tmp)); src_alpha, target[k * 4 + 1], ink[1], tmp);
target[k * 4 + 2] = BLEND(
src_alpha, target[k * 4 + 2], ink[2], tmp);
target[k * 4 + 3] = CLIP8(
src_alpha +
MULDIV255(
target[k * 4 + 3], (255 - src_alpha), tmp));
} else { } else {
target[k * 4 + 0] = ink[0]; target[k * 4 + 0] = ink[0];
target[k * 4 + 1] = ink[1]; target[k * 4 + 1] = ink[1];
@ -1109,7 +1147,13 @@ font_render(FontObject *self, PyObject *args) {
for (k = x0; k < x1; k++) { for (k = x0; k < x1; k++) {
unsigned int src_alpha = source[k] * convert_scale; unsigned int src_alpha = source[k] * convert_scale;
if (src_alpha > 0) { if (src_alpha > 0) {
target[k] = target[k] > 0 ? CLIP8(src_alpha + MULDIV255(target[k], (255 - src_alpha), tmp)) : src_alpha; target[k] =
target[k] > 0
? CLIP8(
src_alpha +
MULDIV255(
target[k], (255 - src_alpha), tmp))
: src_alpha;
} }
} }
} }
@ -1249,7 +1293,8 @@ font_getvaraxes(FontObject *self) {
if (name.name_id == axis.strid) { if (name.name_id == axis.strid) {
axis_name = Py_BuildValue("y#", name.string, name.string_len); axis_name = Py_BuildValue("y#", name.string, name.string_len);
PyDict_SetItemString(list_axis, "name", axis_name ? axis_name : Py_None); PyDict_SetItemString(
list_axis, "name", axis_name ? axis_name : Py_None);
Py_XDECREF(axis_name); Py_XDECREF(axis_name);
break; break;
} }
@ -1299,7 +1344,7 @@ font_setvaraxes(FontObject *self, PyObject *args) {
} }
num_coords = PyObject_Length(axes); num_coords = PyObject_Length(axes);
coords = (FT_Fixed*)malloc(num_coords * sizeof(FT_Fixed)); coords = (FT_Fixed *)malloc(num_coords * sizeof(FT_Fixed));
if (coords == NULL) { if (coords == NULL) {
return PyErr_NoMemory(); return PyErr_NoMemory();
} }

View File

@ -716,7 +716,7 @@ PyImaging_DrawWmf(PyObject *self, PyObject *args) {
HDC dc; HDC dc;
RECT rect; RECT rect;
PyObject *buffer = NULL; PyObject *buffer = NULL;
char *ptr; void *ptr;
char *data; char *data;
Py_ssize_t datasize; Py_ssize_t datasize;

View File

@ -1163,8 +1163,10 @@ PyImaging_JpegEncoderNew(PyObject *self, PyObject *args) {
((JPEGENCODERSTATE *)encoder->state.context)->streamtype = streamtype; ((JPEGENCODERSTATE *)encoder->state.context)->streamtype = streamtype;
((JPEGENCODERSTATE *)encoder->state.context)->xdpi = xdpi; ((JPEGENCODERSTATE *)encoder->state.context)->xdpi = xdpi;
((JPEGENCODERSTATE *)encoder->state.context)->ydpi = ydpi; ((JPEGENCODERSTATE *)encoder->state.context)->ydpi = ydpi;
((JPEGENCODERSTATE *)encoder->state.context)->restart_marker_blocks = restart_marker_blocks; ((JPEGENCODERSTATE *)encoder->state.context)->restart_marker_blocks =
((JPEGENCODERSTATE *)encoder->state.context)->restart_marker_rows = restart_marker_rows; restart_marker_blocks;
((JPEGENCODERSTATE *)encoder->state.context)->restart_marker_rows =
restart_marker_rows;
((JPEGENCODERSTATE *)encoder->state.context)->comment = comment; ((JPEGENCODERSTATE *)encoder->state.context)->comment = comment;
((JPEGENCODERSTATE *)encoder->state.context)->comment_size = comment_size; ((JPEGENCODERSTATE *)encoder->state.context)->comment_size = comment_size;
((JPEGENCODERSTATE *)encoder->state.context)->extra = extra; ((JPEGENCODERSTATE *)encoder->state.context)->extra = extra;
@ -1333,9 +1335,7 @@ PyImaging_Jpeg2KEncoderNew(PyObject *self, PyObject *args) {
if (comment && comment_size > 0) { if (comment && comment_size > 0) {
/* Size is stored as as an uint16, subtract 4 bytes for the header */ /* Size is stored as as an uint16, subtract 4 bytes for the header */
if (comment_size >= 65532) { if (comment_size >= 65532) {
PyErr_SetString( PyErr_SetString(PyExc_ValueError, "JPEG 2000 comment is too long");
PyExc_ValueError,
"JPEG 2000 comment is too long");
Py_DECREF(encoder); Py_DECREF(encoder);
return NULL; return NULL;
} }

View File

@ -185,11 +185,11 @@ put_pixel_32(Imaging im, int x, int y, const void *color) {
void void
ImagingAccessInit() { ImagingAccessInit() {
#define ADD(mode_, get_pixel_, put_pixel_) \ #define ADD(mode_, get_pixel_, put_pixel_) \
{ \ { \
ImagingAccess access = add_item(mode_); \ ImagingAccess access = add_item(mode_); \
access->get_pixel = get_pixel_; \ access->get_pixel = get_pixel_; \
access->put_pixel = put_pixel_; \ access->put_pixel = put_pixel_; \
} }
/* populate access table */ /* populate access table */

View File

@ -83,7 +83,6 @@ decode_bc1_color(rgba *dst, const UINT8 *src, int separate_alpha) {
g1 = p[1].g; g1 = p[1].g;
b1 = p[1].b; b1 = p[1].b;
/* NOTE: BC2 and BC3 reuse BC1 color blocks but always act like c0 > c1 */ /* NOTE: BC2 and BC3 reuse BC1 color blocks but always act like c0 > c1 */
if (col.c0 > col.c1 || separate_alpha) { if (col.c0 > col.c1 || separate_alpha) {
p[2].r = (2 * r0 + 1 * r1) / 3; p[2].r = (2 * r0 + 1 * r1) / 3;
@ -354,8 +353,7 @@ decode_bc7_block(rgba *col, const UINT8 *src) {
} }
return; return;
} }
while (!(mode & (1 << bit++))) while (!(mode & (1 << bit++)));
;
mode = bit - 1; mode = bit - 1;
info = &bc7_modes[mode]; info = &bc7_modes[mode];
/* color selection bits: {subset}{endpoint} */ /* color selection bits: {subset}{endpoint} */
@ -546,7 +544,7 @@ static const UINT8 bc6_bit_packings[][75] = {
21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 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, 48, 49, 50, 51, 52, 10, 112, 113, 114, 115, 64, 65, 66, 67, 26,
176, 160, 161, 162, 163, 80, 81, 82, 83, 42, 177, 128, 129, 130, 131, 176, 160, 161, 162, 163, 80, 81, 82, 83, 42, 177, 128, 129, 130, 131,
96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179}, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, {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, 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, 48, 49, 50, 51, 10, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68,
@ -684,7 +682,7 @@ bc6_clamp(float value) {
} else if (value > 1.0f) { } else if (value > 1.0f) {
return 255; return 255;
} else { } else {
return (UINT8) (value * 255.0f); return (UINT8)(value * 255.0f);
} }
} }
@ -826,7 +824,13 @@ put_block(Imaging im, ImagingCodecState state, const char *col, int sz, int C) {
static int static int
decode_bcn( decode_bcn(
Imaging im, ImagingCodecState state, const UINT8 *src, int bytes, int N, int C, char *pixel_format) { Imaging im,
ImagingCodecState state,
const UINT8 *src,
int bytes,
int N,
int C,
char *pixel_format) {
int ymax = state->ysize + state->yoff; int ymax = state->ysize + state->yoff;
const UINT8 *ptr = src; const UINT8 *ptr = src;
switch (N) { switch (N) {
@ -849,8 +853,7 @@ decode_bcn(
DECODE_LOOP(2, 16, rgba); DECODE_LOOP(2, 16, rgba);
DECODE_LOOP(3, 16, rgba); DECODE_LOOP(3, 16, rgba);
DECODE_LOOP(4, 8, lum); DECODE_LOOP(4, 8, lum);
case 5: case 5: {
{
int sign = strcmp(pixel_format, "BC5S") == 0 ? 1 : 0; int sign = strcmp(pixel_format, "BC5S") == 0 ? 1 : 0;
while (bytes >= 16) { while (bytes >= 16) {
rgba col[16]; rgba col[16];
@ -865,8 +868,7 @@ decode_bcn(
} }
break; break;
} }
case 6: case 6: {
{
int sign = strcmp(pixel_format, "BC6HS") == 0 ? 1 : 0; int sign = strcmp(pixel_format, "BC6HS") == 0 ? 1 : 0;
while (bytes >= 16) { while (bytes >= 16) {
rgba col[16]; rgba col[16];
@ -880,7 +882,7 @@ decode_bcn(
} }
break; break;
} }
DECODE_LOOP(7, 16, rgba); DECODE_LOOP(7, 16, rgba);
#undef DECODE_LOOP #undef DECODE_LOOP
} }
return (int)(ptr - src); return (int)(ptr - src);

View File

@ -313,12 +313,12 @@ _gaussian_blur_radius(float radius, int passes) {
} }
Imaging Imaging
ImagingGaussianBlur(Imaging imOut, Imaging imIn, float xradius, float yradius, int passes) { ImagingGaussianBlur(
Imaging imOut, Imaging imIn, float xradius, float yradius, int passes) {
return ImagingBoxBlur( return ImagingBoxBlur(
imOut, imOut,
imIn, imIn,
_gaussian_blur_radius(xradius, passes), _gaussian_blur_radius(xradius, passes),
_gaussian_blur_radius(yradius, passes), _gaussian_blur_radius(yradius, passes),
passes passes);
);
} }

View File

@ -518,8 +518,8 @@ rgba2rgb_(UINT8 *out, const UINT8 *in, int xsize) {
/* /*
* Conversion of RGB + single transparent color either to * Conversion of RGB + single transparent color either to
* RGBA or LA, where any pixel matching the color will have the alpha channel set to 0, or * RGBA or LA, where any pixel matching the color will have the alpha channel set to 0,
* RGBa or La, where any pixel matching the color will have all channels set to 0 * or RGBa or La, where any pixel matching the color will have all channels set to 0
*/ */
static void static void
@ -1676,7 +1676,8 @@ convert(
return (Imaging)ImagingError_ValueError("conversion not supported"); return (Imaging)ImagingError_ValueError("conversion not supported");
#else #else
static char buf[100]; static char buf[100];
snprintf(buf, 100, "conversion from %.10s to %.10s not supported", imIn->mode, mode); snprintf(
buf, 100, "conversion from %.10s to %.10s not supported", imIn->mode, mode);
return (Imaging)ImagingError_ValueError(buf); return (Imaging)ImagingError_ValueError(buf);
#endif #endif
} }
@ -1720,25 +1721,24 @@ ImagingConvertTransparent(Imaging imIn, const char *mode, int r, int g, int b) {
return (Imaging)ImagingError_ModeError(); return (Imaging)ImagingError_ModeError();
} }
if (strcmp(imIn->mode, "RGB") == 0 && (strcmp(mode, "RGBA") == 0 || strcmp(mode, "RGBa") == 0)) { if (strcmp(imIn->mode, "RGB") == 0 &&
(strcmp(mode, "RGBA") == 0 || strcmp(mode, "RGBa") == 0)) {
convert = rgb2rgba; convert = rgb2rgba;
if (strcmp(mode, "RGBa") == 0) { if (strcmp(mode, "RGBa") == 0) {
premultiplied = 1; premultiplied = 1;
} }
} else if (strcmp(imIn->mode, "RGB") == 0 && (strcmp(mode, "LA") == 0 || strcmp(mode, "La") == 0)) { } else if (
strcmp(imIn->mode, "RGB") == 0 &&
(strcmp(mode, "LA") == 0 || strcmp(mode, "La") == 0)) {
convert = rgb2la; convert = rgb2la;
source_transparency = 1; source_transparency = 1;
if (strcmp(mode, "La") == 0) { if (strcmp(mode, "La") == 0) {
premultiplied = 1; premultiplied = 1;
} }
} else if ((strcmp(imIn->mode, "1") == 0 || } else if (
strcmp(imIn->mode, "I") == 0 || (strcmp(imIn->mode, "1") == 0 || strcmp(imIn->mode, "I") == 0 ||
strcmp(imIn->mode, "I;16") == 0 || strcmp(imIn->mode, "I;16") == 0 || strcmp(imIn->mode, "L") == 0) &&
strcmp(imIn->mode, "L") == 0 (strcmp(mode, "RGBA") == 0 || strcmp(mode, "LA") == 0)) {
) && (
strcmp(mode, "RGBA") == 0 ||
strcmp(mode, "LA") == 0
)) {
if (strcmp(imIn->mode, "1") == 0) { if (strcmp(imIn->mode, "1") == 0) {
convert = bit2rgb; convert = bit2rgb;
} else if (strcmp(imIn->mode, "I") == 0) { } else if (strcmp(imIn->mode, "I") == 0) {

View File

@ -94,8 +94,8 @@ ImagingNewDIB(const char *mode, int xsize, int ysize) {
return (ImagingDIB)ImagingError_MemoryError(); return (ImagingDIB)ImagingError_MemoryError();
} }
dib->bitmap = dib->bitmap = CreateDIBSection(
CreateDIBSection(dib->dc, dib->info, DIB_RGB_COLORS, &dib->bits, NULL, 0); dib->dc, dib->info, DIB_RGB_COLORS, (void **)&dib->bits, NULL, 0);
if (!dib->bitmap) { if (!dib->bitmap) {
free(dib->info); free(dib->info);
free(dib); free(dib);

View File

@ -48,7 +48,7 @@
* This guarantees that ROUND_UP|DOWN(f) == -ROUND_UP|DOWN(-f) * This guarantees that ROUND_UP|DOWN(f) == -ROUND_UP|DOWN(-f)
*/ */
#define ROUND_UP(f) ((int)((f) >= 0.0 ? floor((f) + 0.5F) : -floor(fabs(f) + 0.5F))) #define ROUND_UP(f) ((int)((f) >= 0.0 ? floor((f) + 0.5F) : -floor(fabs(f) + 0.5F)))
#define ROUND_DOWN(f) ((int)((f) >= 0.0 ? ceil((f)-0.5F) : -ceil(fabs(f) - 0.5F))) #define ROUND_DOWN(f) ((int)((f) >= 0.0 ? ceil((f) - 0.5F) : -ceil(fabs(f) - 0.5F)))
/* -------------------------------------------------------------------- */ /* -------------------------------------------------------------------- */
/* Primitives */ /* Primitives */
@ -439,7 +439,14 @@ draw_horizontal_lines(
* Filled polygon draw function using scan line algorithm. * Filled polygon draw function using scan line algorithm.
*/ */
static inline int static inline int
polygon_generic(Imaging im, int n, Edge *e, int ink, int eofill, hline_handler hline, int hasAlpha) { polygon_generic(
Imaging im,
int n,
Edge *e,
int ink,
int eofill,
hline_handler hline,
int hasAlpha) {
Edge **edge_table; Edge **edge_table;
float *xx; float *xx;
int edge_count = 0; int edge_count = 0;
@ -499,7 +506,7 @@ polygon_generic(Imaging im, int n, Edge *e, int ink, int eofill, hline_handler h
// Needed to draw consistent polygons // Needed to draw consistent polygons
xx[j] = xx[j - 1]; xx[j] = xx[j - 1];
j++; j++;
} else if (current->dx != 0 && roundf(xx[j-1]) == xx[j-1]) { } else if (current->dx != 0 && roundf(xx[j - 1]) == xx[j - 1]) {
// Connect discontiguous corners // Connect discontiguous corners
for (k = 0; k < i; k++) { for (k = 0; k < i; k++) {
Edge *other_edge = edge_table[k]; Edge *other_edge = edge_table[k];
@ -510,23 +517,38 @@ polygon_generic(Imaging im, int n, Edge *e, int ink, int eofill, hline_handler h
// Check if the two edges join to make a corner // Check if the two edges join to make a corner
if (((ymin == current->ymin && ymin == other_edge->ymin) || if (((ymin == current->ymin && ymin == other_edge->ymin) ||
(ymin == current->ymax && ymin == other_edge->ymax)) && (ymin == current->ymax && ymin == other_edge->ymax)) &&
xx[j-1] == (ymin - other_edge->y0) * other_edge->dx + other_edge->x0) { xx[j - 1] == (ymin - other_edge->y0) * other_edge->dx +
other_edge->x0) {
// Determine points from the edges on the next row // Determine points from the edges on the next row
// Or if this is the last row, check the previous row // Or if this is the last row, check the previous row
int offset = ymin == ymax ? -1 : 1; int offset = ymin == ymax ? -1 : 1;
adjacent_line_x = (ymin + offset - current->y0) * current->dx + current->x0; adjacent_line_x =
adjacent_line_x_other_edge = (ymin + offset - other_edge->y0) * other_edge->dx + other_edge->x0; (ymin + offset - current->y0) * current->dx +
current->x0;
adjacent_line_x_other_edge =
(ymin + offset - other_edge->y0) * other_edge->dx +
other_edge->x0;
if (ymin == current->ymax) { if (ymin == current->ymax) {
if (current->dx > 0) { if (current->dx > 0) {
xx[k] = fmax(adjacent_line_x, adjacent_line_x_other_edge) + 1; xx[k] = fmax(
adjacent_line_x,
adjacent_line_x_other_edge) +
1;
} else { } else {
xx[k] = fmin(adjacent_line_x, adjacent_line_x_other_edge) - 1; xx[k] = fmin(
adjacent_line_x,
adjacent_line_x_other_edge) -
1;
} }
} else { } else {
if (current->dx > 0) { if (current->dx > 0) {
xx[k] = fmin(adjacent_line_x, adjacent_line_x_other_edge); xx[k] = fmin(
adjacent_line_x, adjacent_line_x_other_edge);
} else { } else {
xx[k] = fmax(adjacent_line_x, adjacent_line_x_other_edge) + 1; xx[k] = fmax(
adjacent_line_x,
adjacent_line_x_other_edge) +
1;
} }
} }
break; break;
@ -552,7 +574,8 @@ polygon_generic(Imaging im, int n, Edge *e, int ink, int eofill, hline_handler h
int x_start = ROUND_UP(xx[i - 1]); int x_start = ROUND_UP(xx[i - 1]);
if (x_pos > x_start) { if (x_pos > x_start) {
// Line would be partway through x_pos, so increase the starting point // Line would be partway through x_pos, so increase the starting
// point
x_start = x_pos; x_start = x_pos;
if (x_end < x_start) { if (x_end < x_start) {
// Line would now end before it started // Line would now end before it started
@ -776,7 +799,8 @@ ImagingDrawRectangle(
} }
int int
ImagingDrawPolygon(Imaging im, int count, int *xy, const void *ink_, int fill, int width, int op) { ImagingDrawPolygon(
Imaging im, int count, int *xy, const void *ink_, int fill, int width, int op) {
int i, n, x0, y0, x1, y1; int i, n, x0, y0, x1, y1;
DRAW *draw; DRAW *draw;
INT32 ink; INT32 ink;
@ -803,7 +827,7 @@ ImagingDrawPolygon(Imaging im, int count, int *xy, const void *ink_, int fill, i
if (y0 == y1 && i != 0 && y0 == xy[i * 2 - 1]) { if (y0 == y1 && i != 0 && y0 == xy[i * 2 - 1]) {
// This is a horizontal line, // This is a horizontal line,
// that immediately follows another horizontal line // that immediately follows another horizontal line
Edge *last_e = &e[n-1]; Edge *last_e = &e[n - 1];
if (x1 > x0 && x0 > xy[i * 2 - 2]) { if (x1 > x0 && x0 > xy[i * 2 - 2]) {
// They are both increasing in x // They are both increasing in x
last_e->xmax = x1; last_e->xmax = x1;
@ -826,14 +850,24 @@ ImagingDrawPolygon(Imaging im, int count, int *xy, const void *ink_, int fill, i
/* Outline */ /* Outline */
if (width == 1) { if (width == 1) {
for (i = 0; i < count - 1; i++) { for (i = 0; i < count - 1; i++) {
draw->line(im, xy[i * 2], xy[i * 2 + 1], xy[i * 2 + 2], xy[i * 2 + 3], ink); draw->line(
im, xy[i * 2], xy[i * 2 + 1], xy[i * 2 + 2], xy[i * 2 + 3], ink);
} }
draw->line(im, xy[i * 2], xy[i * 2 + 1], xy[0], xy[1], ink); draw->line(im, xy[i * 2], xy[i * 2 + 1], xy[0], xy[1], ink);
} else { } else {
for (i = 0; i < count - 1; i++) { for (i = 0; i < count - 1; i++) {
ImagingDrawWideLine(im, xy[i * 2], xy[i * 2 + 1], xy[i * 2 + 2], xy[i * 2 + 3], ink_, width, op); ImagingDrawWideLine(
im,
xy[i * 2],
xy[i * 2 + 1],
xy[i * 2 + 2],
xy[i * 2 + 3],
ink_,
width,
op);
} }
ImagingDrawWideLine(im, xy[i * 2], xy[i * 2 + 1], xy[0], xy[1], ink_, width, op); ImagingDrawWideLine(
im, xy[i * 2], xy[i * 2 + 1], xy[0], xy[1], ink_, width, op);
} }
} }

View File

@ -106,7 +106,7 @@ ImagingExpand(Imaging imIn, int xmargin, int ymargin) {
void void
ImagingFilter3x3(Imaging imOut, Imaging im, const float *kernel, float offset) { ImagingFilter3x3(Imaging imOut, Imaging im, const float *kernel, float offset) {
#define KERNEL1x3(in0, x, kernel, d) \ #define KERNEL1x3(in0, x, kernel, d) \
(_i2f(in0[x - d]) * (kernel)[0] + _i2f(in0[x]) * (kernel)[1] + \ (_i2f(in0[x - d]) * (kernel)[0] + _i2f(in0[x]) * (kernel)[1] + \
_i2f(in0[x + d]) * (kernel)[2]) _i2f(in0[x + d]) * (kernel)[2])
@ -224,10 +224,9 @@ ImagingFilter3x3(Imaging imOut, Imaging im, const float *kernel, float offset) {
void void
ImagingFilter5x5(Imaging imOut, Imaging im, const float *kernel, float offset) { ImagingFilter5x5(Imaging imOut, Imaging im, const float *kernel, float offset) {
#define KERNEL1x5(in0, x, kernel, d) \ #define KERNEL1x5(in0, x, kernel, d) \
(_i2f(in0[x - d - d]) * (kernel)[0] + \ (_i2f(in0[x - d - d]) * (kernel)[0] + _i2f(in0[x - d]) * (kernel)[1] + \
_i2f(in0[x - d]) * (kernel)[1] + _i2f(in0[x]) * (kernel)[2] + \ _i2f(in0[x]) * (kernel)[2] + _i2f(in0[x + d]) * (kernel)[3] + \
_i2f(in0[x + d]) * (kernel)[3] + \
_i2f(in0[x + d + d]) * (kernel)[4]) _i2f(in0[x + d + d]) * (kernel)[4])
int x = 0, y = 0; int x = 0, y = 0;

View File

@ -231,8 +231,9 @@ ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t byt
} }
/* Note, have to check Data + size, not just ptr + size) */ /* Note, have to check Data + size, not just ptr + size) */
if (data + (state->xsize * state->ysize) > ptr + bytes) { if (data + (state->xsize * state->ysize) > ptr + bytes) {
/* not enough data for frame */ // not enough data for frame
/* UNDONE Unclear that we're actually going to leave the buffer at the right place. */ // UNDONE Unclear that we're actually going to leave the buffer at
// the right place.
return ptr - buf; /* bytes consumed */ return ptr - buf; /* bytes consumed */
} }
for (y = 0; y < state->ysize; y++) { for (y = 0; y < state->ysize; y++) {
@ -251,7 +252,7 @@ ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t byt
return -1; return -1;
} }
advance = I32(ptr); advance = I32(ptr);
if (advance == 0 ) { if (advance == 0) {
// If there's no advance, we're in an infinite loop // If there's no advance, we're in an infinite loop
state->errcode = IMAGING_CODEC_BROKEN; state->errcode = IMAGING_CODEC_BROKEN;
return -1; return -1;

View File

@ -565,13 +565,13 @@ bilinear_filter32RGB(void *out, Imaging im, double xin, double yin) {
#undef BILINEAR_HEAD #undef BILINEAR_HEAD
#undef BILINEAR_BODY #undef BILINEAR_BODY
#define BICUBIC(v, v1, v2, v3, v4, d) \ #define BICUBIC(v, v1, v2, v3, v4, d) \
{ \ { \
double p1 = v2; \ double p1 = v2; \
double p2 = -v1 + v3; \ double p2 = -v1 + v3; \
double p3 = 2 * (v1 - v2) + v3 - v4; \ double p3 = 2 * (v1 - v2) + v3 - v4; \
double p4 = -v1 + v2 - v3 + v4; \ double p4 = -v1 + v2 - v3 + v4; \
v = p1 + (d) * (p2 + (d) * (p3 + (d)*p4)); \ v = p1 + (d) * (p2 + (d) * (p3 + (d) * p4)); \
} }
#define BICUBIC_HEAD(type) \ #define BICUBIC_HEAD(type) \
@ -966,7 +966,7 @@ affine_fixed(
ysize = (int)imIn->ysize; ysize = (int)imIn->ysize;
/* use 16.16 fixed point arithmetics */ /* use 16.16 fixed point arithmetics */
#define FIX(v) FLOOR((v)*65536.0 + 0.5) #define FIX(v) FLOOR((v) * 65536.0 + 0.5)
a0 = FIX(a[0]); a0 = FIX(a[0]);
a1 = FIX(a[1]); a1 = FIX(a[1]);

View File

@ -58,11 +58,11 @@ ImagingGetBBox(Imaging im, int bbox[4], int alpha_only) {
INT32 mask = 0xffffffff; INT32 mask = 0xffffffff;
if (im->bands == 3) { if (im->bands == 3) {
((UINT8 *)&mask)[3] = 0; ((UINT8 *)&mask)[3] = 0;
} else if (alpha_only && ( } else if (
strcmp(im->mode, "RGBa") == 0 || strcmp(im->mode, "RGBA") == 0 || alpha_only &&
strcmp(im->mode, "La") == 0 || strcmp(im->mode, "LA") == 0 || (strcmp(im->mode, "RGBa") == 0 || strcmp(im->mode, "RGBA") == 0 ||
strcmp(im->mode, "PA") == 0 strcmp(im->mode, "La") == 0 || strcmp(im->mode, "LA") == 0 ||
)) { strcmp(im->mode, "PA") == 0)) {
#ifdef WORDS_BIGENDIAN #ifdef WORDS_BIGENDIAN
mask = 0x000000ff; mask = 0x000000ff;
#else #else

View File

@ -9,10 +9,10 @@
/* Max size for a LZW code word. */ /* Max size for a LZW code word. */
#define GIFBITS 12 #define GIFBITS 12
#define GIFTABLE (1<<GIFBITS) #define GIFTABLE (1 << GIFBITS)
#define GIFBUFFER (1<<GIFBITS) #define GIFBUFFER (1 << GIFBITS)
typedef struct { typedef struct {
/* CONFIGURATION */ /* CONFIGURATION */
@ -66,7 +66,7 @@ typedef struct {
} GIFDECODERSTATE; } GIFDECODERSTATE;
/* For GIF LZW encoder. */ /* For GIF LZW encoder. */
#define TABLE_SIZE 8192 #define TABLE_SIZE 8192
typedef struct { typedef struct {
/* CONFIGURATION */ /* CONFIGURATION */

View File

@ -34,28 +34,36 @@ enum { INIT, ENCODE, FINISH };
*/ */
/* Return values */ /* Return values */
#define GLZW_OK 0 #define GLZW_OK 0
#define GLZW_NO_INPUT_AVAIL 1 #define GLZW_NO_INPUT_AVAIL 1
#define GLZW_NO_OUTPUT_AVAIL 2 #define GLZW_NO_OUTPUT_AVAIL 2
#define GLZW_INTERNAL_ERROR 3 #define GLZW_INTERNAL_ERROR 3
#define CODE_LIMIT 4096 #define CODE_LIMIT 4096
/* Values of entry_state */ /* Values of entry_state */
enum { LZW_INITIAL, LZW_TRY_IN1, LZW_TRY_IN2, LZW_TRY_OUT1, LZW_TRY_OUT2, enum {
LZW_FINISHED }; LZW_INITIAL,
LZW_TRY_IN1,
LZW_TRY_IN2,
LZW_TRY_OUT1,
LZW_TRY_OUT2,
LZW_FINISHED
};
/* Values of control_state */ /* Values of control_state */
enum { PUT_HEAD, PUT_INIT_CLEAR, PUT_CLEAR, PUT_LAST_HEAD, PUT_END }; enum { PUT_HEAD, PUT_INIT_CLEAR, PUT_CLEAR, PUT_LAST_HEAD, PUT_END };
static void glzwe_reset(GIFENCODERSTATE *st) { static void
glzwe_reset(GIFENCODERSTATE *st) {
st->next_code = st->end_code + 1; st->next_code = st->end_code + 1;
st->max_code = 2 * st->clear_code - 1; st->max_code = 2 * st->clear_code - 1;
st->code_width = st->bits + 1; st->code_width = st->bits + 1;
memset(st->codes, 0, sizeof(st->codes)); memset(st->codes, 0, sizeof(st->codes));
} }
static void glzwe_init(GIFENCODERSTATE *st) { static void
glzwe_init(GIFENCODERSTATE *st) {
st->clear_code = 1 << st->bits; st->clear_code = 1 << st->bits;
st->end_code = st->clear_code + 1; st->end_code = st->clear_code + 1;
glzwe_reset(st); glzwe_reset(st);
@ -64,156 +72,157 @@ static void glzwe_init(GIFENCODERSTATE *st) {
st->code_buffer = 0; st->code_buffer = 0;
} }
static int glzwe(GIFENCODERSTATE *st, const UINT8 *in_ptr, UINT8 *out_ptr, static int
UINT32 *in_avail, UINT32 *out_avail, glzwe(
UINT32 end_of_data) { GIFENCODERSTATE *st,
const UINT8 *in_ptr,
UINT8 *out_ptr,
UINT32 *in_avail,
UINT32 *out_avail,
UINT32 end_of_data) {
switch (st->entry_state) { switch (st->entry_state) {
case LZW_TRY_IN1:
case LZW_TRY_IN1:
get_first_byte: get_first_byte:
if (!*in_avail) { if (!*in_avail) {
if (end_of_data) { if (end_of_data) {
goto end_of_data; goto end_of_data;
}
st->entry_state = LZW_TRY_IN1;
return GLZW_NO_INPUT_AVAIL;
} }
st->entry_state = LZW_TRY_IN1; st->head = *in_ptr++;
return GLZW_NO_INPUT_AVAIL; (*in_avail)--;
}
st->head = *in_ptr++;
(*in_avail)--;
case LZW_TRY_IN2: case LZW_TRY_IN2:
encode_loop: encode_loop:
if (!*in_avail) { if (!*in_avail) {
if (end_of_data) { if (end_of_data) {
st->code = st->head; st->code = st->head;
st->put_state = PUT_LAST_HEAD; st->put_state = PUT_LAST_HEAD;
goto put_code; goto put_code;
}
st->entry_state = LZW_TRY_IN2;
return GLZW_NO_INPUT_AVAIL;
} }
st->entry_state = LZW_TRY_IN2; st->tail = *in_ptr++;
return GLZW_NO_INPUT_AVAIL; (*in_avail)--;
}
st->tail = *in_ptr++;
(*in_avail)--;
/* Knuth TAOCP vol 3 sec. 6.4 algorithm D. */ /* Knuth TAOCP vol 3 sec. 6.4 algorithm D. */
/* Hash found experimentally to be pretty good. */ /* Hash found experimentally to be pretty good. */
/* This works ONLY with TABLE_SIZE a power of 2. */ /* This works ONLY with TABLE_SIZE a power of 2. */
st->probe = ((st->head ^ (st->tail << 6)) * 31) & (TABLE_SIZE - 1); st->probe = ((st->head ^ (st->tail << 6)) * 31) & (TABLE_SIZE - 1);
while (st->codes[st->probe]) { while (st->codes[st->probe]) {
if ((st->codes[st->probe] & 0xFFFFF) == if ((st->codes[st->probe] & 0xFFFFF) == ((st->head << 8) | st->tail)) {
((st->head << 8) | st->tail)) { st->head = st->codes[st->probe] >> 20;
st->head = st->codes[st->probe] >> 20; goto encode_loop;
goto encode_loop; } else {
} else { // Reprobe decrement must be non-zero and relatively prime to table
/* Reprobe decrement must be non-zero and relatively prime to table // size. So, any odd positive number for power-of-2 size.
* size. So, any odd positive number for power-of-2 size. */ if ((st->probe -= ((st->tail << 2) | 1)) < 0) {
if ((st->probe -= ((st->tail << 2) | 1)) < 0) { st->probe += TABLE_SIZE;
st->probe += TABLE_SIZE; }
} }
} }
} /* Key not found, probe is at empty slot. */
/* Key not found, probe is at empty slot. */ st->code = st->head;
st->code = st->head; st->put_state = PUT_HEAD;
st->put_state = PUT_HEAD;
goto put_code;
insert_code_or_clear: /* jump here after put_code */
if (st->next_code < CODE_LIMIT) {
st->codes[st->probe] = (st->next_code << 20) |
(st->head << 8) | st->tail;
if (st->next_code > st->max_code) {
st->max_code = st->max_code * 2 + 1;
st->code_width++;
}
st->next_code++;
} else {
st->code = st->clear_code;
st->put_state = PUT_CLEAR;
goto put_code; goto put_code;
insert_code_or_clear: /* jump here after put_code */
if (st->next_code < CODE_LIMIT) {
st->codes[st->probe] =
(st->next_code << 20) | (st->head << 8) | st->tail;
if (st->next_code > st->max_code) {
st->max_code = st->max_code * 2 + 1;
st->code_width++;
}
st->next_code++;
} else {
st->code = st->clear_code;
st->put_state = PUT_CLEAR;
goto put_code;
reset_after_clear: /* jump here after put_code */ reset_after_clear: /* jump here after put_code */
glzwe_reset(st); glzwe_reset(st);
} }
st->head = st->tail; st->head = st->tail;
goto encode_loop; goto encode_loop;
case LZW_INITIAL: case LZW_INITIAL:
glzwe_reset(st); glzwe_reset(st);
st->code = st->clear_code; st->code = st->clear_code;
st->put_state = PUT_INIT_CLEAR; st->put_state = PUT_INIT_CLEAR;
put_code: put_code:
st->code_bits_left = st->code_width; st->code_bits_left = st->code_width;
check_buf_bits: check_buf_bits:
if (!st->buf_bits_left) { /* out buffer full */ if (!st->buf_bits_left) { /* out buffer full */
case LZW_TRY_OUT1: case LZW_TRY_OUT1:
if (!*out_avail) { if (!*out_avail) {
st->entry_state = LZW_TRY_OUT1; st->entry_state = LZW_TRY_OUT1;
return GLZW_NO_OUTPUT_AVAIL; return GLZW_NO_OUTPUT_AVAIL;
}
*out_ptr++ = st->code_buffer;
(*out_avail)--;
st->code_buffer = 0;
st->buf_bits_left = 8;
}
/* code bits to pack */
UINT32 n = st->buf_bits_left < st->code_bits_left ? st->buf_bits_left
: st->code_bits_left;
st->code_buffer |= (st->code & ((1 << n) - 1)) << (8 - st->buf_bits_left);
st->code >>= n;
st->buf_bits_left -= n;
st->code_bits_left -= n;
if (st->code_bits_left) {
goto check_buf_bits;
}
switch (st->put_state) {
case PUT_INIT_CLEAR:
goto get_first_byte;
case PUT_HEAD:
goto insert_code_or_clear;
case PUT_CLEAR:
goto reset_after_clear;
case PUT_LAST_HEAD:
goto end_of_data;
case PUT_END:
goto flush_code_buffer;
default:
return GLZW_INTERNAL_ERROR;
} }
*out_ptr++ = st->code_buffer;
(*out_avail)--;
st->code_buffer = 0;
st->buf_bits_left = 8;
}
/* code bits to pack */
UINT32 n = st->buf_bits_left < st->code_bits_left
? st->buf_bits_left : st->code_bits_left;
st->code_buffer |=
(st->code & ((1 << n) - 1)) << (8 - st->buf_bits_left);
st->code >>= n;
st->buf_bits_left -= n;
st->code_bits_left -= n;
if (st->code_bits_left) {
goto check_buf_bits;
}
switch (st->put_state) {
case PUT_INIT_CLEAR:
goto get_first_byte;
case PUT_HEAD:
goto insert_code_or_clear;
case PUT_CLEAR:
goto reset_after_clear;
case PUT_LAST_HEAD:
goto end_of_data;
case PUT_END:
goto flush_code_buffer;
default:
return GLZW_INTERNAL_ERROR;
}
end_of_data: end_of_data:
st->code = st->end_code; st->code = st->end_code;
st->put_state = PUT_END; st->put_state = PUT_END;
goto put_code; goto put_code;
flush_code_buffer: /* jump here after put_code */ flush_code_buffer: /* jump here after put_code */
if (st->buf_bits_left < 8) { if (st->buf_bits_left < 8) {
case LZW_TRY_OUT2:
case LZW_TRY_OUT2: if (!*out_avail) {
if (!*out_avail) { st->entry_state = LZW_TRY_OUT2;
st->entry_state = LZW_TRY_OUT2; return GLZW_NO_OUTPUT_AVAIL;
return GLZW_NO_OUTPUT_AVAIL; }
*out_ptr++ = st->code_buffer;
(*out_avail)--;
} }
*out_ptr++ = st->code_buffer; st->entry_state = LZW_FINISHED;
(*out_avail)--; return GLZW_OK;
}
st->entry_state = LZW_FINISHED;
return GLZW_OK;
case LZW_FINISHED: case LZW_FINISHED:
return GLZW_OK; return GLZW_OK;
default: default:
return GLZW_INTERNAL_ERROR; return GLZW_INTERNAL_ERROR;
} }
} }
/* -END- GIF LZW encoder. */ /* -END- GIF LZW encoder. */
int int
ImagingGifEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) { ImagingGifEncode(Imaging im, ImagingCodecState state, UINT8 *buf, int bytes) {
UINT8* ptr; UINT8 *ptr;
UINT8* sub_block_ptr; UINT8 *sub_block_ptr;
UINT8* sub_block_limit; UINT8 *sub_block_limit;
UINT8* buf_limit; UINT8 *buf_limit;
GIFENCODERSTATE *context = (GIFENCODERSTATE*) state->context; GIFENCODERSTATE *context = (GIFENCODERSTATE *)state->context;
int r; int r;
UINT32 in_avail, in_used; UINT32 in_avail, in_used;
@ -278,9 +287,9 @@ ImagingGifEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) {
return ptr - buf; return ptr - buf;
} }
sub_block_ptr = ptr; sub_block_ptr = ptr;
sub_block_limit = sub_block_ptr + sub_block_limit =
(256 < buf_limit - sub_block_ptr ? sub_block_ptr +
256 : buf_limit - sub_block_ptr); (256 < buf_limit - sub_block_ptr ? 256 : buf_limit - sub_block_ptr);
*ptr++ = 0; *ptr++ = 0;
} }
@ -301,9 +310,9 @@ ImagingGifEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) {
/* get another line of data */ /* get another line of data */
state->shuffle( state->shuffle(
state->buffer, state->buffer,
(UINT8*) im->image[state->y + state->yoff] + (UINT8 *)im->image[state->y + state->yoff] +
state->xoff * im->pixelsize, state->xsize state->xoff * im->pixelsize,
); state->xsize);
state->x = 0; state->x = 0;
/* step forward, according to the interlace settings */ /* step forward, according to the interlace settings */
@ -331,10 +340,15 @@ ImagingGifEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) {
} }
} }
in_avail = state->xsize - state->x; /* bytes left in line */ in_avail = state->xsize - state->x; /* bytes left in line */
out_avail = sub_block_limit - ptr; /* bytes left in sub-block */ out_avail = sub_block_limit - ptr; /* bytes left in sub-block */
r = glzwe(context, &state->buffer[state->x], ptr, &in_avail, r = glzwe(
&out_avail, state->state == FINISH); context,
&state->buffer[state->x],
ptr,
&in_avail,
&out_avail,
state->state == FINISH);
out_used = sub_block_limit - ptr - out_avail; out_used = sub_block_limit - ptr - out_avail;
*sub_block_ptr += out_used; *sub_block_ptr += out_used;
ptr += out_used; ptr += out_used;

View File

@ -108,15 +108,15 @@ struct ImagingMemoryInstance {
#define IMAGING_PIXEL_1(im, x, y) ((im)->image8[(y)][(x)]) #define IMAGING_PIXEL_1(im, x, y) ((im)->image8[(y)][(x)])
#define IMAGING_PIXEL_L(im, x, y) ((im)->image8[(y)][(x)]) #define IMAGING_PIXEL_L(im, x, y) ((im)->image8[(y)][(x)])
#define IMAGING_PIXEL_LA(im, x, y) ((im)->image[(y)][(x)*4]) #define IMAGING_PIXEL_LA(im, x, y) ((im)->image[(y)][(x) * 4])
#define IMAGING_PIXEL_P(im, x, y) ((im)->image8[(y)][(x)]) #define IMAGING_PIXEL_P(im, x, y) ((im)->image8[(y)][(x)])
#define IMAGING_PIXEL_PA(im, x, y) ((im)->image[(y)][(x)*4]) #define IMAGING_PIXEL_PA(im, x, y) ((im)->image[(y)][(x) * 4])
#define IMAGING_PIXEL_I(im, x, y) ((im)->image32[(y)][(x)]) #define IMAGING_PIXEL_I(im, x, y) ((im)->image32[(y)][(x)])
#define IMAGING_PIXEL_F(im, x, y) (((FLOAT32 *)(im)->image32[y])[x]) #define IMAGING_PIXEL_F(im, x, y) (((FLOAT32 *)(im)->image32[y])[x])
#define IMAGING_PIXEL_RGB(im, x, y) ((im)->image[(y)][(x)*4]) #define IMAGING_PIXEL_RGB(im, x, y) ((im)->image[(y)][(x) * 4])
#define IMAGING_PIXEL_RGBA(im, x, y) ((im)->image[(y)][(x)*4]) #define IMAGING_PIXEL_RGBA(im, x, y) ((im)->image[(y)][(x) * 4])
#define IMAGING_PIXEL_CMYK(im, x, y) ((im)->image[(y)][(x)*4]) #define IMAGING_PIXEL_CMYK(im, x, y) ((im)->image[(y)][(x) * 4])
#define IMAGING_PIXEL_YCbCr(im, x, y) ((im)->image[(y)][(x)*4]) #define IMAGING_PIXEL_YCbCr(im, x, y) ((im)->image[(y)][(x) * 4])
#define IMAGING_PIXEL_UINT8(im, x, y) ((im)->image8[(y)][(x)]) #define IMAGING_PIXEL_UINT8(im, x, y) ((im)->image8[(y)][(x)])
#define IMAGING_PIXEL_INT32(im, x, y) ((im)->image32[(y)][(x)]) #define IMAGING_PIXEL_INT32(im, x, y) ((im)->image32[(y)][(x)])
@ -161,7 +161,7 @@ typedef struct ImagingMemoryArena {
int stats_reallocated_blocks; /* Number of blocks which were actually reallocated int stats_reallocated_blocks; /* Number of blocks which were actually reallocated
after retrieving */ after retrieving */
int stats_freed_blocks; /* Number of freed blocks */ int stats_freed_blocks; /* Number of freed blocks */
} * ImagingMemoryArena; } *ImagingMemoryArena;
/* Objects */ /* Objects */
/* ------- */ /* ------- */
@ -309,7 +309,8 @@ ImagingFlipLeftRight(Imaging imOut, Imaging imIn);
extern Imaging extern Imaging
ImagingFlipTopBottom(Imaging imOut, Imaging imIn); ImagingFlipTopBottom(Imaging imOut, Imaging imIn);
extern Imaging extern Imaging
ImagingGaussianBlur(Imaging imOut, Imaging imIn, float xradius, float yradius, int passes); ImagingGaussianBlur(
Imaging imOut, Imaging imIn, float xradius, float yradius, int passes);
extern Imaging extern Imaging
ImagingGetBand(Imaging im, int band); ImagingGetBand(Imaging im, int band);
extern Imaging extern Imaging
@ -487,7 +488,8 @@ ImagingDrawPieslice(
extern int extern int
ImagingDrawPoint(Imaging im, int x, int y, const void *ink, int op); ImagingDrawPoint(Imaging im, int x, int y, const void *ink, int op);
extern int extern int
ImagingDrawPolygon(Imaging im, int points, int *xy, const void *ink, int fill, int width, int op); ImagingDrawPolygon(
Imaging im, int points, int *xy, const void *ink, int fill, int width, int op);
extern int extern int
ImagingDrawRectangle( ImagingDrawRectangle(
Imaging im, Imaging im,

View File

@ -21,7 +21,7 @@
#define DIV255(a, tmp) (tmp = (a) + 128, SHIFTFORDIV255(tmp)) #define DIV255(a, tmp) (tmp = (a) + 128, SHIFTFORDIV255(tmp))
#define BLEND(mask, in1, in2, tmp1) DIV255(in1 *(255 - mask) + in2 * mask, tmp1) #define BLEND(mask, in1, in2, tmp1) DIV255(in1 * (255 - mask) + in2 * mask, tmp1)
#define PREBLEND(mask, in1, in2, tmp1) (MULDIV255(in1, (255 - mask), tmp1) + in2) #define PREBLEND(mask, in1, in2, tmp1) (MULDIV255(in1, (255 - mask), tmp1) + in2)

View File

@ -183,9 +183,9 @@ j2ku_gray_i(
UINT16 *row = (UINT16 *)im->image[y0 + y] + x0; UINT16 *row = (UINT16 *)im->image[y0 + y] + x0;
for (x = 0; x < w; ++x) { for (x = 0; x < w; ++x) {
UINT16 pixel = j2ku_shift(offset + *data++, shift); UINT16 pixel = j2ku_shift(offset + *data++, shift);
#ifdef WORDS_BIGENDIAN #ifdef WORDS_BIGENDIAN
pixel = (pixel >> 8) | (pixel << 8); pixel = (pixel >> 8) | (pixel << 8);
#endif #endif
*row++ = pixel; *row++ = pixel;
} }
} }
@ -778,7 +778,7 @@ j2k_decode_entry(Imaging im, ImagingCodecState state) {
color_space = OPJ_CLRSPC_SYCC; color_space = OPJ_CLRSPC_SYCC;
break; break;
} }
break; break;
} }
} }
@ -864,7 +864,7 @@ j2k_decode_entry(Imaging im, ImagingCodecState state) {
a, and then a malicious file could have a smaller tile_bytes a, and then a malicious file could have a smaller tile_bytes
*/ */
for (n=0; n < tile_info.nb_comps; n++) { for (n = 0; n < tile_info.nb_comps; n++) {
// see csize /acsize calcs // see csize /acsize calcs
int csize = (image->comps[n].prec + 7) >> 3; int csize = (image->comps[n].prec + 7) >> 3;
csize = (csize == 3) ? 4 : csize; csize = (csize == 3) ? 4 : csize;

View File

@ -383,8 +383,7 @@ j2k_encode_entry(Imaging im, ImagingCodecState state) {
float *pq; float *pq;
if (len > 0) { if (len > 0) {
if ((size_t)len > if ((size_t)len > sizeof(params.tcp_rates) / sizeof(params.tcp_rates[0])) {
sizeof(params.tcp_rates) / sizeof(params.tcp_rates[0])) {
len = sizeof(params.tcp_rates) / sizeof(params.tcp_rates[0]); len = sizeof(params.tcp_rates) / sizeof(params.tcp_rates[0]);
} }
@ -464,7 +463,8 @@ j2k_encode_entry(Imaging im, ImagingCodecState state) {
} }
if (!context->num_resolutions) { if (!context->num_resolutions) {
while (tile_width < (1U << (params.numresolution - 1U)) || tile_height < (1U << (params.numresolution - 1U))) { while (tile_width < (1U << (params.numresolution - 1U)) ||
tile_height < (1U << (params.numresolution - 1U))) {
params.numresolution -= 1; params.numresolution -= 1;
} }
} }

View File

@ -145,8 +145,8 @@ ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8 *buf, int bytes) {
case JCS_EXT_RGBX: case JCS_EXT_RGBX:
#endif #endif
switch (context->subsampling) { switch (context->subsampling) {
case -1: /* Default */ case -1: /* Default */
case 0: /* No subsampling */ case 0: /* No subsampling */
break; break;
default: default:
/* Would subsample the green and blue /* Would subsample the green and blue
@ -305,7 +305,11 @@ ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8 *buf, int bytes) {
case 4: case 4:
if (context->comment) { if (context->comment) {
jpeg_write_marker(&context->cinfo, JPEG_COM, (unsigned char *)context->comment, context->comment_size); jpeg_write_marker(
&context->cinfo,
JPEG_COM,
(unsigned char *)context->comment,
context->comment_size);
} }
state->state++; state->state++;

View File

@ -432,11 +432,10 @@ fill_mask_L(
} }
} else { } else {
int alpha_channel = strcmp(imOut->mode, "RGBa") == 0 || int alpha_channel =
strcmp(imOut->mode, "RGBA") == 0 || strcmp(imOut->mode, "RGBa") == 0 || strcmp(imOut->mode, "RGBA") == 0 ||
strcmp(imOut->mode, "La") == 0 || strcmp(imOut->mode, "La") == 0 || strcmp(imOut->mode, "LA") == 0 ||
strcmp(imOut->mode, "LA") == 0 || strcmp(imOut->mode, "PA") == 0;
strcmp(imOut->mode, "PA") == 0;
for (y = 0; y < ysize; y++) { for (y = 0; y < ysize; y++) {
UINT8 *out = (UINT8 *)imOut->image[y + dy] + dx * pixelsize; UINT8 *out = (UINT8 *)imOut->image[y + dy] + dx * pixelsize;
UINT8 *mask = (UINT8 *)imMask->image[y + sy] + sx; UINT8 *mask = (UINT8 *)imMask->image[y + sy] + sx;

View File

@ -134,7 +134,7 @@ ImagingPoint(Imaging imIn, const char *mode, const void *table) {
ImagingSectionCookie cookie; ImagingSectionCookie cookie;
Imaging imOut; Imaging imOut;
im_point_context context; im_point_context context;
void (*point)(Imaging imIn, Imaging imOut, im_point_context * context); void (*point)(Imaging imIn, Imaging imOut, im_point_context *context);
if (!imIn) { if (!imIn) {
return (Imaging)ImagingError_ModeError(); return (Imaging)ImagingError_ModeError();

View File

@ -260,8 +260,7 @@ mergesort_pixels(PixelList *head, int i) {
return head; return head;
} }
for (c = t = head; c && t; for (c = t = head; c && t;
c = c->next[i], t = (t->next[i]) ? t->next[i]->next[i] : NULL) c = c->next[i], t = (t->next[i]) ? t->next[i]->next[i] : NULL);
;
if (c) { if (c) {
if (c->prev[i]) { if (c->prev[i]) {
c->prev[i]->next[i] = NULL; c->prev[i]->next[i] = NULL;
@ -354,12 +353,10 @@ splitlists(
for (_i = 0; _i < 3; _i++) { for (_i = 0; _i < 3; _i++) {
for (_nextCount[_i] = 0, _nextTest = h[_i]; for (_nextCount[_i] = 0, _nextTest = h[_i];
_nextTest && _nextTest->next[_i]; _nextTest && _nextTest->next[_i];
_nextTest = _nextTest->next[_i], _nextCount[_i]++) _nextTest = _nextTest->next[_i], _nextCount[_i]++);
;
for (_prevCount[_i] = 0, _prevTest = t[_i]; for (_prevCount[_i] = 0, _prevTest = t[_i];
_prevTest && _prevTest->prev[_i]; _prevTest && _prevTest->prev[_i];
_prevTest = _prevTest->prev[_i], _prevCount[_i]++) _prevTest = _prevTest->prev[_i], _prevCount[_i]++);
;
if (_nextTest != t[_i]) { if (_nextTest != t[_i]) {
printf("next-list of axis %d does not end at tail\n", _i); printf("next-list of axis %d does not end at tail\n", _i);
exit(1); exit(1);
@ -368,10 +365,8 @@ splitlists(
printf("prev-list of axis %d does not end at head\n", _i); printf("prev-list of axis %d does not end at head\n", _i);
exit(1); exit(1);
} }
for (; _nextTest && _nextTest->prev[_i]; _nextTest = _nextTest->prev[_i]) for (; _nextTest && _nextTest->prev[_i]; _nextTest = _nextTest->prev[_i]);
; for (; _prevTest && _prevTest->next[_i]; _prevTest = _prevTest->next[_i]);
for (; _prevTest && _prevTest->next[_i]; _prevTest = _prevTest->next[_i])
;
if (_nextTest != h[_i]) { if (_nextTest != h[_i]) {
printf("next-list of axis %d does not loop back to head\n", _i); printf("next-list of axis %d does not loop back to head\n", _i);
exit(1); exit(1);
@ -548,22 +543,18 @@ split(BoxNode *node) {
for (_i = 0; _i < 3; _i++) { for (_i = 0; _i < 3; _i++) {
for (_nextCount[_i] = 0, _nextTest = node->head[_i]; for (_nextCount[_i] = 0, _nextTest = node->head[_i];
_nextTest && _nextTest->next[_i]; _nextTest && _nextTest->next[_i];
_nextTest = _nextTest->next[_i], _nextCount[_i]++) _nextTest = _nextTest->next[_i], _nextCount[_i]++);
;
for (_prevCount[_i] = 0, _prevTest = node->tail[_i]; for (_prevCount[_i] = 0, _prevTest = node->tail[_i];
_prevTest && _prevTest->prev[_i]; _prevTest && _prevTest->prev[_i];
_prevTest = _prevTest->prev[_i], _prevCount[_i]++) _prevTest = _prevTest->prev[_i], _prevCount[_i]++);
;
if (_nextTest != node->tail[_i]) { if (_nextTest != node->tail[_i]) {
printf("next-list of axis %d does not end at tail\n", _i); printf("next-list of axis %d does not end at tail\n", _i);
} }
if (_prevTest != node->head[_i]) { if (_prevTest != node->head[_i]) {
printf("prev-list of axis %d does not end at head\n", _i); printf("prev-list of axis %d does not end at head\n", _i);
} }
for (; _nextTest && _nextTest->prev[_i]; _nextTest = _nextTest->prev[_i]) for (; _nextTest && _nextTest->prev[_i]; _nextTest = _nextTest->prev[_i]);
; for (; _prevTest && _prevTest->next[_i]; _prevTest = _prevTest->next[_i]);
for (; _prevTest && _prevTest->next[_i]; _prevTest = _prevTest->next[_i])
;
if (_nextTest != node->head[_i]) { if (_nextTest != node->head[_i]) {
printf("next-list of axis %d does not loop back to head\n", _i); printf("next-list of axis %d does not loop back to head\n", _i);
} }
@ -668,8 +659,7 @@ median_cut(PixelList *hl[3], uint32_t imPixelCount, int nPixels) {
return NULL; return NULL;
} }
for (i = 0; i < 3; i++) { for (i = 0; i < 3; i++) {
for (tl[i] = hl[i]; tl[i] && tl[i]->next[i]; tl[i] = tl[i]->next[i]) for (tl[i] = hl[i]; tl[i] && tl[i]->next[i]; tl[i] = tl[i]->next[i]);
;
root->head[i] = hl[i]; root->head[i] = hl[i];
root->tail[i] = tl[i]; root->tail[i] = tl[i];
} }
@ -832,16 +822,9 @@ build_distance_tables(
} }
for (i = 0; i < nEntries; i++) { for (i = 0; i < nEntries; i++) {
for (j = 0; j < nEntries; j++) { for (j = 0; j < nEntries; j++) {
dwi[j] = (DistanceWithIndex){ dwi[j] = (DistanceWithIndex){&(avgDist[i * nEntries + j]), j};
&(avgDist[i * nEntries + j]),
j
};
} }
qsort( qsort(dwi, nEntries, sizeof(DistanceWithIndex), _distance_index_cmp);
dwi,
nEntries,
sizeof(DistanceWithIndex),
_distance_index_cmp);
for (j = 0; j < nEntries; j++) { for (j = 0; j < nEntries; j++) {
avgDistSortKey[i * nEntries + j] = dwi[j].distance; avgDistSortKey[i * nEntries + j] = dwi[j].distance;
} }
@ -1213,7 +1196,7 @@ k_means(
compute_palette_from_quantized_pixels( compute_palette_from_quantized_pixels(
pixelData, nPixels, paletteData, nPaletteEntries, avg, count, qp); pixelData, nPixels, paletteData, nPaletteEntries, avg, count, qp);
if (!build_distance_tables( if (!build_distance_tables(
avgDist, avgDistSortKey, paletteData, nPaletteEntries)) { avgDist, avgDistSortKey, paletteData, nPaletteEntries)) {
goto error_3; goto error_3;
} }
built = 1; built = 1;
@ -1452,15 +1435,17 @@ quantize(
hashtable_insert(h2, pixelData[i], bestmatch); hashtable_insert(h2, pixelData[i], bestmatch);
} }
if (qp[i] != bestmatch) { if (qp[i] != bestmatch) {
printf ("discrepancy in matching algorithms pixel %d [%d %d] %f %f\n", printf(
i,qp[i],bestmatch, "discrepancy in matching algorithms pixel %d [%d %d] %f %f\n",
sqrt((double)(_SQR(pixelData[i].c.r-p[qp[i]].c.r)+ i,
_SQR(pixelData[i].c.g-p[qp[i]].c.g)+ qp[i],
_SQR(pixelData[i].c.b-p[qp[i]].c.b))), bestmatch,
sqrt((double)(_SQR(pixelData[i].c.r-p[bestmatch].c.r)+ sqrt((double)(_SQR(pixelData[i].c.r - p[qp[i]].c.r) +
_SQR(pixelData[i].c.g-p[bestmatch].c.g)+ _SQR(pixelData[i].c.g - p[qp[i]].c.g) +
_SQR(pixelData[i].c.b-p[bestmatch].c.b))) _SQR(pixelData[i].c.b - p[qp[i]].c.b))),
); sqrt((double)(_SQR(pixelData[i].c.r - p[bestmatch].c.r) +
_SQR(pixelData[i].c.g - p[bestmatch].c.g) +
_SQR(pixelData[i].c.b - p[bestmatch].c.b))));
} }
} }
hashtable_free(h2); hashtable_free(h2);

View File

@ -38,7 +38,7 @@ typedef struct _ColorBucket {
uint64_t g; uint64_t g;
uint64_t b; uint64_t b;
uint64_t a; uint64_t a;
} * ColorBucket; } *ColorBucket;
typedef struct _ColorCube { typedef struct _ColorCube {
unsigned int rBits, gBits, bBits, aBits; unsigned int rBits, gBits, bBits, aBits;
@ -47,7 +47,7 @@ typedef struct _ColorCube {
unsigned long size; unsigned long size;
ColorBucket buckets; ColorBucket buckets;
} * ColorCube; } *ColorCube;
#define MAX(a, b) (a) > (b) ? (a) : (b) #define MAX(a, b) (a) > (b) ? (a) : (b)

View File

@ -2,7 +2,7 @@
#include <math.h> #include <math.h>
#define ROUND_UP(f) ((int)((f) >= 0.0 ? (f) + 0.5F : (f)-0.5F)) #define ROUND_UP(f) ((int)((f) >= 0.0 ? (f) + 0.5F : (f) - 0.5F))
UINT32 UINT32
division_UINT32(int divider, int result_bits) { division_UINT32(int divider, int result_bits) {

View File

@ -2,7 +2,7 @@
#include <math.h> #include <math.h>
#define ROUND_UP(f) ((int)((f) >= 0.0 ? (f) + 0.5F : (f)-0.5F)) #define ROUND_UP(f) ((int)((f) >= 0.0 ? (f) + 0.5F : (f) - 0.5F))
struct filter { struct filter {
double (*filter)(double x); double (*filter)(double x);

View File

@ -113,7 +113,8 @@ expandrow(UINT8 *dest, UINT8 *src, int n, int z, int xsize, UINT8 *end_of_buffer
} }
static int static int
expandrow2(UINT8 *dest, const UINT8 *src, int n, int z, int xsize, UINT8 *end_of_buffer) { expandrow2(
UINT8 *dest, const UINT8 *src, int n, int z, int xsize, UINT8 *end_of_buffer) {
UINT8 pixel, count; UINT8 pixel, count;
int x = 0; int x = 0;
@ -197,7 +198,6 @@ ImagingSgiRleDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t
return -1; return -1;
} }
/* decoder initialization */ /* decoder initialization */
state->count = 0; state->count = 0;
state->y = 0; state->y = 0;
@ -252,7 +252,7 @@ ImagingSgiRleDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t
c->rlelength, c->rlelength,
im->bands, im->bands,
im->xsize, im->xsize,
&ptr[c->bufsize-1]); &ptr[c->bufsize - 1]);
} else { } else {
status = expandrow2( status = expandrow2(
&state->buffer[c->channo * 2], &state->buffer[c->channo * 2],
@ -260,7 +260,7 @@ ImagingSgiRleDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t
c->rlelength, c->rlelength,
im->bands, im->bands,
im->xsize, im->xsize,
&ptr[c->bufsize-1]); &ptr[c->bufsize - 1]);
} }
if (status == -1) { if (status == -1) {
state->errcode = IMAGING_CODEC_OVERRUN; state->errcode = IMAGING_CODEC_OVERRUN;
@ -268,7 +268,6 @@ ImagingSgiRleDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t
} else if (status == 1) { } else if (status == 1) {
goto sgi_finish_decode; goto sgi_finish_decode;
} }
} }
/* store decompressed data in image */ /* store decompressed data in image */

View File

@ -418,9 +418,8 @@ ImagingAllocateArray(Imaging im, int dirty, int block_size) {
} }
im->blocks[current_block] = block; im->blocks[current_block] = block;
/* Bulletproof code from libc _int_memalign */ /* Bulletproof code from libc _int_memalign */
aligned_ptr = (char *)( aligned_ptr = (char *)(((size_t)(block.ptr + arena->alignment - 1)) &
((size_t) (block.ptr + arena->alignment - 1)) & -((Py_ssize_t)arena->alignment));
-((Py_ssize_t) arena->alignment));
} }
im->image[y] = aligned_ptr + aligned_linesize * line_in_block; im->image[y] = aligned_ptr + aligned_linesize * line_in_block;

View File

@ -60,7 +60,11 @@ _tiffReadProc(thandle_t hdata, tdata_t buf, tsize_t size) {
dump_state(state); dump_state(state);
if (state->loc > state->eof) { if (state->loc > state->eof) {
TIFFError("_tiffReadProc", "Invalid Read at loc %" PRIu64 ", eof: %" PRIu64, state->loc, state->eof); TIFFError(
"_tiffReadProc",
"Invalid Read at loc %" PRIu64 ", eof: %" PRIu64,
state->loc,
state->eof);
return 0; return 0;
} }
to_read = min(size, min(state->size, (tsize_t)state->eof) - (tsize_t)state->loc); to_read = min(size, min(state->size, (tsize_t)state->eof) - (tsize_t)state->loc);
@ -217,7 +221,12 @@ ImagingLibTiffInit(ImagingCodecState state, int fp, uint32_t offset) {
} }
int int
_pickUnpackers(Imaging im, ImagingCodecState state, TIFF *tiff, uint16_t planarconfig, ImagingShuffler *unpackers) { _pickUnpackers(
Imaging im,
ImagingCodecState state,
TIFF *tiff,
uint16_t planarconfig,
ImagingShuffler *unpackers) {
// if number of bands is 1, there is no difference with contig case // if number of bands is 1, there is no difference with contig case
if (planarconfig == PLANARCONFIG_SEPARATE && im->bands > 1) { if (planarconfig == PLANARCONFIG_SEPARATE && im->bands > 1) {
uint16_t bits_per_sample = 8; uint16_t bits_per_sample = 8;
@ -232,10 +241,14 @@ _pickUnpackers(Imaging im, ImagingCodecState state, TIFF *tiff, uint16_t planarc
// We'll pick appropriate set of unpackers depending on planar_configuration // We'll pick appropriate set of unpackers depending on planar_configuration
// It does not matter if data is RGB(A), CMYK or LUV really, // It does not matter if data is RGB(A), CMYK or LUV really,
// we just copy it plane by plane // we just copy it plane by plane
unpackers[0] = ImagingFindUnpacker("RGBA", bits_per_sample == 16 ? "R;16N" : "R", NULL); unpackers[0] =
unpackers[1] = ImagingFindUnpacker("RGBA", bits_per_sample == 16 ? "G;16N" : "G", NULL); ImagingFindUnpacker("RGBA", bits_per_sample == 16 ? "R;16N" : "R", NULL);
unpackers[2] = ImagingFindUnpacker("RGBA", bits_per_sample == 16 ? "B;16N" : "B", NULL); unpackers[1] =
unpackers[3] = ImagingFindUnpacker("RGBA", bits_per_sample == 16 ? "A;16N" : "A", NULL); ImagingFindUnpacker("RGBA", bits_per_sample == 16 ? "G;16N" : "G", NULL);
unpackers[2] =
ImagingFindUnpacker("RGBA", bits_per_sample == 16 ? "B;16N" : "B", NULL);
unpackers[3] =
ImagingFindUnpacker("RGBA", bits_per_sample == 16 ? "A;16N" : "A", NULL);
return im->bands; return im->bands;
} else { } else {
@ -247,10 +260,10 @@ _pickUnpackers(Imaging im, ImagingCodecState state, TIFF *tiff, uint16_t planarc
int int
_decodeAsRGBA(Imaging im, ImagingCodecState state, TIFF *tiff) { _decodeAsRGBA(Imaging im, ImagingCodecState state, TIFF *tiff) {
// To avoid dealing with YCbCr subsampling and other complications, let libtiff handle it // To avoid dealing with YCbCr subsampling and other complications, let libtiff
// Use a TIFFRGBAImage wrapping the tiff image, and let libtiff handle // handle it Use a TIFFRGBAImage wrapping the tiff image, and let libtiff handle all
// all of the conversion. Metadata read from the TIFFRGBAImage could // of the conversion. Metadata read from the TIFFRGBAImage could be different from
// be different from the metadata that the base tiff returns. // the metadata that the base tiff returns.
INT32 current_row; INT32 current_row;
UINT8 *new_data; UINT8 *new_data;
@ -259,17 +272,16 @@ _decodeAsRGBA(Imaging im, ImagingCodecState state, TIFF *tiff) {
TIFFRGBAImage img; TIFFRGBAImage img;
char emsg[1024] = ""; char emsg[1024] = "";
// Since using TIFFRGBAImage* functions, we can read whole tiff into rastrr in one call // Since using TIFFRGBAImage* functions, we can read whole tiff into rastrr in one
// Let's select smaller block size. Multiplying image width by (tile length OR rows per strip) // call Let's select smaller block size. Multiplying image width by (tile length OR
// gives us manageable block size in pixels // rows per strip) gives us manageable block size in pixels
if (TIFFIsTiled(tiff)) { if (TIFFIsTiled(tiff)) {
ret = TIFFGetFieldDefaulted(tiff, TIFFTAG_TILELENGTH, &rows_per_block); ret = TIFFGetFieldDefaulted(tiff, TIFFTAG_TILELENGTH, &rows_per_block);
} } else {
else {
ret = TIFFGetFieldDefaulted(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_block); ret = TIFFGetFieldDefaulted(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_block);
} }
if (ret != 1 || rows_per_block==(UINT32)(-1)) { if (ret != 1 || rows_per_block == (UINT32)(-1)) {
rows_per_block = state->ysize; rows_per_block = state->ysize;
} }
@ -357,7 +369,12 @@ decodergba_err:
} }
int int
_decodeTile(Imaging im, ImagingCodecState state, TIFF *tiff, int planes, ImagingShuffler *unpackers) { _decodeTile(
Imaging im,
ImagingCodecState state,
TIFF *tiff,
int planes,
ImagingShuffler *unpackers) {
INT32 x, y, tile_y, current_tile_length, current_tile_width; INT32 x, y, tile_y, current_tile_length, current_tile_width;
UINT32 tile_width, tile_length; UINT32 tile_width, tile_length;
tsize_t tile_bytes_size, row_byte_size; tsize_t tile_bytes_size, row_byte_size;
@ -396,8 +413,8 @@ _decodeTile(Imaging im, ImagingCodecState state, TIFF *tiff, int planes, Imaging
if (tile_bytes_size > ((tile_length * state->bits / planes + 7) / 8) * tile_width) { if (tile_bytes_size > ((tile_length * state->bits / planes + 7) / 8) * tile_width) {
// If the tile size as expected by LibTiff isn't what we're expecting, abort. // If the tile size as expected by LibTiff isn't what we're expecting, abort.
// man: TIFFTileSize returns the equivalent size for a tile of data as it would be returned in a // man: TIFFTileSize returns the equivalent size for a tile of data as it
// call to TIFFReadTile ... // would be returned in a call to TIFFReadTile ...
state->errcode = IMAGING_CODEC_BROKEN; state->errcode = IMAGING_CODEC_BROKEN;
return -1; return -1;
} }
@ -428,19 +445,24 @@ _decodeTile(Imaging im, ImagingCodecState state, TIFF *tiff, int planes, Imaging
TRACE(("Read tile at %dx%d; \n\n", x, y)); TRACE(("Read tile at %dx%d; \n\n", x, y));
current_tile_width = min((INT32) tile_width, state->xsize - x); current_tile_width = min((INT32)tile_width, state->xsize - x);
current_tile_length = min((INT32) tile_length, state->ysize - y); current_tile_length = min((INT32)tile_length, state->ysize - y);
// iterate over each line in the tile and stuff data into image // iterate over each line in the tile and stuff data into image
for (tile_y = 0; tile_y < current_tile_length; tile_y++) { for (tile_y = 0; tile_y < current_tile_length; tile_y++) {
TRACE(("Writing tile data at %dx%d using tile_width: %d; \n", tile_y + y, x, current_tile_width)); TRACE(
("Writing tile data at %dx%d using tile_width: %d; \n",
tile_y + y,
x,
current_tile_width));
// UINT8 * bbb = state->buffer + tile_y * row_byte_size; // UINT8 * bbb = state->buffer + tile_y * row_byte_size;
// TRACE(("chars: %x%x%x%x\n", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); // TRACE(("chars: %x%x%x%x\n", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1],
// ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3]));
shuffler((UINT8*) im->image[tile_y + y] + x * im->pixelsize, shuffler(
state->buffer + tile_y * row_byte_size, (UINT8 *)im->image[tile_y + y] + x * im->pixelsize,
current_tile_width state->buffer + tile_y * row_byte_size,
); current_tile_width);
} }
} }
} }
@ -450,7 +472,12 @@ _decodeTile(Imaging im, ImagingCodecState state, TIFF *tiff, int planes, Imaging
} }
int int
_decodeStrip(Imaging im, ImagingCodecState state, TIFF *tiff, int planes, ImagingShuffler *unpackers) { _decodeStrip(
Imaging im,
ImagingCodecState state,
TIFF *tiff,
int planes,
ImagingShuffler *unpackers) {
INT32 strip_row = 0; INT32 strip_row = 0;
UINT8 *new_data; UINT8 *new_data;
UINT32 rows_per_strip; UINT32 rows_per_strip;
@ -458,7 +485,7 @@ _decodeStrip(Imaging im, ImagingCodecState state, TIFF *tiff, int planes, Imagin
tsize_t strip_size, row_byte_size, unpacker_row_byte_size; tsize_t strip_size, row_byte_size, unpacker_row_byte_size;
ret = TIFFGetField(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip); ret = TIFFGetField(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip);
if (ret != 1 || rows_per_strip==(UINT32)(-1)) { if (ret != 1 || rows_per_strip == (UINT32)(-1)) {
rows_per_strip = state->ysize; rows_per_strip = state->ysize;
} }
@ -478,8 +505,8 @@ _decodeStrip(Imaging im, ImagingCodecState state, TIFF *tiff, int planes, Imagin
unpacker_row_byte_size = (state->xsize * state->bits / planes + 7) / 8; unpacker_row_byte_size = (state->xsize * state->bits / planes + 7) / 8;
if (strip_size > (unpacker_row_byte_size * rows_per_strip)) { if (strip_size > (unpacker_row_byte_size * rows_per_strip)) {
// If the strip size as expected by LibTiff isn't what we're expecting, abort. // If the strip size as expected by LibTiff isn't what we're expecting, abort.
// man: TIFFStripSize returns the equivalent size for a strip of data as it would be returned in a // man: TIFFStripSize returns the equivalent size for a strip of data as it
// call to TIFFReadEncodedStrip ... // would be returned in a call to TIFFReadEncodedStrip ...
state->errcode = IMAGING_CODEC_BROKEN; state->errcode = IMAGING_CODEC_BROKEN;
return -1; return -1;
} }
@ -513,8 +540,13 @@ _decodeStrip(Imaging im, ImagingCodecState state, TIFF *tiff, int planes, Imagin
int plane; int plane;
for (plane = 0; plane < planes; plane++) { for (plane = 0; plane < planes; plane++) {
ImagingShuffler shuffler = unpackers[plane]; ImagingShuffler shuffler = unpackers[plane];
if (TIFFReadEncodedStrip(tiff, TIFFComputeStrip(tiff, state->y, plane), (tdata_t)state->buffer, strip_size) == -1) { if (TIFFReadEncodedStrip(
TRACE(("Decode Error, strip %d\n", TIFFComputeStrip(tiff, state->y, 0))); tiff,
TIFFComputeStrip(tiff, state->y, plane),
(tdata_t)state->buffer,
strip_size) == -1) {
TRACE(
("Decode Error, strip %d\n", TIFFComputeStrip(tiff, state->y, 0)));
state->errcode = IMAGING_CODEC_BROKEN; state->errcode = IMAGING_CODEC_BROKEN;
return -1; return -1;
} }
@ -523,16 +555,17 @@ _decodeStrip(Imaging im, ImagingCodecState state, TIFF *tiff, int planes, Imagin
// iterate over each row in the strip and stuff data into image // iterate over each row in the strip and stuff data into image
for (strip_row = 0; for (strip_row = 0;
strip_row < min((INT32) rows_per_strip, state->ysize - state->y); strip_row < min((INT32)rows_per_strip, state->ysize - state->y);
strip_row++) { strip_row++) {
TRACE(("Writing data into line %d ; \n", state->y + strip_row)); TRACE(("Writing data into line %d ; \n", state->y + strip_row));
// UINT8 * bbb = state->buffer + strip_row * (state->bytes / rows_per_strip); // UINT8 * bbb = state->buffer + strip_row * (state->bytes /
// TRACE(("chars: %x %x %x %x\n", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); // rows_per_strip); TRACE(("chars: %x %x %x %x\n", ((UINT8 *)bbb)[0],
// ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3]));
shuffler( shuffler(
(UINT8*) im->image[state->y + state->yoff + strip_row] + (UINT8 *)im->image[state->y + state->yoff + strip_row] +
state->xoff * im->pixelsize, state->xoff * im->pixelsize,
state->buffer + strip_row * row_byte_size, state->buffer + strip_row * row_byte_size,
state->xsize); state->xsize);
} }
@ -666,7 +699,6 @@ ImagingLibTiffDecode(
goto decode_err; goto decode_err;
} }
TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric); TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric);
TIFFGetField(tiff, TIFFTAG_COMPRESSION, &compression); TIFFGetField(tiff, TIFFTAG_COMPRESSION, &compression);
TIFFGetFieldDefaulted(tiff, TIFFTAG_PLANARCONFIG, &planarconfig); TIFFGetFieldDefaulted(tiff, TIFFTAG_PLANARCONFIG, &planarconfig);
@ -675,16 +707,17 @@ ImagingLibTiffDecode(
// Let LibTiff read them as RGBA // Let LibTiff read them as RGBA
readAsRGBA = photometric == PHOTOMETRIC_YCBCR; readAsRGBA = photometric == PHOTOMETRIC_YCBCR;
if (readAsRGBA && compression == COMPRESSION_JPEG && planarconfig == PLANARCONFIG_CONTIG) { if (readAsRGBA && compression == COMPRESSION_JPEG &&
// If using new JPEG compression, let libjpeg do RGB conversion for performance reasons planarconfig == PLANARCONFIG_CONTIG) {
// If using new JPEG compression, let libjpeg do RGB conversion for performance
// reasons
TIFFSetField(tiff, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); TIFFSetField(tiff, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
readAsRGBA = 0; readAsRGBA = 0;
} }
if (readAsRGBA) { if (readAsRGBA) {
_decodeAsRGBA(im, state, tiff); _decodeAsRGBA(im, state, tiff);
} } else {
else {
planes = _pickUnpackers(im, state, tiff, planarconfig, unpackers); planes = _pickUnpackers(im, state, tiff, planarconfig, unpackers);
if (planes <= 0) { if (planes <= 0) {
goto decode_err; goto decode_err;
@ -692,8 +725,7 @@ ImagingLibTiffDecode(
if (TIFFIsTiled(tiff)) { if (TIFFIsTiled(tiff)) {
_decodeTile(im, state, tiff, planes, unpackers); _decodeTile(im, state, tiff, planes, unpackers);
} } else {
else {
_decodeStrip(im, state, tiff, planes, unpackers); _decodeStrip(im, state, tiff, planes, unpackers);
} }
@ -702,20 +734,20 @@ ImagingLibTiffDecode(
// so we have to convert it to RGBA // so we have to convert it to RGBA
if (planes > 3 && strcmp(im->mode, "RGBA") == 0) { if (planes > 3 && strcmp(im->mode, "RGBA") == 0) {
uint16_t extrasamples; uint16_t extrasamples;
uint16_t* sampleinfo; uint16_t *sampleinfo;
ImagingShuffler shuffle; ImagingShuffler shuffle;
INT32 y; INT32 y;
TIFFGetFieldDefaulted(tiff, TIFFTAG_EXTRASAMPLES, &extrasamples, &sampleinfo); TIFFGetFieldDefaulted(
tiff, TIFFTAG_EXTRASAMPLES, &extrasamples, &sampleinfo);
if (extrasamples >= 1 && if (extrasamples >= 1 && (sampleinfo[0] == EXTRASAMPLE_UNSPECIFIED ||
(sampleinfo[0] == EXTRASAMPLE_UNSPECIFIED || sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA) sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA)) {
) {
shuffle = ImagingFindUnpacker("RGBA", "RGBa", NULL); shuffle = ImagingFindUnpacker("RGBA", "RGBa", NULL);
for (y = state->yoff; y < state->ysize; y++) { for (y = state->yoff; y < state->ysize; y++) {
UINT8* ptr = (UINT8*) im->image[y + state->yoff] + UINT8 *ptr = (UINT8 *)im->image[y + state->yoff] +
state->xoff * im->pixelsize; state->xoff * im->pixelsize;
shuffle(ptr, ptr, state->xsize); shuffle(ptr, ptr, state->xsize);
} }
} }
@ -723,7 +755,7 @@ ImagingLibTiffDecode(
} }
} }
decode_err: decode_err:
// TIFFClose in libtiff calls tif_closeproc and TIFFCleanup // TIFFClose in libtiff calls tif_closeproc and TIFFCleanup
if (clientstate->fp) { if (clientstate->fp) {
// Pillow will manage the closing of the file rather than libtiff // Pillow will manage the closing of the file rather than libtiff
@ -973,7 +1005,8 @@ ImagingLibTiffEncode(Imaging im, ImagingCodecState state, UINT8 *buffer, int byt
} }
if (state->state == 1 && !clientstate->fp) { if (state->state == 1 && !clientstate->fp) {
int read = (int)_tiffReadProc(clientstate, (tdata_t)buffer, (tsize_t)bytes); int read =
(int)_tiffReadProc((thandle_t)clientstate, (tdata_t)buffer, (tsize_t)bytes);
TRACE( TRACE(
("Buffer: %p: %c%c%c%c\n", ("Buffer: %p: %c%c%c%c\n",
buffer, buffer,

View File

@ -30,7 +30,7 @@ typedef struct {
* Should be uint32 for libtiff 3.9.x * Should be uint32 for libtiff 3.9.x
* uint64 for libtiff 4.0.x * uint64 for libtiff 4.0.x
*/ */
TIFF *tiff; /* Used in write */ TIFF *tiff; /* Used in write */
toff_t eof; toff_t eof;
int flrealloc; /* may we realloc */ int flrealloc; /* may we realloc */
} TIFFSTATE; } TIFFSTATE;

View File

@ -1437,90 +1437,90 @@ band3I(UINT8 *out, const UINT8 *in, int pixels) {
} }
static void static void
band016B(UINT8* out, const UINT8* in, int pixels) band016B(UINT8 *out, const UINT8 *in, int pixels) {
{
int i; int i;
/* band 0 only, big endian */ /* band 0 only, big endian */
for (i = 0; i < pixels; i++) { for (i = 0; i < pixels; i++) {
out[0] = in[0]; out[0] = in[0];
out += 4; in += 2; out += 4;
in += 2;
} }
} }
static void static void
band116B(UINT8* out, const UINT8* in, int pixels) band116B(UINT8 *out, const UINT8 *in, int pixels) {
{
int i; int i;
/* band 1 only, big endian */ /* band 1 only, big endian */
for (i = 0; i < pixels; i++) { for (i = 0; i < pixels; i++) {
out[1] = in[0]; out[1] = in[0];
out += 4; in += 2; out += 4;
in += 2;
} }
} }
static void static void
band216B(UINT8* out, const UINT8* in, int pixels) band216B(UINT8 *out, const UINT8 *in, int pixels) {
{
int i; int i;
/* band 2 only, big endian */ /* band 2 only, big endian */
for (i = 0; i < pixels; i++) { for (i = 0; i < pixels; i++) {
out[2] = in[0]; out[2] = in[0];
out += 4; in += 2; out += 4;
in += 2;
} }
} }
static void static void
band316B(UINT8* out, const UINT8* in, int pixels) band316B(UINT8 *out, const UINT8 *in, int pixels) {
{
int i; int i;
/* band 3 only, big endian */ /* band 3 only, big endian */
for (i = 0; i < pixels; i++) { for (i = 0; i < pixels; i++) {
out[3] = in[0]; out[3] = in[0];
out += 4; in += 2; out += 4;
in += 2;
} }
} }
static void static void
band016L(UINT8* out, const UINT8* in, int pixels) band016L(UINT8 *out, const UINT8 *in, int pixels) {
{
int i; int i;
/* band 0 only, little endian */ /* band 0 only, little endian */
for (i = 0; i < pixels; i++) { for (i = 0; i < pixels; i++) {
out[0] = in[1]; out[0] = in[1];
out += 4; in += 2; out += 4;
in += 2;
} }
} }
static void static void
band116L(UINT8* out, const UINT8* in, int pixels) band116L(UINT8 *out, const UINT8 *in, int pixels) {
{
int i; int i;
/* band 1 only, little endian */ /* band 1 only, little endian */
for (i = 0; i < pixels; i++) { for (i = 0; i < pixels; i++) {
out[1] = in[1]; out[1] = in[1];
out += 4; in += 2; out += 4;
in += 2;
} }
} }
static void static void
band216L(UINT8* out, const UINT8* in, int pixels) band216L(UINT8 *out, const UINT8 *in, int pixels) {
{
int i; int i;
/* band 2 only, little endian */ /* band 2 only, little endian */
for (i = 0; i < pixels; i++) { for (i = 0; i < pixels; i++) {
out[2] = in[1]; out[2] = in[1];
out += 4; in += 2; out += 4;
in += 2;
} }
} }
static void static void
band316L(UINT8* out, const UINT8* in, int pixels) band316L(UINT8 *out, const UINT8 *in, int pixels) {
{
int i; int i;
/* band 3 only, little endian */ /* band 3 only, little endian */
for (i = 0; i < pixels; i++) { for (i = 0; i < pixels; i++) {
out[3] = in[1]; out[3] = in[1];
out += 4; in += 2; out += 4;
in += 2;
} }
} }
@ -1687,7 +1687,6 @@ static struct {
{"RGB", "G;16N", 16, band116L}, {"RGB", "G;16N", 16, band116L},
{"RGB", "B;16N", 16, band216L}, {"RGB", "B;16N", 16, band216L},
{"RGBA", "R;16N", 16, band016L}, {"RGBA", "R;16N", 16, band016L},
{"RGBA", "G;16N", 16, band116L}, {"RGBA", "G;16N", 16, band116L},
{"RGBA", "B;16N", 16, band216L}, {"RGBA", "B;16N", 16, band216L},

View File

@ -162,24 +162,24 @@ PyPath_Flatten(PyObject *data, double **pxy) {
return -1; return -1;
} }
#define assign_item_to_array(op, decref) \ #define assign_item_to_array(op, decref) \
if (PyFloat_Check(op)) { \ if (PyFloat_Check(op)) { \
xy[j++] = PyFloat_AS_DOUBLE(op); \ xy[j++] = PyFloat_AS_DOUBLE(op); \
} else if (PyLong_Check(op)) { \ } else if (PyLong_Check(op)) { \
xy[j++] = (float)PyLong_AS_LONG(op); \ xy[j++] = (float)PyLong_AS_LONG(op); \
} else if (PyNumber_Check(op)) { \ } else if (PyNumber_Check(op)) { \
xy[j++] = PyFloat_AsDouble(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++] = x; \
xy[j++] = y; \ xy[j++] = y; \
} else { \ } else { \
PyErr_SetString(PyExc_ValueError, "incorrect coordinate type"); \ PyErr_SetString(PyExc_ValueError, "incorrect coordinate type"); \
if (decref) { \ if (decref) { \
Py_DECREF(op); \ Py_DECREF(op); \
} \ } \
free(xy); \ free(xy); \
return -1; \ return -1; \
} }
/* Copy table to path array */ /* Copy table to path array */
if (PyList_Check(data)) { if (PyList_Check(data)) {