PCXImage – Chargement d'images PCX
Module PureBasic de chargement d'images PCX (ZSoft Paintbrush) : 1, 2, 4, 8 et 24 bits, palettes EGA et VGA, décompression RLE sécurisée. Charge depuis un fichier ou depuis la mémoire (IncludeBinary). Windows, Linux et macOS, sans DLL.
Le format PCX, créé par ZSoft pour PC Paintbrush, a été l'un des formats d'image les plus utilisés sous DOS, notamment dans les jeux et la demoscene. PureBasic ne sait pas le lire nativement : ce module comble ce manque en quelques lignes, sans aucune bibliothèque externe.
Il décode toutes les variantes courantes du format, du monochrome au 24 bits, et renvoie une image PureBasic standard, utilisable directement avec ImageGadget, DrawImage ou les fonctions 2D. Le décodage est protégé contre les fichiers abîmés ou tronqués, et l'image est construite directement dans le DrawingBuffer pour un chargement rapide.
Fonctionnalités :
- Formats 1 bit (monochrome), 2 bits (CGA), 4 bits (EGA, en plans ou en compact), 8 bits (256 couleurs) et 24 bits
- Palette VGA de fin de fichier, palette EGA de l'en-tête, palette EGA par défaut si aucune n'est fournie
- Décompression RLE protégée (ne lit et n'écrit jamais en dehors des tampons)
- Chargement depuis un fichier (LoadPCXImage) ou depuis la mémoire (CatchPCXImage)
- Écriture directe dans le DrawingBuffer, avec repli sur Plot() si besoin
- Module autonome, compatible EnableExplicit, x86 et x64
Exemple d'utilisation :
XIncludeFile "module_pcximage.pbi"
; Depuis un fichier
Define img = loadimagePCX::LoadPCXImage("logo.pcx")
; Depuis la mémoire (image intégrée à l'exécutable)
Define img2 = loadimagePCX::CatchPCXImage(?LogoPCX, ?LogoPCX_End - ?LogoPCX)
DataSection
LogoPCX: : IncludeBinary "logo.pcx" : LogoPCX_End:
EndDataSection
Le code source
DisableASM
CompilerIf Not #PB_Compiler_EnableExplicit
EnableExplicit
CompilerEndIf
; ****************************************************************************
;-DeclareModule
DeclareModule PCXImage
Declare.i CatchPCXImage(*buffer, size.i)
Declare.i LoadPCXImage(filename.s)
EndDeclareModule
; ****************************************************************************
;-Module
Module PCXImage
DisableASM
CompilerIf Not #PB_Compiler_EnableExplicit
EnableExplicit
CompilerEndIf
; Entete PCX : 128 octets (les structures PureBasic ne sont pas alignees)
Structure pcx_fileheader
manufactor.a ; toujours 10 (ZSoft)
version.a ; 0, 2, 3, 4 ou 5
encoding.a ; 1 = RLE (0 = brut, rare)
bitsperpixel.a ; bits par pixel ET par plan
xmin.u
ymin.u
xmax.u
ymax.u
hdpi.u
vdpi.u
colormap.a[48] ; palette 16 couleurs (EGA)
reserved.a
bitplan.a ; nombre de plans
bytesperline.u ; octets par ligne ET par plan (toujours pair)
palette_info.u
hscreen.u
vscreen.u
filler.a[54]
EndStructure
Structure pcx_rgb
r.a
g.a
b.a
EndStructure
; ****************************************************************************
; Decode une image PCX deja en memoire (fichier charge ou IncludeBinary)
; @author LERICQUE Jean-Yves
; @return numero d'image #PB_Any, ou 0 en cas d'echec
Procedure.i CatchPCXImage(*buffer, size.i)
Protected *h.pcx_fileheader = *buffer
Protected width, height, bpp, planes, bpl, scansize, total, mask
Protected *data, *src, *srcend, *dst, *dstend, *line
Protected count, value, i, x, y, p, index, byte, shift, haspal
Protected image, *out, *pix, pitch, format, outbpp, reversed, bgr
Protected r, g, b
Protected Dim pal.pcx_rgb(255)
; --- Validation de l'entete -------------------------------------------
If *buffer = 0 Or size <= SizeOf(pcx_fileheader)
ProcedureReturn 0
EndIf
If *h\manufactor <> 10 Or *h\encoding > 1
ProcedureReturn 0
EndIf
width = *h\xmax - *h\xmin + 1
height = *h\ymax - *h\ymin + 1
bpp = *h\bitsperpixel
planes = *h\bitplan
bpl = *h\bytesperline
If width <= 0 Or height <= 0 Or width > 32767 Or height > 32767
ProcedureReturn 0
EndIf
; Combinaisons bits/plans reconnues
Select bpp
Case 1
If planes < 1 Or planes > 4 : ProcedureReturn 0 : EndIf ; mono, EGA planaire
Case 2, 4
If planes <> 1 : ProcedureReturn 0 : EndIf ; CGA, 16 couleurs packed
Case 8
If planes <> 1 And planes <> 3 And planes <> 4 ; 256 couleurs, 24 bits
ProcedureReturn 0
EndIf
Default
ProcedureReturn 0
EndSelect
If bpl < ((width * bpp) + 7) / 8
ProcedureReturn 0
EndIf
; --- Decompression RLE de toute l'image dans un tampon ----------------
; Une ligne = bytesperline * planes. On decode en continu : si un
; encodeur fait deborder une repetition sur la ligne suivante, ca marche.
scansize = bpl * planes
total = scansize * height
*data = AllocateMemory(total) ; mis a zero : fichier tronque = fin noire
If *data = 0
ProcedureReturn 0
EndIf
*src = *buffer + SizeOf(pcx_fileheader)
*srcend = *buffer + size
*dst = *data
*dstend = *data + total
If *h\encoding = 1
While *dst < *dstend And *src < *srcend
value = PeekA(*src) : *src + 1
If (value & $C0) = $C0
count = value & $3F
If *src >= *srcend : Break : EndIf
value = PeekA(*src) : *src + 1
If count > *dstend - *dst
count = *dstend - *dst
EndIf
FillMemory(*dst, count, value, #PB_Ascii)
*dst + count
Else
PokeA(*dst, value) : *dst + 1
EndIf
Wend
Else
count = *srcend - *src
If count > total : count = total : EndIf
CopyMemory(*src, *data, count)
EndIf
; --- Palette -----------------------------------------------------------
If bpp = 8 And planes = 1
; 256 couleurs : palette en fin de fichier, precedee de l'octet $0C
haspal = #False
If size >= SizeOf(pcx_fileheader) + 769
*pix = *buffer + size - 769
If PeekA(*pix) = $0C
*pix + 1
For i = 0 To 255
pal(i)\r = PeekA(*pix)
pal(i)\g = PeekA(*pix + 1)
pal(i)\b = PeekA(*pix + 2)
*pix + 3
Next
haspal = #True
EndIf
EndIf
If Not haspal ; pas de palette : niveaux de gris
For i = 0 To 255
pal(i)\r = i : pal(i)\g = i : pal(i)\b = i
Next
EndIf
ElseIf bpp = 1 And planes = 1
; Monochrome
pal(0)\r = 0 : pal(0)\g = 0 : pal(0)\b = 0
pal(1)\r = 255 : pal(1)\g = 255 : pal(1)\b = 255
ElseIf bpp * planes <= 4
; 4 ou 16 couleurs : palette de l'entete, sinon palette EGA par defaut
haspal = #False
If *h\version <> 3 ; version 3 = "pas de palette"
For i = 0 To 47
If *h\colormap[i]
haspal = #True
Break
EndIf
Next
EndIf
If haspal
For i = 0 To 15
pal(i)\r = *h\colormap[i * 3]
pal(i)\g = *h\colormap[i * 3 + 1]
pal(i)\b = *h\colormap[i * 3 + 2]
Next
Else
Restore EGAPalette
For i = 0 To 15
Read.a pal(i)\r
Read.a pal(i)\g
Read.a pal(i)\b
Next
EndIf
EndIf
mask = (1 << bpp) - 1
; --- Rendu dans l'image ------------------------------------------------
image = CreateImage(#PB_Any, width, height, 24)
If image = 0
FreeMemory(*data)
ProcedureReturn 0
EndIf
If StartDrawing(ImageOutput(image)) = 0
FreeImage(image)
FreeMemory(*data)
ProcedureReturn 0
EndIf
; Ecriture directe dans le DrawingBuffer (beaucoup plus rapide que Plot)
*out = DrawingBuffer()
pitch = DrawingBufferPitch()
format = DrawingBufferPixelFormat()
reversed = Bool(format & #PB_PixelFormat_ReversedY) ; Windows : lignes a l'envers
format = format & ~#PB_PixelFormat_ReversedY
Select format
Case #PB_PixelFormat_24Bits_RGB : outbpp = 3 : bgr = #False
Case #PB_PixelFormat_24Bits_BGR : outbpp = 3 : bgr = #True
Case #PB_PixelFormat_32Bits_RGB : outbpp = 4 : bgr = #False
Case #PB_PixelFormat_32Bits_BGR : outbpp = 4 : bgr = #True
Default : outbpp = 0 ; format inconnu : Plot()
EndSelect
If *out = 0 : outbpp = 0 : EndIf
For y = 0 To height - 1
*line = *data + (y * scansize)
If outbpp
If reversed
*pix = *out + ((height - 1 - y) * pitch)
Else
*pix = *out + (y * pitch)
EndIf
EndIf
For x = 0 To width - 1
If bpp = 8 And planes >= 3
; 24 bits : un plan R, un plan G, un plan B (4e plan alpha ignore)
r = PeekA(*line + x)
g = PeekA(*line + bpl + x)
b = PeekA(*line + (bpl * 2) + x)
Else
; Indexe : on assemble l'index plan par plan
index = 0
shift = 8 - bpp - ((x * bpp) & 7)
For p = 0 To planes - 1
byte = PeekA(*line + (p * bpl) + ((x * bpp) >> 3))
index = index | (((byte >> shift) & mask) << (p * bpp))
Next
r = pal(index)\r
g = pal(index)\g
b = pal(index)\b
EndIf
If outbpp
If bgr
PokeA(*pix, b) : PokeA(*pix + 1, g) : PokeA(*pix + 2, r)
Else
PokeA(*pix, r) : PokeA(*pix + 1, g) : PokeA(*pix + 2, b)
EndIf
If outbpp = 4
PokeA(*pix + 3, 255)
EndIf
*pix + outbpp
Else
Plot(x, y, RGB(r, g, b))
EndIf
Next
Next
StopDrawing()
FreeMemory(*data)
ProcedureReturn image
EndProcedure
; ****************************************************************************
; Charge un fichier PCX
; @author LERICQUE Jean-Yves
; @return numero d'image #PB_Any, ou 0 en cas d'echec
Procedure.i LoadPCXImage(filename.s)
Protected file, size, *buffer, image
file = ReadFile(#PB_Any, filename)
If file
size = Lof(file)
If size > SizeOf(pcx_fileheader)
*buffer = AllocateMemory(size, #PB_Memory_NoClear)
If *buffer
If ReadData(file, *buffer, size) = size
image = CatchPCXImage(*buffer, size)
EndIf
FreeMemory(*buffer)
EndIf
EndIf
CloseFile(file) ; toujours ferme, meme en cas d'echec
EndIf
ProcedureReturn image
EndProcedure
; ****************************************************************************
DataSection
EGAPalette:
Data.a $00,$00,$00, $00,$00,$AA, $00,$AA,$00, $00,$AA,$AA
Data.a $AA,$00,$00, $AA,$00,$AA, $AA,$55,$00, $AA,$AA,$AA
Data.a $55,$55,$55, $55,$55,$FF, $55,$FF,$55, $55,$FF,$FF
Data.a $FF,$55,$55, $FF,$55,$FF, $FF,$FF,$55, $FF,$FF,$FF
EndDataSection
EndModule
; ****************************************************************************
CompilerIf #PB_Compiler_IsMainFile = 1
Define event.i
Define ImagePCX.i
Define filename.s
If OpenWindow(0, 0, 0, 800, 600, "LoadPCX", #PB_Window_SystemMenu | #PB_Window_MinimizeGadget | #PB_Window_MaximizeGadget | #PB_Window_SizeGadget | #PB_Window_ScreenCentered)
ScrollAreaGadget(0, 0, 0, 800, 600, 800, 600)
ImageGadget(1, 0, 0, 0, 0, 0)
CloseGadgetList()
filename = OpenFileRequester("Ouvrir un fichier PCX", "", "Image pcx|*.pcx|Tous les fichiers|*.*", 0)
If filename
ImagePCX = PCXImage::LoadPCXImage(filename)
If ImagePCX
SetGadgetState(1, ImageID(ImagePCX))
SetGadgetAttribute(0, #PB_ScrollArea_InnerWidth, ImageWidth(ImagePCX))
SetGadgetAttribute(0, #PB_ScrollArea_InnerHeight, ImageHeight(ImagePCX))
SetWindowTitle(0, "LoadPCX - " + GetFilePart(filename) + " (" + Str(ImageWidth(ImagePCX)) + " x " + Str(ImageHeight(ImagePCX)) + ")")
Else
MessageRequester("LoadPCX", "Impossible de charger :" + #LF$ + filename, #PB_MessageRequester_Error)
EndIf
EndIf
Repeat
event = WaitWindowEvent()
If event = #PB_Event_SizeWindow
ResizeGadget(0, 0, 0, WindowWidth(0), WindowHeight(0))
EndIf
Until event = #PB_Event_CloseWindow
EndIf
CompilerEndIf
Avis des membres
Vous utilisez ce code ? Donnez-lui une note.
Se connecter pour noter Pas de compte ? Inscription gratuiteSoyez le premier à donner votre avis.
