Skip to content

Conversation

@radarhere
Copy link
Member

@radarhere radarhere commented Aug 17, 2025

Resolves #9158. The issue requested a method to check if glyphs are present in a font. This question has arisen previously in #7380 (comment), and I think this would also help users from #4808, in a less elegant way.

This adds FreeTypeFont.has_characters(text). I expect that the issue was only thinking about checking a single character at a time, but if user wanted to check multiple characters at once, I don't see any reason not to let them. If any character in the string is missing, then False is returned.

The C code in here is based on

Pillow/src/_imagingft.c

Lines 432 to 463 in 9d39fe6

if (PyUnicode_Check(string)) {
count = PyUnicode_GET_LENGTH(string);
} else if (PyBytes_Check(string)) {
PyBytes_AsStringAndSize(string, &buffer, &count);
} else {
PyErr_SetString(PyExc_TypeError, "expected string or bytes");
return 0;
}
if (count == 0) {
return 0;
}
(*glyph_info) = PyMem_New(GlyphInfo, count);
if ((*glyph_info) == NULL) {
PyErr_SetString(PyExc_MemoryError, "PyMem_New() failed");
return 0;
}
load_flags = FT_LOAD_DEFAULT;
if (mask) {
load_flags |= FT_LOAD_TARGET_MONO;
}
if (color) {
load_flags |= FT_LOAD_COLOR;
}
for (i = 0; i < count; i++) {
if (buffer) {
ch = buffer[i];
} else {
ch = PyUnicode_READ_CHAR(string, i);
}
(*glyph_info)[i].index = FT_Get_Char_Index(self->face, ch);

@hugovk
Copy link
Member

hugovk commented Oct 15, 2025

I'm on the fence with this. It feels outside the core focus of Pillow, and it's not too tricky to do this with Pillow in Python:

#9158 (comment)

Plus it's a even easier with a dedicated FreeType library:

#9158 (comment)

@glebm
Copy link

glebm commented Oct 20, 2025

A font is roughly a collection of images and checking if an image exists in the collection is pretty basic functionality?

Of course it's doable in other ways but:

  1. The pillow way suggested is verbose and inefficient.
  2. The freetype way requires loading the font twice (once in Pillow, once in Freetype).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature request: Check if glyph exists in font

3 participants