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);

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
1 participant