Lecture de codes-barres pour PureBasic (zxing-cpp)
Module PureBasic de lecture des codes-barres 1D et 2D (QR Code, Data Matrix, PDF417, Aztec, EAN, Code 128…) basé sur zxing-cpp compilé en DLL x86 et x64 : détection et décodage directement depuis une image PureBasic.
Ce module permet de lire les codes-barres présents dans une image : photo, scan ou capture d'écran. Il s'appuie sur zxing-cpp, la version C++ de la célèbre bibliothèque open source ZXing (« Zebra Crossing »), compilée en DLL Windows 32 et 64 bits et fournie avec le source.
Il suffit de lui passer une image PureBasic chargée ou dessinée : le module détecte les codes présents et renvoie leur contenu et leur format. Il peut servir à lire des QR Codes, des étiquettes produits (EAN/UPC), des codes logistiques (Code 128, ITF) ou des documents officiels en Data Matrix comme le 2D-DOC.
Le module choisit automatiquement la bonne DLL selon que ton programme est compilé en x86 ou en x64.
Formats reconnus
- 2D : QR Code, Micro QR Code, rMQR, Data Matrix, PDF417, Aztec, MaxiCode
- 1D : EAN-8, EAN-13, UPC-A, UPC-E, Code 39, Code 93, Code 128, Codabar, ITF, DataBar
Fichiers fournis
module_zxing.pbi : le module PureBasic
zxing_x86.dll : zxing-cpp [version], 32 bits
zxing_x64.dll : zxing-cpp [version], 64 bits
LICENSE_zxing-cpp.txt : licence Apache 2.0 de zxing-cpp
Exemple d'utilisation
XIncludeFile "module_zxing.pbi"
UseJPEGImageDecoder()
UsePNGImageDecoder()
img = LoadImage(#PB_Any, "etiquette.png")
If img
resultat$ = [ZXing::Decode(img)]
If resultat$ <> ""
MessageRequester("ZXing", resultat$)
Else
MessageRequester("ZXing", "Aucun code-barres trouvé")
EndIf
EndIf
Licence
Le module PureBasic est gratuit et libre d'utilisation dans tes projets personnels ou professionnels. Merci de conserver l'entête KoakDesign — GallyHomeCorp.
Les DLL sont compilées à partir de zxing-cpp, distribuée sous licence Apache 2.0, et restent la propriété de leurs auteurs. Le texte complet de la licence est fourni dans LICENSE_zxing-cpp.txt. Le code source de zxing-cpp est disponible sur https://github.com/zxing-cpp/zxing-cpp.
Crédits
zxing-cpp : Axel Waggershauser et les contributeurs du projet ZXing
Le code source
; +===========================================================================+
; | |
; +---------------------------------------------------------------------------+
; | COPYRIGHT (C) 2026, ALL RIGHTS RESERVED KOAKDESIGN DEVELOPMENT. |
; +------------------+--------------------------------------------------------+
; | Purebasiv Ver. | PUREBASIC 4.40 |
; | Program Type | MODULE |
; +------------------+--------------------------------------------------------+
; | Version / Rev. | 0.0.1 |
; +------------------+--------------------------------------------------------+
; | Program Name | |
; | Executable Name | |
; +===========================================================================+
; | Original Version | 0.0.1 |
; +------------------+--------------------------------------------------------+
; | Created By | GallyHomeCorp |
; | Graphics By | |
; +==================+========================================================+
; | Comments |
; +---------------------------------------------------------------------------+
; | |
; | Program Type : Module (Include) - Lecture de codes-barres 1D / 2D |
; | QR Code, DataMatrix, PDF417, Aztec, EAN, Code 128, ... |
; | Version/Rev : 1.0.0 |
; | Created By : GallyHomeCorp |
; | Moteur : zxing-cpp 3.2.0 (Apache License 2.0) - API C |
; | |
; +=====================================+=====================================+
; | Operating System | Compilation Settings |
; +---------------------------------+---+---------------------------------+---+
; | Windows | X | Thread Management | X |
; | Linux | | OnError Management | |
; | macOS | | | |
; +---------------------------------+---+---------------------------------+---+
; | x86 (32-bit) | X | Administrator Rights | |
; | x64 (64-bit) | X | Special Privileges | |
; +=================================+===+=================================+===+
; *****************************************************************************
;- INITIALISATION DES DIRECTIVES DU COMPILEUR.
DisableASM
CompilerIf Not #PB_Compiler_EnableExplicit
EnableExplicit
CompilerEndIf
; *****************************************************************************
;-DeclareModule
DeclareModule ZXing
; --- Options de lecture (combinables avec |) ---
EnumerationBinary
#Opt_TryHarder ; recherche plus poussée (plus lent, plus fiable)
#Opt_TryRotate ; essaie 90/180/270°
#Opt_TryInvert ; codes en négatif (clair sur fond sombre)
#Opt_TryDownscale ; réduit les grandes images pour trouver les gros codes
#Opt_TryDenoise ; débruitage (scans sales)
#Opt_Pure ; image ne contenant QU'UN code, parfaitement cadré
EndEnumeration
#Opt_Defaut = #Opt_TryHarder | #Opt_TryRotate | #Opt_TryInvert | #Opt_TryDownscale
Structure CODE
Format$ ; "QR Code", "Data Matrix", "EAN-13", "Code 128"...
Texte$ ; contenu décodé (UTF-8 -> chaîne PB)
TypeContenu$ ; "Text", "Binary", "Mixed", "GS1"...
Rotation.l ; angle détecté en degrés
; Coins du code, en pixels, repère image (0,0 = haut-gauche)
X1.l : Y1.l ; haut-gauche
X2.l : Y2.l ; haut-droit
X3.l : Y3.l ; bas-droit
X4.l : Y4.l ; bas-gauche
EndStructure
Declare.i Init (Dll$ = "")
Declare Free ()
Declare.s Version ()
Declare.s DerniereErreur ()
; Formats$ : filtre optionnel, ex. "QRCode, DataMatrix" ou "EAN13, Code128" ("" = tous)
; Retour : nombre de codes trouvés, -1 en cas d'erreur (voir DerniereErreur())
Declare.i LireImage (Image, List Codes.CODE(), Options = #Opt_Defaut, Formats$ = "")
Declare.i LireFichier (Fichier$, List Codes.CODE(), Options = #Opt_Defaut, Formats$ = "")
EndDeclareModule
Module ZXing
EnableExplicit
UsePNGImageDecoder ()
UseJPEGImageDecoder ()
UseTIFFImageDecoder ()
CompilerIf #PB_Compiler_Processor = #PB_Processor_x64
#DLL_DEFAUT = "zxing_x64.dll"
CompilerElse
#DLL_DEFAUT = "zxing_x86.dll"
CompilerEndIf
; Formats de pixels ZXing (ZXing_ImageFormat)
#ZX_Fmt_RGB = $03000102
#ZX_Fmt_BGR = $03020100
#ZX_Fmt_RGBA = $04000102
#ZX_Fmt_BGRA = $04020100
Structure ZX_PointI
x.l : y.l
EndStructure
Structure ZX_Position
TopLeft.ZX_PointI
TopRight.ZX_PointI
BottomRight.ZX_PointI
BottomLeft.ZX_PointI
EndStructure
; --- Prototypes de l'API C (cdecl) ---
PrototypeC.i P_ImageView_new(*Data, Largeur.l, Hauteur.l, Format.l, RowStride.l, PixStride.l)
PrototypeC P_Delete(*Objet) ; tous les ZXing_xxx_delete et ZXing_free
PrototypeC.i P_New() ; ZXing_ReaderOptions_new
PrototypeC P_SetBool(*Opts, Valeur.l) ; ZXing_ReaderOptions_setXxx(bool)
PrototypeC P_SetFormats(*Opts, *Formats, Nombre.l)
PrototypeC.i P_FormatsFromString(Chaine.p-utf8, *Nombre)
PrototypeC.i P_ReadBarcodes(*ImageView, *Opts)
PrototypeC.l P_Size(*Barcodes)
PrototypeC.i P_At(*Barcodes, Index.l)
PrototypeC.l P_GetInt(*Barcode) ; format, contentType, rotation
PrototypeC.i P_GetStr(*Barcode) ; text -> char* à libérer
PrototypeC.i P_Position(*Resultat, *Barcode) ; struct renvoyée via pointeur caché
PrototypeC.i P_EnumToStr(Valeur.l) ; FormatToString / ContentTypeToString
PrototypeC.i P_Str() ; Version / LastErrorMsg
Global.i hDll
Global.s Erreur
Global ZX_ImageView_new.P_ImageView_new
Global ZX_ImageView_delete.P_Delete
Global ZX_ReaderOptions_new.P_New
Global ZX_ReaderOptions_delete.P_Delete
Global ZX_setTryHarder.P_SetBool
Global ZX_setTryRotate.P_SetBool
Global ZX_setTryInvert.P_SetBool
Global ZX_setTryDownscale.P_SetBool
Global ZX_setTryDenoise.P_SetBool
Global ZX_setIsPure.P_SetBool
Global ZX_setFormats.P_SetFormats
Global ZX_FormatsFromString.P_FormatsFromString
Global ZX_ReadBarcodes.P_ReadBarcodes
Global ZX_Barcodes_size.P_Size
Global ZX_Barcodes_at.P_At
Global ZX_Barcodes_delete.P_Delete
Global ZX_Barcode_format.P_GetInt
Global ZX_Barcode_contentType.P_GetInt
Global ZX_Barcode_rotation.P_GetInt
Global ZX_Barcode_text.P_GetStr
Global ZX_Barcode_position.P_Position
Global ZX_FormatToString.P_EnumToStr
Global ZX_ContentTypeToString.P_EnumToStr
Global ZX_Version.P_Str
Global ZX_LastErrorMsg.P_Str
Global ZX_free.P_Delete
Macro _Charge(Variable, Nom)
Variable = GetFunction(hDll, Nom)
If Variable = 0
Erreur = "Fonction absente de la DLL : " + Nom
Ok = #False
EndIf
EndMacro
; Convertit un char* UTF-8 alloué par ZXing en chaîne PB, puis le libère
Procedure.s _ChaineZX(*Ptr)
Protected Texte$
If *Ptr
Texte$ = PeekS(*Ptr, -1, #PB_UTF8)
ZX_free(*Ptr)
EndIf
ProcedureReturn Texte$
EndProcedure
Procedure.i Init(Dll$ = "")
Protected Ok = #True
If hDll : ProcedureReturn #True : EndIf
If Dll$ = "" : Dll$ = #DLL_DEFAUT : EndIf
hDll = OpenLibrary(#PB_Any, Dll$)
If hDll = 0
Erreur = "Impossible de charger " + Dll$
ProcedureReturn #False
EndIf
_Charge(ZX_ImageView_new, "ZXing_ImageView_new")
_Charge(ZX_ImageView_delete, "ZXing_ImageView_delete")
_Charge(ZX_ReaderOptions_new, "ZXing_ReaderOptions_new")
_Charge(ZX_ReaderOptions_delete, "ZXing_ReaderOptions_delete")
_Charge(ZX_setTryHarder, "ZXing_ReaderOptions_setTryHarder")
_Charge(ZX_setTryRotate, "ZXing_ReaderOptions_setTryRotate")
_Charge(ZX_setTryInvert, "ZXing_ReaderOptions_setTryInvert")
_Charge(ZX_setTryDownscale, "ZXing_ReaderOptions_setTryDownscale")
_Charge(ZX_setTryDenoise, "ZXing_ReaderOptions_setTryDenoise")
_Charge(ZX_setIsPure, "ZXing_ReaderOptions_setIsPure")
_Charge(ZX_setFormats, "ZXing_ReaderOptions_setFormats")
_Charge(ZX_FormatsFromString, "ZXing_BarcodeFormatsFromString")
_Charge(ZX_ReadBarcodes, "ZXing_ReadBarcodes")
_Charge(ZX_Barcodes_size, "ZXing_Barcodes_size")
_Charge(ZX_Barcodes_at, "ZXing_Barcodes_at")
_Charge(ZX_Barcodes_delete, "ZXing_Barcodes_delete")
_Charge(ZX_Barcode_format, "ZXing_Barcode_format")
_Charge(ZX_Barcode_contentType, "ZXing_Barcode_contentType")
_Charge(ZX_Barcode_rotation, "ZXing_Barcode_rotation")
_Charge(ZX_Barcode_text, "ZXing_Barcode_text")
_Charge(ZX_Barcode_position, "ZXing_Barcode_position")
_Charge(ZX_FormatToString, "ZXing_BarcodeFormatToString")
_Charge(ZX_ContentTypeToString, "ZXing_ContentTypeToString")
_Charge(ZX_Version, "ZXing_Version")
_Charge(ZX_LastErrorMsg, "ZXing_LastErrorMsg")
_Charge(ZX_free, "ZXing_free")
If Ok = #False
CloseLibrary(hDll) : hDll = 0
EndIf
ProcedureReturn Ok
EndProcedure
Procedure Free()
If hDll : CloseLibrary(hDll) : hDll = 0 : EndIf
EndProcedure
Procedure.s Version()
If hDll = 0 And Init() = #False : ProcedureReturn "" : EndIf
ProcedureReturn PeekS(ZX_Version(), -1, #PB_UTF8) ; const char* : ne pas libérer
EndProcedure
Procedure.s DerniereErreur()
ProcedureReturn Erreur
EndProcedure
Procedure.i LireImage(Image, List Codes.CODE(), Options = #Opt_Defaut, Formats$ = "")
Protected *Opts, *Liste, *IV, *Bcs, *Bc, *Buffer, *Debut
Protected Pitch, PixFmt, FmtZX, Largeur, Hauteur, Pas, NbFmt.l, n, i
Protected Pos.ZX_Position
ClearList(Codes())
Erreur = ""
If hDll = 0 And Init() = #False : ProcedureReturn -1 : EndIf
If IsImage(Image) = 0
Erreur = "Image invalide"
ProcedureReturn -1
EndIf
; --- Options de lecture ---
*Opts = ZX_ReaderOptions_new()
ZX_setTryHarder(*Opts, Bool(Options & #Opt_TryHarder))
ZX_setTryRotate(*Opts, Bool(Options & #Opt_TryRotate))
ZX_setTryInvert(*Opts, Bool(Options & #Opt_TryInvert))
ZX_setTryDownscale(*Opts, Bool(Options & #Opt_TryDownscale))
ZX_setTryDenoise(*Opts, Bool(Options & #Opt_TryDenoise))
ZX_setIsPure(*Opts, Bool(Options & #Opt_Pure))
If Formats$ <> ""
*Liste = ZX_FormatsFromString(Formats$, @NbFmt)
If *Liste = 0
Erreur = "Filtre de formats invalide : " + _ChaineZX(ZX_LastErrorMsg())
ZX_ReaderOptions_delete(*Opts)
ProcedureReturn -1
EndIf
ZX_setFormats(*Opts, *Liste, NbFmt)
ZX_free(*Liste)
EndIf
; --- On passe directement le buffer de l'image à ZXing (aucune copie) ---
If StartDrawing(ImageOutput(Image))
*Buffer = DrawingBuffer()
Pitch = DrawingBufferPitch()
PixFmt = DrawingBufferPixelFormat()
Largeur = OutputWidth()
Hauteur = OutputHeight()
Select PixFmt & ~#PB_PixelFormat_ReversedY
Case #PB_PixelFormat_32Bits_BGR : FmtZX = #ZX_Fmt_BGRA
Case #PB_PixelFormat_32Bits_RGB : FmtZX = #ZX_Fmt_RGBA
Case #PB_PixelFormat_24Bits_BGR : FmtZX = #ZX_Fmt_BGR
Case #PB_PixelFormat_24Bits_RGB : FmtZX = #ZX_Fmt_RGB
Default : FmtZX = 0
EndSelect
If FmtZX = 0
Erreur = "Format de pixels non géré ($" + Hex(PixFmt) + ")"
ElseIf *Buffer
; Sous Windows le buffer est stocké à l'envers (ReversedY) :
; on démarre sur la dernière ligne avec un pas négatif,
; ainsi ZXing "voit" l'image à l'endroit et les coordonnées sont justes.
If PixFmt & #PB_PixelFormat_ReversedY
*Debut = *Buffer + (Hauteur - 1) * Pitch
Pas = -Pitch
Else
*Debut = *Buffer
Pas = Pitch
EndIf
*IV = ZX_ImageView_new(*Debut, Largeur, Hauteur, FmtZX, Pas, 0)
If *IV
*Bcs = ZX_ReadBarcodes(*IV, *Opts)
If *Bcs = 0 : Erreur = _ChaineZX(ZX_LastErrorMsg()) : EndIf
ZX_ImageView_delete(*IV)
Else
Erreur = _ChaineZX(ZX_LastErrorMsg())
EndIf
EndIf
StopDrawing()
Else
Erreur = "StartDrawing() impossible sur l'image"
EndIf
ZX_ReaderOptions_delete(*Opts)
If *Bcs = 0 : ProcedureReturn -1 : EndIf
; --- Récupération des résultats ---
n = ZX_Barcodes_size(*Bcs)
For i = 0 To n - 1
*Bc = ZX_Barcodes_at(*Bcs, i) ; pointeur appartenant à *Bcs : ne pas libérer
If *Bc
AddElement(Codes())
Codes()\Format$ = _ChaineZX(ZX_FormatToString(ZX_Barcode_format(*Bc)))
Codes()\Texte$ = _ChaineZX(ZX_Barcode_text(*Bc))
Codes()\TypeContenu$ = _ChaineZX(ZX_ContentTypeToString(ZX_Barcode_contentType(*Bc)))
Codes()\Rotation = ZX_Barcode_rotation(*Bc)
ZX_Barcode_position(@Pos, *Bc)
Codes()\X1 = Pos\TopLeft\x : Codes()\Y1 = Pos\TopLeft\y
Codes()\X2 = Pos\TopRight\x : Codes()\Y2 = Pos\TopRight\y
Codes()\X3 = Pos\BottomRight\x : Codes()\Y3 = Pos\BottomRight\y
Codes()\X4 = Pos\BottomLeft\x : Codes()\Y4 = Pos\BottomLeft\y
EndIf
Next
ZX_Barcodes_delete(*Bcs)
ProcedureReturn ListSize(Codes())
EndProcedure
Procedure.i LireFichier(fichier.s, List Codes.CODE(), Options = #Opt_Defaut, formats.s = "")
Protected Image, Resultat
ClearList(Codes())
Image = LoadImage(#PB_Any, fichier)
If Image = 0
Erreur = "Impossible de charger l'image : " + fichier
ProcedureReturn -1
EndIf
Resultat = LireImage(Image, Codes(), Options, formats)
FreeImage(Image)
ProcedureReturn Resultat
EndProcedure
EndModule
; *****************************************************************************
;-
CompilerIf #PB_Compiler_IsMainFile = 1
Enumeration
#Fen
#Btn_Ouvrir
#Img_Gadget
#Liste
EndEnumeration
Global NewList Codes.ZXing::CODE()
Global ImgSource, ImgAffiche
; Dessine le contour de chaque code trouvé sur une copie de l'image
Procedure Afficher()
Protected Echelle.f, l, h
If ImgAffiche
FreeImage(ImgAffiche)
EndIf
ImgAffiche = CopyImage(ImgSource, #PB_Any)
If StartDrawing(ImageOutput(ImgAffiche))
ForEach Codes()
With Codes()
LineXY(\X1, \Y1, \X2, \Y2, RGB(255, 0, 0))
LineXY(\X2, \Y2, \X3, \Y3, RGB(255, 0, 0))
LineXY(\X3, \Y3, \X4, \Y4, RGB(255, 0, 0))
LineXY(\X4, \Y4, \X1, \Y1, RGB(255, 0, 0))
Circle(\X1, \Y1, 4, RGB(0, 200, 0)) ; coin haut-gauche
EndWith
Next
StopDrawing()
EndIf
; Mise à l'échelle pour l'affichage
l = ImageWidth(ImgAffiche) : h = ImageHeight(ImgAffiche)
Echelle = 780 / l
If h * Echelle > 440
Echelle = 440 / h
EndIf
If Echelle < 1
ResizeImage(ImgAffiche, l * Echelle, h * Echelle)
EndIf
SetGadgetState(#Img_Gadget, ImageID(ImgAffiche))
EndProcedure
Procedure Analyser(Fichier$)
Protected n, t
If ImgSource : FreeImage(ImgSource) : EndIf
ImgSource = LoadImage(#PB_Any, Fichier$)
If ImgSource = 0
MessageRequester("ZXing", "Impossible de charger " + Fichier$) : ProcedureReturn
EndIf
t = ElapsedMilliseconds()
n = ZXing::LireImage(ImgSource, Codes()) ; tous formats, options par défaut
; Exemple de filtre : ZXing::LireImage(ImgSource, Codes(), ZXing::#Opt_Defaut, "QRCode,DataMatrix")
t = ElapsedMilliseconds() - t
ClearGadgetItems(#Liste)
If n < 0
MessageRequester("ZXing", "Erreur : " + ZXing::DerniereErreur())
Else
ForEach Codes()
With Codes()
AddGadgetItem(#Liste, -1, \Format$ + Chr(10) + \Texte$ + Chr(10) + \TypeContenu$ + Chr(10) +
Str(\Rotation) + "°" + Chr(10) + Str(\X1) + "," + Str(\Y1))
Debug \Texte$
EndWith
Next
SetWindowTitle(#Fen, "Test ZXing " + ZXing::Version() + " - " + Str(n) + " code(s) en " + Str(t) + " ms")
Afficher()
EndIf
EndProcedure
If ZXing::Init() = #False
MessageRequester("ZXing", ZXing::DerniereErreur()) : End
EndIf
If OpenWindow(#Fen, 0, 0, 800, 640, "Test ZXing " + ZXing::Version(), #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
ButtonGadget(#Btn_Ouvrir, 10, 10, 160, 26, "Ouvrir une image...")
ImageGadget(#Img_Gadget, 10, 44, 780, 440, 0, #PB_Image_Border)
ListIconGadget(#Liste, 10, 492, 780, 138, "Format", 100, #PB_ListIcon_FullRowSelect | #PB_ListIcon_GridLines)
AddGadgetColumn(#Liste, 1, "Contenu", 420)
AddGadgetColumn(#Liste, 2, "Type", 70)
AddGadgetColumn(#Liste, 3, "Rot.", 50)
AddGadgetColumn(#Liste, 4, "Haut-gauche", 100)
If FileSize("page_test.png") > 0
Analyser("page_test.png")
EndIf
Define Fichier$
Repeat
Select WaitWindowEvent()
Case #PB_Event_CloseWindow
Break
Case #PB_Event_Gadget
If EventGadget() = #Btn_Ouvrir
Fichier$ = OpenFileRequester("Image à analyser", "", "Images|*.png;*.jpg;*.jpeg;*.bmp;*.tif;*.tiff|Tous|*.*", 0)
If Fichier$ : Analyser(Fichier$) : EndIf
EndIf
EndSelect
ForEver
EndIf
ZXing::Free()
CompilerEndIf
; IDE Options = PureBasic 6.41 (Windows - x64)
; CursorPosition = 435
; Folding = ---
; EnableXP
; DPIAware
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.
