{"record":{"id":"bc5feffbec826577","repo":"deepfakes/faceswap","slug":"invalid-header-found-in-png-filename","errorCode":null,"errorMessage":"Invalid header found in png: {filename}","messagePattern":"Invalid header found in png: (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"lib/image.py","lineNumber":279,"sourceCode":"    \"\"\"\n    retval = {}\n    if os.path.splitext(filename)[-1].lower() != \".png\":\n        # Get the dimensions directly from the image for non-png\n        logger.trace(  # type:ignore[attr-defined]\n            \"Non png found. Loading file for dimensions: '%s'\",\n            filename)\n        img = cv2.imread(filename)\n        assert img is not None\n        retval[\"height\"], retval[\"width\"] = img.shape[:2]\n        return retval\n    with open(filename, \"rb\") as in_file:\n        try:\n            chunk = in_file.read(8)\n        except PermissionError as exc:\n            raise PermissionError(f\"PermissionError while reading: {filename}\") from exc\n\n        if chunk != b\"\\x89PNG\\r\\n\\x1a\\n\":\n            raise ValueError(f\"Invalid header found in png: {filename}\")\n\n        while True:\n            chunk = in_file.read(8)\n            length, field = struct.unpack(\">I4s\", chunk)\n            logger.trace(  # type:ignore[attr-defined]\n                \"Read chunk: (chunk: %s, length: %s, field: %s\",\n                chunk, length, field)\n            if not chunk or field == b\"IDAT\":\n                break\n            if field == b\"IHDR\":\n                # Get dimensions\n                chunk = in_file.read(8)\n                retval[\"width\"], retval[\"height\"] = struct.unpack(\">II\", chunk)\n                length -= 8\n            elif field == b\"iTXt\":\n                keyword, value = in_file.read(length).split(b\"\\0\", 1)\n                if keyword == b\"faceswap\":\n                    retval[\"itxt\"] = literal_eval(value[4:].decode(\"utf-8\", errors=\"replace\"))","sourceCodeStart":261,"sourceCodeEnd":297,"githubUrl":"https://github.com/deepfakes/faceswap/blob/f530cb7508ae670f6474f8a7d9c4df94705cf96b/lib/image.py#L261-L297","documentation":"Raised when the first 8 bytes of a file do not match the PNG magic signature (\\x89PNG\\r\\x1a\\n) in faceswap's lightweight PNG dimension reader. The library assumes files with a .png extension (or detected as png) start with a valid PNG header; a mismatch means the file is corrupt, truncated, or not actually a PNG.","triggerScenarios":"A file with a .png extension whose content is JPEG/WebP/other format, a truncated or zero-byte download, or a file that was renamed to .png without conversion. Hit when faceswap enumerates a folder and probes each file for PNG dimensions.","commonSituations":"Datasets scraped from the web with wrong extensions, images partially downloaded or corrupted by transfer, files double-compressed or re-saved by tools that mangled headers, mixed-format folders.","solutions":["Verify and re-convert the offending file: open it in an image editor or with PIL/cv2 and re-save as real PNG (or correct its extension to the actual format).","Remove corrupt files from the input folder; validate the dataset with a magic-byte check before running faceswap.","Re-download/re-transfer the file if it was truncated."],"exampleFix":"import struct\n\n# before: assume every .png is a png\n# after: validate magic bytes before handing folder to faceswap\nwith open(path, 'rb') as f:\n    if f.read(8) != b'\\x89PNG\\r\\n\\x1a\\n':\n        print('not a real png, skipping:', path)","handlingStrategy":"validation","validationCode":"PNG_MAGIC = b'\\x89PNG\\r\\n\\x1a\\n'\n\ndef is_png(path: str) -> bool:\n    with open(path, 'rb') as f:\n        return f.read(8) == PNG_MAGIC","typeGuard":null,"tryCatchPattern":"try:\n    meta = read_image_meta(path)\nexcept ValueError as err:\n    if 'Invalid header' in str(err):\n        quarantine.append(path)  # move aside and continue\n    else:\n        raise","preventionTips":["Pre-scan datasets verifying magic bytes match extensions.","Do not rename files to .png without converting them.","Remove zero-byte and truncated downloads before extraction."],"tags":["png","file-format","validation","corruption"],"backgroundTag":null,"analyzedSha":"f530cb7508ae670f6474f8a7d9c4df94705cf96b","analyzedAt":"2026-08-15T02:59:26.626Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}