Skip to content

Commit

Permalink
Merge remote-tracking branch 'upstream/main' into types-imagefont
Browse files Browse the repository at this point in the history
  • Loading branch information
nulano committed Dec 27, 2023
2 parents 0d90bc8 + 78b96c0 commit f7445bf
Show file tree
Hide file tree
Showing 9 changed files with 176 additions and 115 deletions.
33 changes: 21 additions & 12 deletions .github/workflows/wheels.yml
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,9 @@ jobs:
CIBW_TEST_SKIP: "*-macosx_arm64"
MACOSX_DEPLOYMENT_TARGET: ${{ matrix.macosx_deployment_target }}

- uses: actions/upload-artifact@v3
- uses: actions/upload-artifact@v4
with:
name: dist
name: dist-${{ matrix.os }}-${{ matrix.archs }}${{ matrix.manylinux && format('-{0}', matrix.manylinux) }}
path: ./wheelhouse/*.whl

windows:
Expand Down Expand Up @@ -154,9 +154,9 @@ jobs:
shell: cmd

- name: Upload wheels
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: dist
name: dist-windows-${{ matrix.arch }}
path: ./wheelhouse/*.whl

- name: Upload fribidi.dll
Expand All @@ -179,17 +179,26 @@ jobs:

- run: make sdist

- uses: actions/upload-artifact@v3
- uses: actions/upload-artifact@v4
with:
name: dist
name: dist-sdist
path: dist/*.tar.gz

success:
permissions:
contents: none
pypi-publish:
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags')
needs: [build, windows, sdist]
runs-on: ubuntu-latest
name: Wheels Successful
name: Upload release to PyPI
environment:
name: release-pypi
url: https://pypi.org/p/Pillow
permissions:
id-token: write
steps:
- name: Success
run: echo Wheels Successful
- uses: actions/download-artifact@v4
with:
pattern: dist-*
path: dist
merge-multiple: true
- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
12 changes: 12 additions & 0 deletions Tests/test_fontfile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from __future__ import annotations
import pytest

from PIL import FontFile


def test_save(tmp_path):
tempname = str(tmp_path / "temp.pil")

font = FontFile.FontFile()
with pytest.raises(ValueError):
font.save(tempname)
13 changes: 7 additions & 6 deletions docs/handbook/image-file-formats.rst
Original file line number Diff line number Diff line change
Expand Up @@ -552,12 +552,13 @@ JPEG 2000

.. versionadded:: 2.4.0

Pillow reads and writes JPEG 2000 files containing ``L``, ``LA``, ``RGB`` or
``RGBA`` data. It can also read files containing ``YCbCr`` data, which it
converts on read into ``RGB`` or ``RGBA`` depending on whether or not there is
an alpha channel. Pillow supports JPEG 2000 raw codestreams (``.j2k`` files),
as well as boxed JPEG 2000 files (``.j2p`` or ``.jpx`` files). Pillow does
*not* support files whose components have different sampling frequencies.
Pillow reads and writes JPEG 2000 files containing ``L``, ``LA``, ``RGB``,
``RGBA``, or ``YCbCr`` data. When reading, ``YCbCr`` data is converted to
``RGB`` or ``RGBA`` depending on whether or not there is an alpha channel.
Beginning with version 8.3.0, Pillow can read (but not write) ``RGB``,
``RGBA``, and ``YCbCr`` images with subsampled components. Pillow supports
JPEG 2000 raw codestreams (``.j2k`` files), as well as boxed JPEG 2000 files
(``.jp2`` or ``.jpx`` files).

When loading, if you set the ``mode`` on the image prior to the
:py:meth:`~PIL.Image.Image.load` method being invoked, you can ask Pillow to
Expand Down
21 changes: 16 additions & 5 deletions src/PIL/BdfFontFile.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
"""
from __future__ import annotations

from typing import BinaryIO

from . import FontFile, Image

bdf_slant = {
Expand All @@ -36,7 +38,17 @@
bdf_spacing = {"P": "Proportional", "M": "Monospaced", "C": "Cell"}


def bdf_char(f):
def bdf_char(
f: BinaryIO,
) -> (
tuple[
str,
int,
tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]],
Image.Image,
]
| None
):
# skip to STARTCHAR
while True:
s = f.readline()
Expand All @@ -56,13 +68,12 @@ def bdf_char(f):
props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")

# load bitmap
bitmap = []
bitmap = bytearray()
while True:
s = f.readline()
if not s or s[:7] == b"ENDCHAR":
break
bitmap.append(s[:-1])
bitmap = b"".join(bitmap)
bitmap += s[:-1]

# The word BBX
# followed by the width in x (BBw), height in y (BBh),
Expand Down Expand Up @@ -92,7 +103,7 @@ def bdf_char(f):
class BdfFontFile(FontFile.FontFile):
"""Font file plugin for the X11 BDF format."""

def __init__(self, fp):
def __init__(self, fp: BinaryIO):
super().__init__()

s = fp.readline()
Expand Down
55 changes: 41 additions & 14 deletions src/PIL/FontFile.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,16 @@
from __future__ import annotations

import os
from typing import BinaryIO

from . import Image, _binary

WIDTH = 800


def puti16(fp, values):
def puti16(
fp: BinaryIO, values: tuple[int, int, int, int, int, int, int, int, int, int]
) -> None:
"""Write network order (big-endian) 16-bit sequence"""
for v in values:
if v < 0:
Expand All @@ -33,16 +36,34 @@ def puti16(fp, values):
class FontFile:
"""Base class for raster font file handlers."""

bitmap = None

def __init__(self):
self.info = {}
self.glyph = [None] * 256

def __getitem__(self, ix):
bitmap: Image.Image | None = None

def __init__(self) -> None:
self.info: dict[bytes, bytes | int] = {}
self.glyph: list[
tuple[
tuple[int, int],
tuple[int, int, int, int],
tuple[int, int, int, int],
Image.Image,
]
| None
] = [None] * 256

def __getitem__(
self, ix: int
) -> (
tuple[
tuple[int, int],
tuple[int, int, int, int],
tuple[int, int, int, int],
Image.Image,
]
| None
):
return self.glyph[ix]

def compile(self):
def compile(self) -> None:
"""Create metrics and bitmap"""

if self.bitmap:
Expand All @@ -51,7 +72,7 @@ def compile(self):
# create bitmap large enough to hold all data
h = w = maxwidth = 0
lines = 1
for glyph in self:
for glyph in self.glyph:
if glyph:
d, dst, src, im = glyph
h = max(h, src[3] - src[1])
Expand All @@ -65,13 +86,16 @@ def compile(self):
ysize = lines * h

if xsize == 0 and ysize == 0:
return ""
return

self.ysize = h

# paste glyphs into bitmap
self.bitmap = Image.new("1", (xsize, ysize))
self.metrics = [None] * 256
self.metrics: list[
tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]]
| None
] = [None] * 256
x = y = 0
for i in range(256):
glyph = self[i]
Expand All @@ -88,12 +112,15 @@ def compile(self):
self.bitmap.paste(im.crop(src), s)
self.metrics[i] = d, dst, s

def save(self, filename):
def save(self, filename: str) -> None:
"""Save font"""

self.compile()

# font data
if not self.bitmap:
msg = "No bitmap created"
raise ValueError(msg)
self.bitmap.save(os.path.splitext(filename)[0] + ".pbm", "PNG")

# font metrics
Expand All @@ -104,6 +131,6 @@ def save(self, filename):
for id in range(256):
m = self.metrics[id]
if not m:
puti16(fp, [0] * 10)
puti16(fp, (0,) * 10)
else:
puti16(fp, m[0] + m[1] + m[2])
10 changes: 5 additions & 5 deletions src/PIL/Image.py
Original file line number Diff line number Diff line change
Expand Up @@ -1194,7 +1194,7 @@ def copy(self) -> Image:

__copy__ = copy

def crop(self, box=None):
def crop(self, box=None) -> Image:
"""
Returns a rectangular region from this image. The box is a
4-tuple defining the left, upper, right, and lower pixel
Expand Down Expand Up @@ -1659,7 +1659,7 @@ def entropy(self, mask=None, extrema=None):
return self.im.entropy(extrema)
return self.im.entropy()

def paste(self, im, box=None, mask=None):
def paste(self, im, box=None, mask=None) -> None:
"""
Pastes another image into this image. The box argument is either
a 2-tuple giving the upper left corner, a 4-tuple defining the
Expand Down Expand Up @@ -2352,7 +2352,7 @@ def transform(x, y, matrix):
(w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor
)

def save(self, fp, format=None, **params):
def save(self, fp, format=None, **params) -> None:
"""
Saves this image under the given filename. If no format is
specified, the format to use is determined from the filename
Expand Down Expand Up @@ -2903,7 +2903,7 @@ def _check_size(size):
return True


def new(mode, size, color=0):
def new(mode, size, color=0) -> Image:
"""
Creates a new image with the given mode and size.
Expand Down Expand Up @@ -2942,7 +2942,7 @@ def new(mode, size, color=0):
return im._new(core.fill(mode, size, color))


def frombytes(mode, size, data, decoder_name="raw", *args):
def frombytes(mode, size, data, decoder_name="raw", *args) -> Image:
"""
Creates a copy of an image memory from pixel data in a buffer.
Expand Down
Loading

0 comments on commit f7445bf

Please sign in to comment.