Connexion Inscription
Intermédiaire Purebasic 6.4x

IFFImage – Chargeur d'images Amiga IFF

Module PureBasic de chargement des images Amiga IFF (ILBM et PBM) : 1 à 8 plans, EHB, HAM6/HAM8, 24/32 bits, compression ByteRun1, correction du ratio des pixels. Load/Catch comme LoadImage/CatchImage, sans aucune DLL.

IFFImage permet d'ouvrir dans PureBasic les images au format IFF, le format d'image de l'Amiga, utilisé par Deluxe Paint, Personal Paint, Brilliance et bien d'autres. Les fichiers .iff, .ilbm et .lbm produits par Deluxe Paint sur PC sont aussi reconnus.

Le module se pilote comme les commandes natives de PureBasic : IFFImage::Load() remplace LoadImage() et IFFImage::Catch() remplace CatchImage(). L'image obtenue est une image PureBasic standard, utilisable avec ImageGadget, DrawImage, SaveImage et le reste des commandes d'image.

Il est écrit entièrement en PureBasic, sans DLL ni bibliothèque externe. Il est robuste : les fichiers tronqués ou corrompus ne font pas planter le programme, et la mémoire source n'est jamais modifiée, ce qui permet de lire une même image plusieurs fois depuis une DataSection. Le rendu passe par DrawingBuffer(), ce qui le rend nettement plus rapide qu'un tracé pixel par pixel.

Formats pris en charge :

  • ILBM planaire de 1 à 8 plans (2 à 256 couleurs)
  • Extra Half Brite (EHB, 64 couleurs)
  • Hold And Modify : HAM6 (4 096 couleurs) et HAM8 (262 144 couleurs)
  • ILBM 24 bits et 32 bits (couleurs directes)
  • PBM chunky 8 bits et 24 bits (Deluxe Paint PC)
  • Compression ByteRun1 ou aucune compression
  • Images avec plan de masque

Fonctions pratiques :

  • Correction du ratio des pixels Amiga, en option (par exemple 320×200 affiché en 320×220)
  • Détection des anciennes palettes 4 bits ($X0 étendu en $XX)
  • Détection automatique de HAM et d'EHB quand le chunk CAMG est absent
  • Palette en niveaux de gris si le fichier n'en contient pas
  • IFFImage::IsIFF() pour savoir si un fichier est une image IFF avant de le charger

Utilisation :

exemple.pbPureBasic · 15 lignes
XIncludeFile "module_iffimage.pbi"

; Chargement simple
Define img = IFFImage::Load(#PB_Any, "deluxepaint.iff")

; Chargement avec correction du ratio des pixels Amiga, lissé
Define img2 = IFFImage::Load(#PB_Any, "hires.ilbm", #False, #PB_Image_Smooth)

; Depuis la mémoire
Define img3 = IFFImage::Catch(#PB_Any, ?Logo, ?LogoEnd - ?Logo)

DataSection
  Logo:    : IncludeBinary "logo.iff"
  LogoEnd:
EndDataSection

Paramètres :

Image : numéro de l'image, ou #PB_Any pour en générer un
KeepAspect : #True (défaut) garde les pixels tels quels, #False corrige le ratio Amiga
ResizeMode : #PB_Image_Raw (défaut) ou #PB_Image_Smooth, utilisé pour la correction du ratio

Valeur de retour : la même que LoadImage(), c'est-à-dire 0 en cas d'échec ^^.

Le code source

🔒 Copier / Télécharger le codeRéservé aux membres. Se connecter · Créer un compte
module_iffimage.pbiPureBasic · 511 lignes
DisableASM
CompilerIf Not #PB_Compiler_EnableExplicit
  EnableExplicit
CompilerEndIf

; ****************************************************************************
;-DeclareModule

DeclareModule IFFImage

  ; @IFFImage::Load()
  ; Charge une image IFF-ILBM ou IFF-PBM depuis un fichier.
  ; Image      : numéro de l'image, ou #PB_Any pour en générer un.
  ; FileName$  : nom du fichier (absolu ou relatif au répertoire courant).
  ; KeepAspect : #True  = garde les pixels tels quels (défaut).
  ;              #False = corrige le ratio des pixels Amiga (BMHD xAspect/yAspect).
  ; ResizeMode : #PB_Image_Raw (défaut) ou #PB_Image_Smooth, utilisé si KeepAspect = #False.
  ; Retour     : comme LoadImage() -> numéro si #PB_Any, sinon une valeur non nulle. 0 en cas d'échec.
  Declare.i Load(Image.i, FileName$, KeepAspect.i = #True, ResizeMode.i = #PB_Image_Raw)

  ; @IFFImage::Catch()
  ; Charge une image IFF-ILBM ou IFF-PBM depuis la mémoire (la mémoire n'est PAS modifiée).
  ; *Memory    : adresse des données.
  ; MemSize    : taille des données en octets (obligatoire, protège des fichiers corrompus).
  Declare.i Catch(Image.i, *Memory, MemSize.q, KeepAspect.i = #True, ResizeMode.i = #PB_Image_Raw)

  ; @IFFImage::IsIFF()
  ; Renvoie #True si la mémoire contient une image IFF-ILBM ou IFF-PBM.
  Declare.i IsIFF(*Memory, MemSize.q)

EndDeclareModule

; ****************************************************************************
;-Module

Module IFFImage

  DisableASM
  CompilerIf Not #PB_Compiler_EnableExplicit
    EnableExplicit
  CompilerEndIf

  ; ****************************************************************************
  ;-Macros

  ; Identifiant de chunk tel qu'il est lu par PeekL() (pas de conversion d'endian nécessaire)
  Macro MAKEID(a, b, c, d)
    ((a) | ((b) << 8) | ((c) << 16) | ((d) << 24))
  EndMacro

  ; Lecture big-endian (format Motorola) octet par octet : ne touche jamais la mémoire source
  Macro BE16(p)
    ((PeekA(p) << 8) | PeekA((p) + 1))
  EndMacro

  Macro BE32(p)
    ((PeekA(p) << 24) | (PeekA((p) + 1) << 16) | (PeekA((p) + 2) << 8) | PeekA((p) + 3))
  EndMacro

  ; ****************************************************************************
  ;-Constantes

  #ID_FORM = MAKEID('F','O','R','M') ; Fichier IFF
  #ID_ILBM = MAKEID('I','L','B','M') ; Interleaved Bitmap (planaire)
  #ID_PBM  = MAKEID('P','B','M',' ') ; Portable Bitmap (chunky, DPaint PC)
  #ID_BMHD = MAKEID('B','M','H','D') ; Bitmap Header
  #ID_CMAP = MAKEID('C','M','A','P') ; Palette
  #ID_CAMG = MAKEID('C','A','M','G') ; Modes d'affichage Amiga
  #ID_BODY = MAKEID('B','O','D','Y') ; Données image

  #CAMG_EHB = $0080 ; Extra Half Brite
  #CAMG_HAM = $0800 ; Hold And Modify

  #CMP_None     = 0 ; Pas de compression
  #CMP_ByteRun1 = 1 ; Compression ByteRun1 (PackBits)

  #MSK_HasMask  = 1 ; Un plan de masque suit les plans de couleur sur chaque ligne

  ; ****************************************************************************
  ;-Structures

  Structure UBYTES
    b.a[0]
  EndStructure

  Structure BYTES
    b.b[0]
  EndStructure

  ; En-tête BMHD converti en valeurs natives
  Structure BMHD
    w.i
    h.i
    nPlanes.i
    masking.i
    compression.i
    tColor.i
    xAspect.i
    yAspect.i
  EndStructure

  ; Contexte de décodage
  Structure Decoder
    bmhd.BMHD
    form.l          ; #ID_ILBM ou #ID_PBM
    camg.l
    nColors.i       ; Nombre de couleurs lues dans le CMAP
    planeRowBytes.i ; ILBM : octets d'une ligne d'UN plan (multiple de 2)
    lineBytes.i     ; Octets d'une ligne complète (tous les plans + masque éventuel)
    cmap.l[256]     ; Palette au format RGB()
  EndStructure

  ; ****************************************************************************
  ;-Décompression

  ; Décompresse un flux ByteRun1 avec contrôle des bornes en entrée ET en sortie.
  Procedure.i UnpackByteRun1(*src.BYTES, srcSize.q, *dst, dstSize.q)
    Protected i.q, o.q, n.i, count.q
    While i < srcSize And o < dstSize
      n = *src\b[i] : i + 1
      If n >= 0
        ; Copie littérale de n+1 octets
        count = n + 1
        If count > srcSize - i : count = srcSize - i : EndIf
        If count > dstSize - o : count = dstSize - o : EndIf
        CopyMemory(*src + i, *dst + o, count)
        i + n + 1
        o + count
      ElseIf n <> -128
        ; Répétition de l'octet suivant 1-n fois
        If i >= srcSize : Break : EndIf
        count = 1 - n
        If count > dstSize - o : count = dstSize - o : EndIf
        FillMemory(*dst + o, count, *src\b[i] & $FF, #PB_Byte)
        i + 1
        o + count
      EndIf
    Wend
    ProcedureReturn o
  EndProcedure

  ; ****************************************************************************
  ;-Lecture des chunks

  Procedure ReadBMHD(*d.Decoder, *data)
    *d\bmhd\w           = BE16(*data)
    *d\bmhd\h           = BE16(*data + 2)
    *d\bmhd\nPlanes     = PeekA(*data + 8)
    *d\bmhd\masking     = PeekA(*data + 9)
    *d\bmhd\compression = PeekA(*data + 10)
    *d\bmhd\tColor      = BE16(*data + 12)
    *d\bmhd\xAspect     = PeekA(*data + 14)
    *d\bmhd\yAspect     = PeekA(*data + 15)
  EndProcedure

  Procedure ReadCMAP(*d.Decoder, *data.UBYTES, size.q)
    Protected i, n, r, g, b, lowBits
    n = size / 3
    If n > 256 : n = 256 : EndIf
    For i = 0 To n - 1
      r = *data\b[i * 3]
      g = *data\b[i * 3 + 1]
      b = *data\b[i * 3 + 2]
      lowBits | r | g | b
      *d\cmap[i] = RGB(r, g, b)
    Next
    ; Vieux fichiers Amiga : composantes sur 4 bits stockées en $X0.
    ; Si aucun quartet bas n'est utilisé, on étend $X0 -> $XX (sinon le blanc vaut $F0F0F0).
    If n And (lowBits & $0F) = 0
      For i = 0 To n - 1
        *d\cmap[i] | ((*d\cmap[i] >> 4) & $0F0F0F)
      Next
    EndIf
    *d\nColors = n
  EndProcedure

  Procedure PreparePalette(*d.Decoder, haveCMAP.i)
    Protected i, n, c, np = *d\bmhd\nPlanes
    If np > 8 : ProcedureReturn : EndIf ; 24/32 bits : couleurs directes

    ; Pas de CMAP : palette en niveaux de gris
    If Not haveCMAP
      n = 1 << np
      For i = 0 To n - 1
        c = i * 255 / (n - 1)
        *d\cmap[i] = RGB(c, c, c)
      Next
    EndIf

    ; Pas de CAMG en 6 plans : on devine le mode comme le font les lecteurs Amiga
    If *d\form = #ID_ILBM And np = 6 And (*d\camg & (#CAMG_HAM | #CAMG_EHB)) = 0
      If *d\nColors = 16
        *d\camg | #CAMG_HAM
      ElseIf *d\nColors = 32
        *d\camg | #CAMG_EHB
      EndIf
    EndIf

    ; EHB : les couleurs 32-63 sont les couleurs 0-31 à demi-intensité
    If *d\camg & #CAMG_EHB And np = 6
      For i = 0 To 31
        *d\cmap[i + 32] = (*d\cmap[i] >> 1) & $7F7F7F
      Next
    EndIf
  EndProcedure

  ; ****************************************************************************
  ;-Rendu

  ; Convertit une ligne planaire en indices chunky (un bit par plan).
  ; En 24/32 plans, les plans 0-7 / 8-15 / 16-23 donnent directement une valeur au format RGB().
  Procedure PlanarToChunky(*pl.UBYTES, planeRowBytes.i, nPlanes.i, Array idx.l(1))
    Protected plane, xb, v, x, bit
    FillMemory(@idx(0), planeRowBytes * 8 * SizeOf(Long), 0, #PB_Long)
    For plane = 0 To nPlanes - 1
      bit = 1 << plane
      For xb = 0 To planeRowBytes - 1
        v = *pl\b[xb]
        If v ; Octet vide = 8 pixels sans ce bit : on saute
          x = xb << 3
          If v & $80 : idx(x)     | bit : EndIf
          If v & $40 : idx(x + 1) | bit : EndIf
          If v & $20 : idx(x + 2) | bit : EndIf
          If v & $10 : idx(x + 3) | bit : EndIf
          If v & $08 : idx(x + 4) | bit : EndIf
          If v & $04 : idx(x + 5) | bit : EndIf
          If v & $02 : idx(x + 6) | bit : EndIf
          If v & $01 : idx(x + 7) | bit : EndIf
        EndIf
      Next
      *pl + planeRowBytes
    Next
  EndProcedure

  ; Doit être appelée entre StartDrawing() et StopDrawing()
  Procedure Render(*d.Decoder, *body)
    Protected w = *d\bmhd\w, h = *d\bmhd\h, np = *d\bmhd\nPlanes
    Protected x, y, c, v, e, o
    Protected *row.UBYTES, *dst.UBYTES, *buf, pitch, fmt, reversed, bpp, bgr
    Protected ham, hamBits, hamMask, hamUp, hamDown
    Protected Dim line.l(w)
    Protected Dim idx.l(*d\planeRowBytes * 8)

    ; Accès direct au buffer de l'image (bien plus rapide que Plot)
    *buf = DrawingBuffer()
    If *buf
      pitch    = DrawingBufferPitch()
      fmt      = DrawingBufferPixelFormat()
      reversed = fmt & #PB_PixelFormat_ReversedY
      Select fmt & ~#PB_PixelFormat_ReversedY
        Case #PB_PixelFormat_24Bits_RGB : bpp = 3
        Case #PB_PixelFormat_24Bits_BGR : bpp = 3 : bgr = #True
        Case #PB_PixelFormat_32Bits_RGB : bpp = 4
        Case #PB_PixelFormat_32Bits_BGR : bpp = 4 : bgr = #True
      EndSelect
    EndIf

    ; HAM6 (6 plans, 4 bits de valeur) ou HAM8 (8 plans, 6 bits de valeur)
    If *d\form = #ID_ILBM And (*d\camg & #CAMG_HAM) And (np = 6 Or np = 8)
      ham     = #True
      hamBits = np - 2
      hamMask = (1 << hamBits) - 1
      hamUp   = 8 - hamBits       ; Étend la valeur sur 8 bits :
      hamDown = 2 * hamBits - 8   ; HAM6 : v<<4|v   HAM8 : v<<2|v>>4
    EndIf

    For y = 0 To h - 1
      *row = *body + y * *d\lineBytes

      ; --- Décodage d'une ligne en couleurs RGB() ---
      If *d\form = #ID_PBM
        If np = 8
          For x = 0 To w - 1
            line(x) = *d\cmap[*row\b[x]]
          Next
        Else
          For x = 0 To w - 1
            o = x * 3
            line(x) = RGB(*row\b[o], *row\b[o + 1], *row\b[o + 2])
          Next
        EndIf
      Else
        PlanarToChunky(*row, *d\planeRowBytes, np, idx())
        If np > 8
          For x = 0 To w - 1
            line(x) = idx(x) & $FFFFFF
          Next
        ElseIf ham
          c = *d\cmap[0] ; Chaque ligne HAM part de la couleur de fond
          For x = 0 To w - 1
            v = idx(x)
            e = v & hamMask
            e = (e << hamUp) | (e >> hamDown)
            Select v >> hamBits
              Case 0 : c = *d\cmap[v & hamMask]      ; Couleur de la palette
              Case 1 : c = (c & $00FFFF) | (e << 16) ; Modifie le bleu
              Case 2 : c = (c & $FFFF00) | e         ; Modifie le rouge
              Default: c = (c & $FF00FF) | (e << 8)  ; Modifie le vert
            EndSelect
            line(x) = c
          Next
        Else
          For x = 0 To w - 1
            line(x) = *d\cmap[idx(x) & $FF]
          Next
        EndIf
      EndIf

      ; --- Écriture de la ligne dans l'image ---
      If bpp
        If reversed
          *dst = *buf + (h - 1 - y) * pitch
        Else
          *dst = *buf + y * pitch
        EndIf
        o = 0
        For x = 0 To w - 1
          c = line(x)
          If bgr
            *dst\b[o] = c >> 16 : *dst\b[o + 1] = c >> 8 : *dst\b[o + 2] = c
          Else
            *dst\b[o] = c : *dst\b[o + 1] = c >> 8 : *dst\b[o + 2] = c >> 16
          EndIf
          If bpp = 4 : *dst\b[o + 3] = 255 : EndIf
          o + bpp
        Next
      Else
        ; Format de buffer inconnu : repli sur Plot()
        For x = 0 To w - 1
          Plot(x, y, line(x))
        Next
      EndIf
    Next
  EndProcedure

  ; ****************************************************************************
  ;-Décodage

  Procedure.i Decode(*d.Decoder, Image.i, *src, srcSize.q, haveCMAP.i, KeepAspect.i, ResizeMode.i)
    Protected w = *d\bmhd\w, h = *d\bmhd\h, np = *d\bmhd\nPlanes
    Protected bodySize.q, *body, *alloc, result.i, img.i, xa, ya

    If w <= 0 Or h <= 0 : ProcedureReturn 0 : EndIf

    ; Taille d'une ligne selon le format
    If *d\form = #ID_ILBM
      If Not ((np >= 1 And np <= 8) Or np = 24 Or np = 32) : ProcedureReturn 0 : EndIf
      *d\planeRowBytes = ((w + 15) >> 4) << 1
      *d\lineBytes     = *d\planeRowBytes * np
      If *d\bmhd\masking = #MSK_HasMask
        *d\lineBytes + *d\planeRowBytes ; Plan de masque à sauter
      EndIf
    Else
      If np <> 8 And np <> 24 : ProcedureReturn 0 : EndIf
      *d\lineBytes = w * (np >> 3)
      *d\lineBytes + (*d\lineBytes & 1) ; Lignes PBM alignées sur un mot
    EndIf
    bodySize = *d\lineBytes * h

    ; Préparation du BODY
    Select *d\bmhd\compression
      Case #CMP_None
        If srcSize >= bodySize
          *body = *src ; Lecture directe, aucune copie
        Else
          *alloc = AllocateMemory(bodySize) ; Fichier tronqué : complété par du noir
          If *alloc And srcSize > 0 : CopyMemory(*src, *alloc, srcSize) : EndIf
          *body = *alloc
        EndIf
      Case #CMP_ByteRun1
        *alloc = AllocateMemory(bodySize)
        If *alloc : UnpackByteRun1(*src, srcSize, *alloc, bodySize) : EndIf
        *body = *alloc
      Default
        ProcedureReturn 0 ; Compression non gérée
    EndSelect
    If *body = 0 : ProcedureReturn 0 : EndIf

    PreparePalette(*d, haveCMAP)

    result = CreateImage(Image, w, h, 24, 0)
    If result
      If Image = #PB_Any : img = result : Else : img = Image : EndIf
      If StartDrawing(ImageOutput(img))
        Render(*d, *body)
        StopDrawing()
      EndIf

      ; Correction du ratio des pixels (ex. 320x200 en 10:11, 640x200 en 5:11)
      If KeepAspect = #False
        xa = *d\bmhd\xAspect
        ya = *d\bmhd\yAspect
        If xa And ya And xa <> ya
          If xa > ya
            ResizeImage(img, (w * xa + ya / 2) / ya, h, ResizeMode)
          Else
            ResizeImage(img, w, (h * ya + xa / 2) / xa, ResizeMode)
          EndIf
        EndIf
      EndIf
    EndIf

    If *alloc : FreeMemory(*alloc) : EndIf
    ProcedureReturn result
  EndProcedure

  ; ****************************************************************************
  ;-Public

  Procedure.i IsIFF(*Memory, MemSize.q)
    If *Memory And MemSize >= 12 And PeekL(*Memory) = #ID_FORM
      Select PeekL(*Memory + 8)
        Case #ID_ILBM, #ID_PBM
          ProcedureReturn #True
      EndSelect
    EndIf
    ProcedureReturn #False
  EndProcedure

  Procedure.i Catch(Image.i, *Memory, MemSize.q, KeepAspect.i = #True, ResizeMode.i = #PB_Image_Raw)
    Protected d.Decoder, *p, *data, *end, id.l, size.q, formSize.q
    Protected haveBMHD, haveCMAP, *bodyData, bodySize.q

    If Not IsIFF(*Memory, MemSize) : ProcedureReturn 0 : EndIf
    d\form = PeekL(*Memory + 8)

    ; Fin des données = la plus petite des deux tailles (FORM ou mémoire)
    formSize = BE32(*Memory + 4) & $FFFFFFFF
    *end = *Memory + MemSize
    If formSize + 8 < MemSize : *end = *Memory + formSize + 8 : EndIf

    *p = *Memory + 12
    While *p + 8 <= *end
      id    = PeekL(*p)
      size  = BE32(*p + 4) & $FFFFFFFF
      *data = *p + 8
      If size < 0 Or size > *end - *data
        size = *end - *data ; Chunk tronqué : on garde ce qui existe
      EndIf
      Select id
        Case #ID_BMHD
          If size >= 20
            ReadBMHD(@d, *data)
            haveBMHD = #True
          EndIf
        Case #ID_CMAP
          ReadCMAP(@d, *data, size)
          haveCMAP = #True
        Case #ID_CAMG
          If size >= 4 : d\camg = BE32(*data) : EndIf
        Case #ID_BODY
          *bodyData = *data
          bodySize  = size
          Break
      EndSelect
      *p = *data + size + (size & 1) ; Les chunks sont alignés sur un mot
    Wend

    If haveBMHD And *bodyData
      ProcedureReturn Decode(@d, Image, *bodyData, bodySize, haveCMAP, KeepAspect, ResizeMode)
    EndIf
    ProcedureReturn 0
  EndProcedure

  Procedure.i Load(Image.i, FileName$, KeepAspect.i = #True, ResizeMode.i = #PB_Image_Raw)
    Protected result.i, file.i, fileSize.q, *fileData
    file = ReadFile(#PB_Any, FileName$)
    If file
      fileSize = Lof(file)
      If fileSize >= 12
        *fileData = AllocateMemory(fileSize, #PB_Memory_NoClear)
        If *fileData
          If ReadData(file, *fileData, fileSize) = fileSize
            result = Catch(Image, *fileData, fileSize, KeepAspect, ResizeMode)
          EndIf
          FreeMemory(*fileData)
        EndIf
      EndIf
      CloseFile(file)
    EndIf
    ProcedureReturn result
  EndProcedure

EndModule

; ****************************************************************************
;-Test (sans Debug : affichage dans une fenêtre)

CompilerIf #PB_Compiler_IsMainFile

  Define file$, img, t, aspect, win
  file$ = OpenFileRequester("Image IFF", "", "IFF/LBM|*.iff;*.ilbm;*.lbm;*.ham;*.pic|Tous|*.*", 0)
  If file$
    aspect = Bool(MessageRequester("IFFImage", "Corriger le ratio des pixels Amiga ?", #PB_MessageRequester_YesNo) <> #PB_MessageRequester_Yes)
    t   = ElapsedMilliseconds()
    img = IFFImage::Load(#PB_Any, file$, aspect, #PB_Image_Smooth)
    t   = ElapsedMilliseconds() - t
    If img
      win = OpenWindow(#PB_Any, 0, 0, ImageWidth(img), ImageHeight(img),
                       GetFilePart(file$) + " - " + ImageWidth(img) + "x" + ImageHeight(img) + " - " + t + " ms",
                       #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
      If win
        ImageGadget(#PB_Any, 0, 0, ImageWidth(img), ImageHeight(img), ImageID(img))
        Repeat : Until WaitWindowEvent() = #PB_Event_CloseWindow
      EndIf
    Else
      MessageRequester("IFFImage", "Impossible de charger : " + file$, #PB_MessageRequester_Error)
    EndIf
  EndIf

CompilerEndIf

Avis des membres

– Pas encore d’avis
5 ★0
4 ★0
3 ★0
2 ★0
1 ★0

Vous utilisez ce code ? Donnez-lui une note.

Se connecter pour noter Pas de compte ? Inscription gratuite

Soyez le premier à donner votre avis.