A .png Name Is Not a Decodable Image: Inspect Your Project Folder Before Building a Gallery
Scan a project folder for decodable PNGs with Pillow. Use four explicit skip reasons and verify the checks with eleven local tests.

The scan returned one accepted file from a directory of five entries. The name was `valid.PNG`, the dimensions were 3 by 2 pixels, and the mode was RGB. A filter that only compared the extension would have offered four names. One of those names belonged to a directory. Another was an empty file. A third held a JPEG. The five entries are retained fixtures from the local run, so the difference can be reproduced without using anyone's photo collection.
The practical fix is to make the scanner return two lists. The accepted list supplies enough information to start a gallery. The skipped list explains which check excluded each remaining entry. An operator who sees an empty gallery can inspect that second list before assuming the images are missing or changing the display code.
Open the fixture inventory before opening a gallery
The directory contains `empty.png`, `fake.png`, `folder.png`, `picture.txt`, and `valid.PNG`. Their names were chosen so that file type, filename, and successful decoding can be checked independently. `folder.png` is a directory with a name that looks like a file. `empty.png` is a regular file with zero bytes. `fake.png` is a real JPEG with the wrong suffix. `picture.txt` holds valid PNG data with a suffix outside the project's rule. `valid.PNG` is a small RGB PNG that should be accepted. Nothing about this exercise depends on judging the appearance of a natural photograph.
`broken_candidates` lists names whose suffix case folds to `.png`. In the saved run it offered `empty.png`, `fake.png`, `folder.png`, and `valid.PNG`. The function returns names only, so it has no reason to distinguish a directory from a file or a JPEG from a PNG. The order in that baseline is the order observed in the saved directory run. The baseline does not sort its results. Its purpose is to reproduce the weakness of treating a name as a finished decision, rather than to serve as a second gallery scanner.
To make an equivalent test in your own project, place a real tiny PNG beside a directory ending in the same suffix. Add a zero-byte file and a JPEG saved under a PNG name. Keep the source fixtures distinct and use a directory you control. This makes it easy to inspect both the positive case and the three ways a matching name can mislead you. If your application is supposed to accept images by content even when the extension is wrong, add a valid PNG with a different suffix. That last file separates an intentional filename policy from an accident in the decoder.
Preserve the source fixture names and dimensions in the report. A name listed as skipped only tells you that a rule was reached. The contents tell you why that rule was the right one. For example, `fake.png` was excluded even though it is an image a JPEG-capable application can open. A project that permits both PNG and JPEG may decide to convert that file or fix its extension. The scanner used here deliberately accepts PNG only. The decision to support another format would need its own accepted fixture and a change to the contract.
Read the reason in the order the scanner checks it
The scanner first resolves the root with `strict=True` and checks that it is a directory. A missing root raises `FileNotFoundError` in the recorded test. A real file supplied as the root is rejected with `ValueError`. Those are problems with the scan request, not skip reasons for one child. A caller can present them as errors that require choosing a different root. A valid empty directory gives empty accepted and skipped lists, which is a separate, successful outcome.
Once the directory is open for iteration, the function sorts its direct entries using the case folded name and then the original name. This makes the order of the output lists understandable from the names that Python actually saw. It does not change the stored name or rename any entry. A directory inside the root appears as a direct entry and can receive a skip reason. The scanner never descends into it to look for pictures. A project that needs recursion can define how to represent nested paths and whether they should be included at all before extending this loop.
The first reason is `not_file`. It means the path did not pass `is_file` at the time of the check. In the retained run this is the reason for `folder.png`. A name does not reach suffix inspection when this first check fails. In Python 3.12 this predicate can follow symbolic links to files. The fixtures use ordinary files and directories and the scanner is not a boundary for keeping arbitrary paths inside a trusted root. The predicate also does not guarantee that a later open will succeed. If a caller needs stronger rules about links, readability, or ownership, those are separate conditions to specify and test.
Path.iterdir yields directory children and Path.is_file checks whether a path points to a regular file. Python 3.12 pathlib reference
The second reason is `extension`. The scanner compares the folded suffix with `.png`, then preserves the exact original name in either list. This is why `valid.PNG` passes the extension rule while `picture.txt` is skipped. In the retained fixture, the latter was deliberately saved as PNG. It never reaches Pillow. If that file should appear in a real gallery, decide whether to adopt a content-first policy or correct the name after checking that it really holds the intended format. Removing the extension filter would change what files the decoder attempts to open.
Two more reasons come from inspecting the bytes. `format` means that Pillow opened the input but reported a format other than PNG. In the retained run it applies to the JPEG in `fake.png`. `decode_error` means that the open or load step raised one of the exceptions the scanner catches. `empty.png` received that reason and the recorded exception type was `UnidentifiedImageError`. Only that error branch adds an `error_type` field. A gallery report can use the reason as its main category and show the exception class only when the scanner supplies it.
Keep recognition and loading in the same inspection
For entries that pass the name and file checks, `Image.open` runs inside a context manager. The format comparison happens first. For a recognized PNG, the code calls `load` before reading size and mode into the record. This order matters because identifying the container and decoding the selected image data are two steps. An open call that returned an image object does not by itself show that the subsequent pixel read will succeed. By loading while the file is still in scope, the scanner reports the dimensions only after that additional check.
The accepted record contains the original name, a list of two dimensions, and the mode string. It contains neither the open file handle nor a copy of the image pixels. When the context manager exits, that file is closed. A later consumer that needs the image bytes must get them from somewhere. A build script might copy accepted assets into an output directory, create a thumbnail, or refer to a file already served by the application. Each action has its own error handling and output. The scanner's success says that this input passed the listed checks at the time it was read.
The code catches `UnidentifiedImageError` and `OSError` around the decoder operations. The scope of that block makes the skip reason useful. A caught exception during the selected open or load path can be recorded and scanning can proceed to the next entry. Failures to resolve the root are outside it. Other exception classes may also reach the caller. If a real project needs to log a permission problem differently from malformed bytes, design that mapping using evidence from its own read path. The local output confirms the class for the empty-file fixture, rather than a complete taxonomy of decoder failures.
Use the format rule to explain why a different input is rejected before it reaches the gallery. A JPEG under a PNG name did not fail because its image data was malformed. It was rejected because its actual format violated this scanner's contract. An empty file did not report a different recognized format. Its decoder could not identify it. These cases can have different repairs. One calls for a name correction or format conversion, while the other may need the original export to be recovered. A single label such as “bad image” would remove that distinction from the report.
scan_png.py
from pathlib import Path
from PIL import Image,UnidentifiedImageError
def broken_candidates(root):
return [p.name for p in Path(root).iterdir() if p.suffix.casefold()=='.png']
def scan_png(root):
root=Path(root).resolve(strict=True)
if not root.is_dir():raise ValueError('Expected directory')
accepted=[];skipped=[]
for path in sorted(root.iterdir(),key=lambda p:(p.name.casefold(),p.name)):
if not path.is_file():skipped.append({'name':path.name,'reason':'not_file'});continue
if path.suffix.casefold()!='.png':skipped.append({'name':path.name,'reason':'extension'});continue
try:
with Image.open(path) as image:
if image.format!='PNG':skipped.append({'name':path.name,'reason':'format'});continue
image.load();accepted.append({'name':path.name,'size':list(image.size),'mode':image.mode})
except (UnidentifiedImageError,OSError) as error:skipped.append({'name':path.name,'reason':'decode_error','error_type':type(error).__name__})
return {'accepted':accepted,'skipped':skipped}
Recorded local check: Eleven owned filesystem/Pillow methods. Suffix baseline includes directory, fixed nonrecursive scan checks is_file, extension, decodedPNGformat and load. Uppercase extension/Arabic name preserved; JPEGwithPNGname, emptyfile, wrongextension rejected/skipped. Trusted nonsymlink fixtures only; no arbitrary upload security, race defense, decompression resource limits, allframes/ICC/EXIF or performance test.; environment: Python 3.12.3 on Windows; Pillow 12.3.0
Confirm each boundary with a small assertion
Eleven local methods ran in Python 3.12.3 with Pillow 12.3.0. The baseline test checks that `broken_candidates` includes `folder.png`. The corrected directory test compares the entire skip list for that one entry, checking the name and reason together. The uppercase test saves a real PNG as `valid.PNG` and checks that the accepted record has size `[3, 2]`. It proves that a valid image with that extension reached acceptance in the fixture. The retained multi-entry scan also records the RGB mode and exact uppercase spelling.
The empty-file and JPEG tests read the reason strings from the resulting skip records. The valid PNG with a text extension produces `extension`. These tests are deliberately small enough that one failed assertion points to a specific boundary. In an adapted suite, keep a fixture for each reason even if several failures would produce the same visible placeholder in a gallery. If the label changes from `format` to `decode_error`, an operator may start looking for a damaged export when the actual issue is simply a name mismatch.
The test for a nested `inside.png` asserts that the accepted list is empty. It does not assert that the nested directory is absent from the skipped list. The loop still sees the direct directory entry, but it leaves its contents alone. Another test saves `مشهد.png` and reads back the exact name. The Arabic test is separate from the retained five-entry run. It demonstrates that this particular name survived the local path and result operations. A publishing step still has to handle how names become URLs or display captions.
The remaining tests give the caller examples of a successful empty inventory and two bad root inputs. If you put the sample into a project, try a separate test that passes the directory chosen by the real user-facing entry point. That proposed check can catch cases where a command uses a different root from the one the operator selected. Keep the expected result distinct from the scanner's tests. A correctly filtered directory can still be the wrong directory for the job.
One way to replay the experiment is to keep the fixture setup and the implementation together and run the supplied `unittest` discovery command against that directory. The tests create their temporary files under the owned example directory. If you copy the layout into your own application tests, use a temporary location reserved for the test and compare the resulting dictionaries. A separate saved example with several files makes it easier to understand how those one-case assertions combine in a realistic report.
Give the operator a way to act on skipped entries
Imagine that a gallery builder runs before a design review. The output shows one thumbnail, and a reviewer expected three. Instead of putting broken placeholders among the accepted photos, the build can write a separate inventory that shows which inputs were excluded. Start by grouping the entries by the reason returned by the scanner. For `not_file`, show the entry as a folder if it is one and explain that the current scan uses direct files. For `extension`, display the suffix that did not match and let the operator decide whether the file belongs in the gallery.
For `format`, the report can tell the operator that the decoder did not recognize the expected PNG format. This implementation records the reason and name only, so a report should not claim it can display the actual detected format for every skipped file. In the fixture we know `fake.png` is JPEG because we created it that way. If the operator needs that detail in the real report, extend the record to carry the format that Pillow reported before leaving the context manager, then test it against the renamed JPEG. That would be an additional feature to the current code.
For `decode_error`, show the known exception type when it is present. Avoid presenting every such entry as permanently damaged. An application can encounter a file before another process has finished writing it, or after access to its path has changed. If you design a workflow that copies assets into a folder, consider a point where completed assets become eligible for scanning. Give the copy step and the scanner an explicit handoff and test the order with your actual process. The retained run uses files that were prepared before the scan. It says nothing about a race between a writer and the decoder.
Reports also need a clear definition of success. A developer building a small proof could allow accepted files to proceed while reporting optional skipped entries. A release build might require every item from a curated list to appear. In the second case, compare that list of required names with the accepted records and signal which required file is missing. Counting all skips as failures would turn incidental text files and subdirectories into blockers. Counting only accepted items can hide missing required assets. A build can make that decision after the scan, using the project list that defines what is expected.
Choose an order for the report and another for the gallery when needed
The example sorts directory entries for a predictable report. The key compares folded names first and uses the original name to break ties. This sorting operation has no knowledge of the order in which pictures were taken or the sequence intended by a designer. It also does not convert numbers embedded in names to numeric values. In a folder containing `draft2.png` and `draft10.png`, a separate sequence rule could make the difference between a helpful review and a confusing one. Keep the acceptance rule independent so a change in presentation order does not change the result of checking a file.
If a project stores an explicit list of source names, compare it to the two lists returned by the scanner. A name missing from both lists can mean that it was not observed as a direct child. A name in the skipped list tells you that it was observed and failed a specific check. If a designer intentionally moves the file into a subfolder, the direct scan may report the folder itself instead of the moved file. That is an indication to review the selected root or the inventory rules rather than changing the decoder.
The two output lists also preserve relative ordering within each list. They do not preserve the complete interleaving of successes and skips. If an audit interface needs to reconstruct the exact traversal, it could save a single ordered sequence of decisions or record an input index on each entry. That is a proposed change to the output contract. The saved fixture report keeps the two lists because the gallery and the operator use them for different actions. If the same information serves a second consumer, decide whether it needs the order observed by the scanner or an order specified by the project.
Hand the accepted records to a builder with a defined lifetime
The function returns ordinary mutable dictionaries and lists. If you pass the results to several components, decide which one may annotate them. A gallery builder could copy each accepted record and add a thumbnail path for display. The inventory writer can retain the original observation. That makes it easier to see whether a later missing image was excluded by the scanner or failed while being prepared for the web. For a small command you may choose to return both pieces of information in a single report, with separate fields for discovery and export.
The accepted dimensions can help a builder plan a layout. It can reserve a rectangle based on the source size or a thumbnail size chosen separately. The scanner itself never opens a browser. It does not know whether the display layer applies rotation, uses the right URL, or loads the image before a user scrolls. If the downstream stage uses filenames in URLs, construct those URLs according to the web application's rules. The preserved name is a filesystem value. Spaces, non-ASCII characters, and punctuation still need appropriate handling at the URL and markup boundaries.
Once the scanner accepts a PNG, a separate operation can compare decoded PNG samples to answer an identity question. This scanner only decides which entries qualify. A project may discover two valid files with identical pixels or different names. Deciding whether to show both in a review is a policy about content and identifiers. It is useful to keep that decision after acceptance so a duplicate and a decode failure never receive the same explanation.
If you save a scan and use it later, keep track of the input directory and when it was read. A filename could be reused for a different image after the report was generated. The recorded size can then be accurate for the earlier file and wrong for the current one. An application that needs a frozen input set can use a controlled output copy or verify the files again at the point of use. If it only needs a current directory view, it can rebuild the inventory when the operator refreshes. Neither policy follows automatically from the metadata returned by this function.
Finally, decide how much of the scanner should be exposed to directories controlled by somebody else. The example reads trusted local fixtures, loads the selected image data, and checks one format. It makes no claim about validating every frame of an animated image, governing memory use for arbitrary input, or defending against path changes during the scan. A service that accepts uploads has a different input contract and requires controls that you can verify at that boundary. For a project folder you own, the narrow result here is already useful: it records which path matched the project's PNG policy and which check excluded each other entry.
Prepared with AI assistance and automated review. The original code was tested locally. The lead photograph illustrates the subject.



