Skip to main content
  • Home
  • Development
  • Documentation
  • Donate
  • Operational login
  • Browse the archive

swh logo
SoftwareHeritage
Software
Heritage
Archive
Features
  • Search

  • Downloads

  • Save code now

  • Add forge now

  • Help

  • ec325a8
  • /
  • byceps
  • /
  • util
  • /
  • image
  • /
  • image_type.py
Raw File Download

To reference or cite the objects present in the Software Heritage archive, permalinks based on SoftWare Hash IDentifiers (SWHIDs) must be used.
Select below a type of object currently browsed in order to display its associated SWHID and permalink.

  • content
  • directory
content badge
swh:1:cnt:edb3a793d959deb2eb7c580a3589c072cd052cd7
directory badge
swh:1:dir:01e24b3029b5a3da1a0baba5cb47691131055a54

This interface enables to generate software citations, provided that the root directory of browsed objects contains a citation.cff or codemeta.json file.
Select below a type of object currently browsed in order to generate citations for them.

  • content
  • directory
(requires biblatex-software package)
Generating citation ...
(requires biblatex-software package)
Generating citation ...
image_type.py
"""
byceps.util.image.image_type
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2014-2025 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""

from collections.abc import Iterable
from enum import Enum
from typing import BinaryIO

from byceps.util.result import Err, Ok, Result


ImageType = Enum('ImageType', ['gif', 'jpeg', 'png', 'svg', 'webp'])


def get_image_type_names(types: Iterable[ImageType]) -> frozenset[str]:
    """Return the names of the image types."""
    return frozenset(t.name.upper() for t in types)


def determine_image_type(
    stream: BinaryIO, allowed_types: frozenset[ImageType] | set[ImageType]
) -> Result[ImageType, str]:
    """Extract image type from stream."""
    image_type = guess_image_type(stream)

    if (image_type is None) or (image_type not in allowed_types):
        message = _get_image_type_prohibited_error_message(allowed_types)
        return Err(message)

    return Ok(image_type)


def _get_image_type_prohibited_error_message(
    allowed_types: frozenset[ImageType] | set[ImageType],
) -> str:
    allowed_type_names = get_image_type_names(allowed_types)
    allowed_type_names_string = ', '.join(sorted(allowed_type_names))

    return (
        f'Image is not one of the allowed types ({allowed_type_names_string}).'
    )


def guess_image_type(stream: BinaryIO) -> ImageType | None:
    """Return the guessed type, or `None` if the type could not be
    guessed or is not allowed (i.e. not a member of the enum).
    """
    header = stream.read(12)
    stream.seek(0)

    if _is_gif(header):
        return ImageType.gif
    elif _is_jpeg(header):
        return ImageType.jpeg
    elif _is_png(header):
        return ImageType.png
    elif _is_webp(header):
        return ImageType.webp

    if _is_svg(stream):
        return ImageType.svg

    return None


def _is_gif(header: bytes) -> bool:
    # See: https://www.w3.org/Graphics/GIF/spec-gif89a.txt
    return header[:6] in (b'GIF87a', b'GIF89a')


def _is_jpeg(header: bytes) -> bool:
    # See: https://en.wikipedia.org/wiki/JPEG#Syntax_and_structure
    jpeg_marker_soi = b'\xff\xd8'
    return header.startswith(jpeg_marker_soi)


def _is_png(header: bytes) -> bool:
    # See: https://tools.ietf.org/html/rfc2083#page-11
    return header.startswith(b'\x89PNG\r\n\x1a\n')


def _is_webp(header: bytes) -> bool:
    return header.startswith(b'RIFF') and header[8:12] == b'WEBP'


def _is_svg(stream: BinaryIO) -> bool:
    header = stream.read(80)
    stream.seek(0)

    return bool(
        header.startswith(b'<svg')
        or (header.startswith(b'<?xml version="1.0"') and header.find(b'<svg'))
    )

back to top

Software Heritage — Copyright (C) 2015–2026, The Software Heritage developers. License: GNU AGPLv3+.
The source code of Software Heritage itself is available on our development forge.
The source code files archived by Software Heritage are available under their own copyright and licenses.
Terms of use: Archive access, API— Content policy— Contact— JavaScript license information— Web API