$TYPECHECK ON
'------------------------------------------------------------------------------------------------------
'   QFImage.inc rev1.3 (c) 07/2006 by StoneCold (Christian Tandler)
'   Contact: stonecold@sctools.de
'   This code is freeware - use it at your own risk and edit it in your own opinion IF you like it.
'
'   A Mini-wrapper for use with FreeImage.dll (current version is 3.13.1)
'   FreeImage is an open source image library released under the GNU GPL version 2.
'   See http://freeimage.sourceforge.net for details.
'
'   IF you pack the FreeImage.dll with an EXE-Packer like (free) UPX, you can downsize
'   the DLL by more than half to make your distribution smaller!
'
'   This file contains 2 RapidQ-Ojects:
'   QFImage    - the standard object, does not handle animated GIF's (only the first frame)
'   QFGifImage - handles animated GIF's, but only read functions and no resize and so on...
'
'-------------------------------------------------------------------------------------------------------
'   v1.4 Feb 2010 d_homans@yahoo.com.au
'       Bug fixes and tidy-ups
'       Fixed the "fast load" FUNCTION so that there is no need to have a temp bmp file created
'       Removed the original LoadImage code; Renamed LoadFastImage() -> LoadImage()
'
'   v1.5 Jan 2013 d_homans@yahoo.com.au 
'       Tidy-ups on animated GIF code and added a separate UnloadImage() function for animated GIF
'-------------------------------------------------------------------------------------------------------
'  v1.6 added more functions/ constants for FreeImage version 3.18  Oct, 2015 , johnK
'-------------------------------------------------------------------------------------------------------

'Set the max. frames for animated Gif's, 128 should be enough in most cases
$DEFINE GIF_MAX_FRAMES      128

'FreeImage Load/Save Constants
Const FI_LOAD_PROP = -1
Const FI_SAVE_PROP = -1


' Load / Save flag constants, constants can also be 
'Enum FREE_IMAGE_LOAD_OPTIONS                 FILO_*** with same name below
'Enum FREE_IMAGE_SAVE_OPTIONS                 FISO_*** with same name below
CONST FIF_LOAD_NOPIXELS = &H8000              ' load the image header only (not supported by all plugins)
CONST BMP_DEFAULT As Long = 0
CONST BMP_SAVE_RLE As Long = 1
CONST CUT_DEFAULT As Long = 0
CONST DDS_DEFAULT As Long = 0
CONST EXR_DEFAULT As Long = 0                 ' save data as half with piz-based wavelet compression
CONST EXR_FLOAT As Long = &H1                 ' save data as float instead of as half (not recommended)
CONST EXR_NONE As Long = &H2                  ' save with no compression
CONST EXR_ZIP As Long = &H4                   ' save with zlib compression, in blocks of 16 scan lines
CONST EXR_PIZ As Long = &H8                   ' save with piz-based wavelet compression
CONST EXR_PXR24 As Long = &H10                ' save with lossy 24-bit float compression
CONST EXR_B44 As Long = &H20                  ' save with lossy 44% float compression - goes to 22% when combined with EXR_LC
CONST EXR_LC As Long = &H40                   ' save images with one luminance and two chroma channels, rather than as RGB (lossy compression)
CONST FAXG3_DEFAULT As Long = 0
CONST GIF_DEFAULT As Long = 0
CONST GIF_LOAD256 As Long = 1                 ' Load the image as a 256 color image with ununsed palette entries, if it's 16 or 2 color
CONST GIF_PLAYBACK As Long = 2                ''Play' the GIF to generate each frame (as 32bpp) instead of returning raw frame data when loading
CONST HDR_DEFAULT As Long = 0
CONST ICO_DEFAULT As Long = 0
CONST ICO_MAKEALPHA As Long = 1               ' convert to 32bpp and create an alpha channel from the AND-mask when loading
CONST IFF_DEFAULT As Long = 0
CONST J2K_DEFAULT  As Long = 0                ' save with a 16:1 rate
CONST JP2_DEFAULT As Long = 0                 ' save with a 16:1 rate
CONST JPEG_DEFAULT As Long = 0                ' loading (see JPEG_FAST); saving (see JPEG_QUALITYGOOD|JPEG_SUBSAMPLING_420)
CONST JPEG_FAST As Long = &H1                 ' load the file as fast as possible, sacrificing some quality
CONST JPEG_ACCURATE As Long = &H2             ' load the file with the best quality, sacrificing some speed
CONST JPEG_CMYK As Long = &H4                 ' load separated CMYK "as is" (use 'OR' to combine with other flags)
CONST JPEG_EXIFROTATE As Long = &H8           ' load and rotate according to Exif 'Orientation' tag if available
CONST JPEG_GREYSCALE As Long = &H10           ' load and convert to a 8-bit greyscale image
CONST JPEG_QUALITYSUPERB As Long = &H80       ' save with superb quality (100:1)
CONST JPEG_QUALITYGOOD As Long = &H100        ' save with good quality (75:1)
CONST JPEG_QUALITYNORMAL As Long = &H200      ' save with normal quality (50:1)
CONST JPEG_QUALITYAVERAGE As Long = &H400     ' save with average quality (25:1)
CONST JPEG_QUALITYBAD As Long = &H800         ' save with bad quality (10:1)
CONST JPEG_PROGRESSIVE As Long = &H2000       ' save as a progressive-JPEG (use 'OR' to combine with other save flags)
CONST JPEG_SUBSAMPLING_411 As Long = &H1000   ' save with high 4x1 chroma subsampling (4:1:1)
CONST JPEG_SUBSAMPLING_420 As Long = &H4000   ' save with medium 2x2 medium chroma subsampling (4:2:0) - default value
CONST JPEG_SUBSAMPLING_422 As Long = &H8000   ' save with low 2x1 chroma subsampling (4:2:2)
CONST JPEG_SUBSAMPLING_444 As Long = &H10000  ' save with no chroma subsampling (4:4:4)
CONST JPEG_OPTIMIZE As Long = &H20000         ' on saving, compute optimal Huffman coding tables (can reduce a few percent of file size)
CONST JPEG_BASELINE As Long = &H40000         ' save basic JPEG, without metadata or any markers
CONST KOALA_DEFAULT As Long = 0
CONST LBM_DEFAULT As Long = 0
CONST MNG_DEFAULT As Long = 0
CONST PCD_DEFAULT As Long = 0
CONST PCD_BASE As Long = 1                    ' load the bitmap sized 768 x 512
CONST PCD_BASEDIV4 As Long = 2                ' load the bitmap sized 384 x 256
CONST PCD_BASEDIV16 As Long = 3               ' load the bitmap sized 192 x 128
CONST PCX_DEFAULT As Long = 0
CONST PFM_DEFAULT As Long = 0
CONST PICT_DEFAULT As Long = 0
CONST PNG_DEFAULT As Long = 0
CONST PNG_IGNOREGAMMA As Long = 1             ' avoid gamma correction
CONST PNG_Z_BEST_SPEED As Long = &H1          ' save using ZLib level 1 compression flag (default value is 6)
CONST PNG_Z_DEFAULT_COMPRESSION As Long = &H6 ' save using ZLib level 6 compression flag (default recommended value)
CONST PNG_Z_BEST_COMPRESSION As Long = &H9    ' save using ZLib level 9 compression flag (default value is 6)
CONST PNG_Z_NO_COMPRESSION As Long = &H100    ' save without ZLib compression
CONST PNG_INTERLACED As Long = &H200          ' save using Adam7 interlacing (use | to combine with other save flags)
CONST PNM_DEFAULT As Long = 0
CONST PNM_SAVE_RAW As Long = 0                ' if set, the writer saves in RAW format (i.e. P4, P5 or P6)
CONST PNM_SAVE_ASCII As Long = 1              ' if set, the writer saves in ASCII format (i.e. P1, P2 or P3)
CONST PSD_DEFAULT As Long = 0
CONST PSD_CMYK As Long = 1                    ' reads tags for separated CMYK (default is conversion to RGB)
CONST PSD_LAB As Long = 2                     ' reads tags for CIELab (default is conversion to RGB)
CONST RAS_DEFAULT As Long = 0
CONST RAW_DEFAULT As Long = 0                 ' load the file as linear RGB 48-bit
CONST RAW_PREVIEW As Long = 1                 ' try to load the embedded JPEG preview with included Exif Data or default to RGB 24-bit
CONST RAW_DISPLAY As Long = 2                 ' load the file as RGB 24-bit
CONST RAW_HALFSIZE As Long = 4                ' load the file as half-size color image
CONST RAW_UNPROCESSED As Long = 8             ' load the file as FIT_UINT16 raw Bayer image
CONST SGI_DEFAULT As Long = 0
CONST TARGA_DEFAULT As Long = 0
CONST TARGA_LOAD_RGB888 As Long = 1           ' if set, the loader converts RGB555 and ARGB8888 -> RGB888
CONST TARGA_SAVE_RLE As Long = 2              ' if set, the writer saves with RLE compression
CONST TIFF_DEFAULT As Long = 0
CONST TIFF_CMYK As Long = &H1                 ' reads/stores tags for separated CMYK (use 'OR' to combine with compression flags)
CONST TIFF_PACKBITS As Long = &H100           ' save using PACKBITS compression
CONST TIFF_DEFLATE As Long = &H200            ' save using DEFLATE compression (a.k.a. ZLIB compression)
CONST TIFF_ADOBE_DEFLATE As Long = &H400      ' save using ADOBE DEFLATE compression
CONST TIFF_NONE As Long = &H800               ' save without any compression
CONST TIFF_CCITTFAX3 As Long = &H1000         ' save using CCITT Group 3 fax encoding
CONST TIFF_CCITTFAX4 As Long = &H2000         ' save using CCITT Group 4 fax encoding
CONST TIFF_LZW As Long = &H4000               ' save using LZW compression
CONST TIFF_JPEG As Long = &H8000              ' save using JPEG compression
CONST TIFF_LOGLUV As Long = &H10000           ' save using LogLuv compression
CONST WBMP_DEFAULT As Long = 0
CONST XBM_DEFAULT As Long = 0
CONST XPM_DEFAULT As Long = 0
CONST WEBP_DEFAULT As Long = 0                ' save with good quality (75:1)
CONST WEBP_LOSSLESS As Long = &H100           ' save in lossless mode
CONST JXR_DEFAULT As Long = 0                 ' save with quality 80 and no chroma subsampling (4:4:4)
CONST JXR_LOSSLESS As Long = &H64             ' save in lossless mode
CONST JXR_PROGRESSIVE As Long = &H2000        ' save as a progressive-JXR (use Or to combine with other save flags)

'FreeImage File-Formats
' Enum FREE_IMAGE_FORMAT
Const FIF_UNKNOWN = -1
$DEFINE FIF_BMP             0
$DEFINE FIF_ICO             1
$DEFINE FIF_JPEG            2
$DEFINE FIF_JNG             3
$DEFINE FIF_KOALA           4
$DEFINE FIF_IFF             5
$DEFINE FIF_LBM             5               ' FIF_IFF
$DEFINE FIF_MNG             6
$DEFINE FIF_PBM             7
$DEFINE FIF_PBMRAW          8
$DEFINE FIF_PCD             9
$DEFINE FIF_PCX             10
$DEFINE FIF_PGM             11
$DEFINE FIF_PGMRAW          12
$DEFINE FIF_PNG             13
$DEFINE FIF_PPM             14
$DEFINE FIF_PPMRAW          15
$DEFINE FIF_RAS             16
$DEFINE FIF_TARGA           17
$DEFINE FIF_TIFF            18
$DEFINE FIF_WBMP            19
$DEFINE FIF_PSD             20
$DEFINE FIF_CUT             21
$DEFINE FIF_XBM             22
$DEFINE FIF_XPM             23
$DEFINE FIF_DDS             24
$DEFINE FIF_GIF             25
$DEFINE FIF_HDR             26
$DEFINE FIF_FAXG3           27
$DEFINE FIF_SGI             28
$DEFINE FIF_EXR             29
$DEFINE FIF_J2K             30
$DEFINE FIF_JP2             31
$DEFINE FIF_PFM             32
$DEFINE FIF_PICT            33
$DEFINE FIF_RAW             34
$DEFINE FIF_WEBP            35
$DEFINE FIF_JXR             36

' Image types used in FreeImage
'Enum FREE_IMAGE_TYPE
CONST FIT_UNKNOWN = 0           ' unknown type
CONST FIT_BITMAP = 1            ' standard image           : 1-, 4-, 8-, 16-, 24-, 32-bit
CONST FIT_UINT16 = 2            ' array of unsigned short  : unsigned 16-bit
CONST FIT_INT16 = 3             ' array of short           : signed 16-bit
CONST FIT_UINT32 = 4            ' array of unsigned long   : unsigned 32-bit
CONST FIT_INT32 = 5             ' array of long            : signed 32-bit
CONST FIT_FLOAT = 6             ' array of float           : 32-bit IEEE floating point
CONST FIT_DOUBLE = 7            ' array of double          : 64-bit IEEE floating point
CONST FIT_COMPLEX = 8           ' array of FICOMPLEX       : 2 x 64-bit IEEE floating point
CONST FIT_RGB16 = 9             ' 48-bit RGB image         : 3 x 16-bit
CONST FIT_RGBA16 = 10           ' 64-bit RGBA image        : 4 x 16-bit
CONST FIT_RGBF = 11             ' 96-bit RGB float image   : 3 x 32-bit IEEE floating point
CONST FIT_RGBAF = 12            ' 128-bit RGBA float image : 4 x 32-bit IEEE floating point


'FreeImage Filter for resizing
$DEFINE FI_FILTER_BOX       0
$DEFINE FI_FILTER_PIX       0
$DEFINE FI_FILTER_BICUBIC   1
$DEFINE FI_FILTER_BILINEAR  2
$DEFINE FI_FILTER_BSPLINE   3
$DEFINE FI_FILTER_CATMULLROM    4
$DEFINE FI_FILTER_LANCZOS3  5

'public Enum FREE_IMAGE_COLOR_TYPE
CONST FIC_MINISWHITE = 0        ' min value is white
CONST FIC_MINISBLACK = 1        ' min value is black
CONST FIC_RGB = 2               ' RGB color model
CONST FIC_PALETTE = 3           ' color map indexed
CONST FIC_RGBALPHA = 4          ' RGB color model with alpha channel
CONST FIC_CMYK = 5              ' CMYK color model

'' Dithering algorithm constants
''public Enum FREE_IMAGE_DITHER
'CONST FID_FS = 0                ' Floyd & Steinberg error diffusion
'CONST FID_BAYER4x4 = 1          ' Bayer ordered dispersed dot dithering (order 2 dithering matrix)
'CONST FID_BAYER8x8 = 2          ' Bayer ordered dispersed dot dithering (order 3 dithering matrix)
'CONST FID_CLUSTER6x6 = 3        ' Ordered clustered dot dithering (order 3 - 6x6 matrix)
'CONST FID_CLUSTER8x8 = 4        ' Ordered clustered dot dithering (order 4 - 8x8 matrix)
'CONST FID_CLUSTER16x16 = 5      ' Ordered clustered dot dithering (order 8 - 16x16 matrix)
'CONST FID_BAYER16x16 = 6        ' Bayer ordered dispersed dot dithering (order 4 dithering matrix)

' Color quantization algorithm constants
'public Enum FREE_IMAGE_QUANTIZE
$DEFINE FIQ_WUQUANT         0               ' Xiaolin Wu color quantization algorithm
$DEFINE FIQ_NNQUANT         1               ' NeuQuant neural-net quantization algorithm by Anthony Dekker

' Lossless JPEG transformation constants
'public Enum FREE_IMAGE_JPEG_OPERATION
CONST FIJPEG_OP_NONE = 0        ' no transformation
CONST FIJPEG_OP_FLIP_H = 1      ' horizontal flip
CONST FIJPEG_OP_FLIP_V = 2      ' vertical flip
CONST FIJPEG_OP_TRANSPOSE = 3   ' transpose across UL-to-LR axis
CONST FIJPEG_OP_TRANSVERSE = 4  ' transpose across UR-to-LL axis
CONST FIJPEG_OP_ROTATE_90 = 5   ' 90-degree clockwise rotation
CONST FIJPEG_OP_ROTATE_180 = 6  ' 180-degree rotation
CONST FIJPEG_OP_ROTATE_270 = 7  ' 270-degree clockwise (or 90 ccw)

'' Color channel constants
''public Enum FREE_IMAGE_COLOR_CHANNEL
'   FICC_RGB = 0              ' Use red, green and blue channels
'   FICC_RED = 1              ' Use red channel
'   FICC_GREEN = 2            ' Use green channel
'   FICC_BLUE = 3             ' Use blue channel
'   FICC_ALPHA = 4            ' Use alpha channel
'   FICC_BLACK = 5            ' Use black channel
'   FICC_REAL = 6             ' Complex images: use real part
'   FICC_IMAG = 7             ' Complex images: use imaginary part
'   FICC_MAG = 8              ' Complex images: use magnitude
'   FICC_PHASE = 9            ' Complex images: use phase

'
'' Tag data type information constants (based on TIFF specifications)
''public Enum FREE_IMAGE_MDTYPE
'   FIDT_NOTYPE = 0           ' placeholder
'   FIDT_BYTE = 1             ' 8-bit unsigned integer
'   FIDT_ASCII = 2            ' 8-bit bytes w/ last byte null
'   FIDT_SHORT = 3            ' 16-bit unsigned integer
'   FIDT_LONG = 4             ' 32-bit unsigned integer
'   FIDT_RATIONAL = 5         ' 64-bit unsigned fraction
'   FIDT_SBYTE = 6            ' 8-bit signed integer
'   FIDT_UNDEFINED = 7        ' 8-bit untyped data
'   FIDT_SSHORT = 8           ' 16-bit signed integer
'   FIDT_SLONG = 9            ' 32-bit signed integer
'   FIDT_SRATIONAL = 10       ' 64-bit signed fraction
'   FIDT_FLOAT = 11           ' 32-bit IEEE floating point
'   FIDT_DOUBLE = 12          ' 64-bit IEEE floating point
'   FIDT_IFD = 13             ' 32-bit unsigned integer (offset)
'   FIDT_PALETTE = 14         ' 32-bit RGBQUAD
'
'
'' Metadata models supported by FreeImage
''public Enum FREE_IMAGE_MDMODEL
'   FIMD_NODATA = -1          '
'   FIMD_COMMENTS = 0         ' single comment or keywords
'   FIMD_EXIF_MAIN = 1        ' Exif-TIFF metadata
'   FIMD_EXIF_EXIF = 2        ' Exif-specific metadata
'   FIMD_EXIF_GPS = 3         ' Exif GPS metadata
'   FIMD_EXIF_MAKERNOTE = 4   ' Exif maker note metadata
'   FIMD_EXIF_INTEROP = 5     ' Exif interoperability metadata
'   FIMD_IPTC = 6             ' IPTC/NAA metadata
'   FIMD_XMP = 7              ' Abobe XMP metadata
'   FIMD_GEOTIFF = 8          ' GeoTIFF metadata
'   FIMD_ANIMATION = 9        ' Animation metadata
'   FIMD_CUSTOM = 10          ' Used to attach other metadata types to a dib
'   FIMD_EXIF_RAW = 11        ' Exif metadata as a raw buffer

'
'' These are the GIF_DISPOSAL metadata constants
''public Enum FREE_IMAGE_FRAME_DISPOSAL_METHODS
'   FIFD_GIF_DISPOSAL_UNSPECIFIED = 0
'   FIFD_GIF_DISPOSAL_LEAVE = 1
'   FIFD_GIF_DISPOSAL_BACKGROUND = 2
'   FIFD_GIF_DISPOSAL_PREVIOUS = 3

'
'' Constants used in FreeImage_FillBackground and FreeImage_EnlargeCanvas
''public Enum FREE_IMAGE_COLOR_OPTIONS
'   FI_COLOR_IS_RGB_COLOR = &H0          ' RGBQUAD color is a RGB color (contains no valid alpha channel)
'   FI_COLOR_IS_RGBA_COLOR = &H1         ' RGBQUAD color is a RGBA color (contains a valid alpha channel)
'   FI_COLOR_FIND_EQUAL_COLOR = &H2      ' For palettized images: lookup equal RGB color from palette
'   FI_COLOR_ALPHA_IS_INDEX = &H4        ' The color's rgbReserved member (alpha) contains the palette index to be used

'CONST FI_COLOR_PALETTE_SEARCH_MASK = _
'      (FI_COLOR_FIND_EQUAL_COLOR Or FI_COLOR_ALPHA_IS_INDEX)     ' Flag to test, if any color lookup is performed
'
'' The following enum constants are used by derived (wrapper) functions of the
'' FreeImage 3 VB Wrapper
''public Enum FREE_IMAGE_CONVERSION_FLAGS
'   FICF_MONOCHROME = &H1
'   FICF_MONOCHROME_THRESHOLD = FICF_MONOCHROME
'   FICF_MONOCHROME_DITHER = &H3
'   FICF_GREYSCALE_4BPP = &H4
'   FICF_PALLETISED_8BPP = &H8
'   FICF_GREYSCALE_8BPP = FICF_PALLETISED_8BPP Or FICF_MONOCHROME
'   FICF_GREYSCALE = FICF_GREYSCALE_8BPP
'   FICF_RGB_15BPP = &HF
'   FICF_RGB_16BPP = &H10
'   FICF_RGB_24BPP = &H18
'   FICF_RGB_32BPP = &H20
'   FICF_RGB_ALPHA = FICF_RGB_32BPP
'   FICF_KEEP_UNORDERED_GREYSCALE_PALETTE = &H0
'   FICF_REORDER_GREYSCALE_PALETTE = &H1000

'
''public Enum FREE_IMAGE_COLOR_DEPTH
CONST FICD_AUTO = &H0
CONST FICD_MONOCHROME = &H1
CONST FICD_MONOCHROME_THRESHOLD = &H1
CONST FICD_MONOCHROME_DITHER = &H3
CONST FICD_1BPP = &H1
CONST FICD_4BPP = &H4
CONST FICD_8BPP = &H8
CONST FICD_15BPP = &HF
CONST FICD_16BPP = &H10
CONST FICD_24BPP = &H18
CONST FICD_32BPP = &H20

'
''public Enum FREE_IMAGE_ADJUST_MODE
'   AM_STRECH = &H1
'   AM_DEFAULT = AM_STRECH
'   AM_ADJUST_BOTH = AM_STRECH
'   AM_ADJUST_WIDTH = &H2
'   AM_ADJUST_HEIGHT = &H4
'   AM_ADJUST_OPTIMAL_SIZE = &H8

'
''public Enum FREE_IMAGE_MASK_FLAGS
'   FIMF_MASK_NONE = &H0
'   FIMF_MASK_FULL_TRANSPARENCY = &H1
'   FIMF_MASK_ALPHA_TRANSPARENCY = &H2
'   FIMF_MASK_COLOR_TRANSPARENCY = &H4
'   FIMF_MASK_FORCE_TRANSPARENCY = &H8
'   FIMF_MASK_INVERSE_MASK = &H10

'
''public Enum FREE_IMAGE_COLOR_FORMAT_FLAGS
'   FICFF_COLOR_RGB = &H1
'   FICFF_COLOR_BGR = &H2
'   FICFF_COLOR_PALETTE_INDEX = &H4
'   
'   FICFF_COLOR_HAS_ALPHA = &H100
'   
'   FICFF_COLOR_ARGB = FICFF_COLOR_RGB Or FICFF_COLOR_HAS_ALPHA
'   FICFF_COLOR_ABGR = FICFF_COLOR_BGR Or FICFF_COLOR_HAS_ALPHA
'   
'   FICFF_COLOR_FORMAT_ORDER_MASK = FICFF_COLOR_RGB Or FICFF_COLOR_BGR

'
''public Enum FREE_IMAGE_MASK_CREATION_OPTION_FLAGS
'   MCOF_CREATE_MASK_IMAGE = &H1
'   MCOF_MODIFY_SOURCE_IMAGE = &H2
'   MCOF_CREATE_AND_MODIFY = MCOF_CREATE_MASK_IMAGE Or MCOF_MODIFY_SOURCE_IMAGE

'
''public Enum FREE_IMAGE_TRANSPARENCY_STATE_FLAGS
'   FITSF_IGNORE_TRANSPARENCY = &H0
'   FITSF_NONTRANSPARENT = &H1
'   FITSF_TRANSPARENT = &H2
'   FITSF_INCLUDE_ALPHA_TRANSPARENCY = &H4

'
''public Enum FREE_IMAGE_ICON_TRANSPARENCY_OPTION_FLAGS
'   ITOF_NO_TRANSPARENCY = &H0
'   ITOF_USE_TRANSPARENCY_INFO = &H1
'   ITOF_USE_TRANSPARENCY_INFO_ONLY = ITOF_USE_TRANSPARENCY_INFO
'   ITOF_USE_COLOR_TRANSPARENCY = &H2
'   ITOF_USE_COLOR_TRANSPARENCY_ONLY = ITOF_USE_COLOR_TRANSPARENCY
'   ITOF_USE_TRANSPARENCY_INFO_OR_COLOR = ITOF_USE_TRANSPARENCY_INFO Or ITOF_USE_COLOR_TRANSPARENCY
'   ITOF_USE_DEFAULT_TRANSPARENCY = ITOF_USE_TRANSPARENCY_INFO_OR_COLOR
'   ITOF_USE_COLOR_TOP_LEFT_PIXEL = &H0
'   ITOF_USE_COLOR_FIRST_PIXEL = ITOF_USE_COLOR_TOP_LEFT_PIXEL
'   ITOF_USE_COLOR_TOP_RIGHT_PIXEL = &H20
'   ITOF_USE_COLOR_BOTTOM_LEFT_PIXEL = &H40
'   ITOF_USE_COLOR_BOTTOM_RIGHT_PIXEL = &H80
'   ITOF_USE_COLOR_SPECIFIED = &H100
'   ITOF_FORCE_TRANSPARENCY_INFO = &H400



'Flip options
$DEFINE FI_FLIP_VER         0
$DEFINE FI_FLIP_HOR         1

'Adjust options
$DEFINE FI_ADJ_GAMMA        0
$DEFINE FI_ADJ_BRIGHT       1
$DEFINE FI_ADJ_CONTRAST     2

'Convert options
$DEFINE FI_CONV_GREY        0
$DEFINE FI_CONV_4BIT        1
$DEFINE FI_CONV_8BIT        2
$DEFINE FI_CONV_16BIT       3
$DEFINE FI_CONV_24BIT       4
$DEFINE FI_CONV_32BIT       5

'FreeImage structures, not complete but likely for RQ

' 64-bit RGBA
Type FIRGBA16
   Red As Integer
   Green As Integer
   Blue As Integer
   Alpha As Integer
End Type

Type FITAG
   Key As Long
   Description As Long
   Id As Integer
   Type As Integer
   Count As Long
   Length As Long
   Value As Long
End Type


'Type FREE_IMAGE_TAG
'   Model As FREE_IMAGE_MDMODEL
'   TagPtr As Long
'   Key As String
'   Description As String
'   Id As Long
'   Type As FREE_IMAGE_MDTYPE
'   Count As Long
'   Length As Long
'   StringValue As String
'   Palette() As RGBQUAD
'   RationalValue() As FIRATIONAL
'   Value As Variant
'End Type

Type FreeImageIO
   read_proc As Long
   write_proc As Long
   seek_proc As Long
   tell_proc As Long
End Type


'FreeImage Format-Strings
Const FIF_STR_UNKNOWN = "Unknown"
Const FIF_STR_BMP = "Windows/OS2 Bitmap (BMP)"
Const FIF_STR_GIF = "CompuServe Graphics Interchange (GIF)"
Const FIF_STR_JPEG = "Independent JPEG/JFIF (JPG)"
Const FIF_STR_JNG = "JPEG Network Graphics (JNG)"
Const FIF_STR_PNG = "Portable Network Graphics (PNG)"
Const FIF_STR_ICO = "Icon (ICO)"
Const FIF_STR_TARGA = "Truevision Targa (TGA)"
Const FIF_STR_TIFF = "Tagged Image File (TIF)"
Const FIF_STR_PCX = "Zsoft Paintbrush (PCX)"
Const FIF_STR_IFF = "Amiga/Deluxe Paint (IFF/LBM)"
Const FIF_STR_LBM = FIF_STR_IFF
Const FIF_STR_MNG = "Multiple Network Graphics (MNG)"
Const FIF_STR_PBM = "Portable Bitmap (PBM)"
Const FIF_STR_PGM = "Portable Greymap (PGM)"
Const FIF_STR_PPM = "Portable Pixelmap (PPM)"
Const FIF_STR_RAS = "Sun Raster Picture (RAS)"
Const FIF_STR_WBMP = "Wireless Bitmap (WBMP)"
Const FIF_STR_PSD = "Photoshop Image (PSD)"
Const FIF_STR_CUT = "Dr. Halo (CUT)"
Const FIF_STR_XBM = "X Windows Bitmap (XBM)"
Const FIF_STR_XPM = "X Windows Pixmap (XPM)"
Const FIF_STR_DDS = "DirectDraw Surface (DDS)"
Const FIF_STR_FAXG3 = "FAX Group 3 (G3)"
Const FIF_STR_SGI = "Silicon Graphics Image (SGI)"

'--------------------------------------------------------------------------------
' FreeImage 3 FUNCTION wrapper
'--------------------------------------------------------------------------------
'This is just a very small basic part of all FreeImage functions!
'All FreeImage 3 functions are described in the FreeImage 3 API documentation
'and especially the VB-Wrapper examples.
'Please see there for further details of these and many others functions.

'fif : FImage fileformats (FIF_...)
'dib : FImage handle
'Flags : FImage load/save options
'Filter : FImage filter
'quantize : Quantize method for reducing bpp


' Initialization / Deinitialization functions
Declare Sub FreeImage_Initialise Lib "FreeImage.dll" Alias "_FreeImage_Initialise@4" (ByVal LoadLocalPluginsOnly As Long)
Declare Sub FreeImage_DeInitialise Lib "FreeImage.dll" Alias "_FreeImage_DeInitialise@0" ()

' Version functions
Declare Function FreeImage_GetVersionInt Lib "FreeImage.dll" Alias "_FreeImage_GetVersion@0" () As Long
Declare Function FreeImage_GetCopyrightMessageInt Lib "FreeImage.dll" Alias "_FreeImage_GetCopyrightMessage@0" () As Long

' Message output functions
Declare Sub FreeImage_SetOutputMessage Lib "FreeImage.dll" Alias "_FreeImage_SetOutputMessageStdCall@4" (ByVal omf As Long)

'General functions
DECLARE FUNCTION FI_GetVersion LIB "FreeImage.dll" ALIAS "_FreeImage_GetVersion@0" () AS string
DECLARE FUNCTION FI_GetCopyright LIB "FreeImage.dll" ALIAS "_FreeImage_GetCopyrightMessage@0" () AS string

'Info functions
Declare Function FreeImage_GetColorsUsed Lib "FreeImage.dll" Alias "_FreeImage_GetColorsUsed@4" (ByVal Bitmap As Long) As Long
DECLARE FUNCTION FI_GetBPP LIB "FreeImage.dll" ALIAS "_FreeImage_GetBPP@4" (dib AS long) AS long
DECLARE FUNCTION FI_GetWidth LIB "FreeImage.dll" ALIAS "_FreeImage_GetWidth@4" (dib AS long) AS long
DECLARE FUNCTION FI_GetHeight LIB "FreeImage.dll" ALIAS "_FreeImage_GetHeight@4" (dib AS long) AS long
DECLARE FUNCTION FI_GetSize LIB "FreeImage.dll" ALIAS "_FreeImage_GetDIBSize@4" (dib AS long) AS long
Declare Function FreeImage_GetLine Lib "FreeImage.dll" Alias "_FreeImage_GetLine@4" ( ByVal Bitmap As Long) As Long
Declare Function FreeImage_GetPitch Lib "FreeImage.dll" Alias "_FreeImage_GetPitch@4" (ByVal Bitmap As Long) As Long
Declare Function FreeImage_GetDIBSize Lib "FreeImage.dll" Alias "_FreeImage_GetDIBSize@4" (ByVal Bitmap As Long) As Long
Declare Function FreeImage_GetPalette Lib "FreeImage.dll" Alias "_FreeImage_GetPalette@4" (ByVal Bitmap As Long) As Long
Declare Function FreeImage_GetDotsPerMeterX Lib "FreeImage.dll" Alias "_FreeImage_GetDotsPerMeterX@4" (ByVal Bitmap As Long) As Long
Declare Function FreeImage_GetDotsPerMeterY Lib "FreeImage.dll" Alias "_FreeImage_GetDotsPerMeterY@4" (ByVal Bitmap As Long) As Long
Declare Sub FreeImage_SetDotsPerMeterX Lib "FreeImage.dll" Alias "_FreeImage_SetDotsPerMeterX@8" (ByVal Bitmap As Long, ByVal Resolution As Long)
Declare Sub FreeImage_SetDotsPerMeterY Lib "FreeImage.dll" Alias "_FreeImage_SetDotsPerMeterY@8" ( ByVal Bitmap As Long, ByVal Resolution As Long)
Declare Function FreeImage_GetInfoHeader Lib "FreeImage.dll" Alias "_FreeImage_GetInfoHeader@4" ( ByVal Bitmap As Long) As Long
Declare Function FreeImage_GetInfo Lib "FreeImage.dll" Alias "_FreeImage_GetInfo@4" (ByVal Bitmap As Long) As Long
Declare Function FreeImage_GetColorType Lib "FreeImage.dll" Alias "_FreeImage_GetColorType@4" (ByVal Bitmap As Long) As long
Declare Function FreeImage_GetTransparencyCount Lib "FreeImage.dll" Alias "_FreeImage_GetTransparencyCount@4" (ByVal Bitmap As Long) As Long
Declare Function FreeImage_GetTransparencyTable Lib "FreeImage.dll" Alias "_FreeImage_GetTransparencyTable@4" (ByVal Bitmap As Long) As Long
declare Sub FreeImage_SetTransparentInt Lib "FreeImage.dll" Alias "_FreeImage_SetTransparent@8" (ByVal Bitmap As Long, ByVal Value As Long)
Declare Sub FreeImage_SetTransparencyTable Lib "FreeImage.dll" Alias "_FreeImage_SetTransparencyTable@12" ( _
           ByVal Bitmap As Long, _
           ByVal TransTablePtr As Long, _
ByVal Count As Long)

Declare Function FreeImage_IsTransparentInt Lib "FreeImage.dll" Alias "_FreeImage_IsTransparent@4" ( _
    ByVal Bitmap As Long) As Long

Declare Function FreeImage_SetTransparentIndex Lib "FreeImage.dll" Alias "_FreeImage_SetTransparentIndex@8" ( _
    ByVal Bitmap As Long, _
    ByVal Index As Long) As Long

Declare Function FreeImage_GetTransparentIndex Lib "FreeImage.dll" Alias "_FreeImage_GetTransparentIndex@4" ( _
    ByVal Bitmap As Long) As Long

Declare Function FreeImage_HasBackgroundColorInt Lib "FreeImage.dll" Alias "_FreeImage_HasBackgroundColor@4" ( _
    ByVal Bitmap As Long) As Long
           
Declare Function FreeImage_GetBackgroundColorInt Lib "FreeImage.dll" Alias "_FreeImage_GetBackgroundColor@8" ( _
    ByVal Bitmap As Long, ByRef BackColor As long) As Long

Declare Function FreeImage_GetBackgroundColorAsLongInt Lib "FreeImage.dll" Alias "_FreeImage_GetBackgroundColor@8" ( _
    ByVal Bitmap As Long, _
           ByRef BackColor As Long) As Long

Declare Function FreeImage_SetBackgroundColorInt Lib "FreeImage.dll" Alias "_FreeImage_SetBackgroundColor@8" ( _
    ByVal Bitmap As Long, _
           ByRef BackColor As long) As Long
           
Declare Function FreeImage_SetBackgroundColorAsLongInt Lib "FreeImage.dll" Alias "_FreeImage_SetBackgroundColor@8" ( _
    ByVal Bitmap As Long, _
           ByRef BackColor As Long) As Long



'Load and save functions
DECLARE FUNCTION FI_LoadImage LIB "FreeImage.dll" ALIAS "_FreeImage_Load@12" _
                                            (fif AS long, Filename AS string, Flags AS long ) AS long
DECLARE FUNCTION FI_SaveImage LIB "FreeImage.dll" ALIAS "_FreeImage_Save@16" _
                                (fif AS long, dib AS long, Filename AS string, Flags AS long) AS long

Declare Function FreeImage_LoadFromHandle Lib "FreeImage.dll" Alias "_FreeImage_LoadFromHandle@16" ( _
    ByVal Format As long, _
    ByVal IO As Long, _
    ByVal Handle As Long, _
    ByVal Flags As long) As Long

Declare Function FreeImage_SaveInt Lib "FreeImage.dll" Alias "_FreeImage_Save@16" ( _
    ByVal Format As long, _
    ByVal Bitmap As Long, _
    ByVal Filename As String, _
    ByVal Flags As long) As Long
  
Declare Function FreeImage_SaveUInt Lib "FreeImage.dll" Alias "_FreeImage_SaveU@16" ( _
    ByVal Format As long, _
    ByVal Bitmap As Long, _
    ByVal Filename As Long, _
    ByVal Flags As long) As Long

Declare Function FreeImage_SaveToHandleInt Lib "FreeImage.dll" Alias "_FreeImage_SaveToHandle@20" ( _
    ByVal Format As long, _
    ByVal Bitmap As Long, _
    ByVal IO As Long, _
    ByVal Handle As Long, _
    ByVal Flags As long) As Long



'Conversion functions
DECLARE FUNCTION FI_ConvToGrey LIB "FreeImage.dll" ALIAS "_FreeImage_ConvertToGreyscale@4" _
                                                                                (dib AS long) AS long
DECLARE FUNCTION FI_ConvTo4Bit LIB "FreeImage.dll" ALIAS "_FreeImage_ConvertTo4Bits@4" _
                                                                                (dib AS long) AS long
DECLARE FUNCTION FI_ConvTo8Bit LIB "FreeImage.dll" ALIAS "_FreeImage_ConvertTo8Bits@4" _
                                                                                (dib AS long) AS long
DECLARE FUNCTION FI_ConvTo16Bit LIB "FreeImage.dll" ALIAS "_FreeImage_ConvertTo16Bits555@4" _
                                                                                (dib AS long) AS long
DECLARE FUNCTION FI_ConvTo24Bit LIB "FreeImage.dll" ALIAS "_FreeImage_ConvertTo24Bits@4" _
                                                                                (dib AS long) AS long
DECLARE FUNCTION FI_ConvTo32Bit LIB "FreeImage.dll" ALIAS "_FreeImage_ConvertTo32Bits@4" _
                                                                                (dib AS long) AS long

'Upsampling and downsampling
DECLARE FUNCTION FI_Resize LIB "FreeImage.dll" ALIAS "_FreeImage_Rescale@16" _
                        (dib AS long, dst_width AS long, dst_height AS long, Filter AS long) AS long

Declare Function FreeImage_RescaleRect Lib "FreeImage.dll" Alias "_FreeImage_RescaleRect@32" ( _
           ByVal Bitmap As Long, _
           ByVal Left As Long, _
           ByVal Top As Long, _
           ByVal Right As Long, _
           ByVal Bottom As Long, _
           ByVal Width As Long, _
           ByVal Height As Long, _
           ByVal Filter As long) As Long

Declare Function FreeImage_ColorQuantize Lib "FreeImage.dll" Alias "_FreeImage_ColorQuantize@8" ( _
           ByVal Bitmap As Long, _
           ByVal QuantizeMethod As long) As Long
           

DECLARE FUNCTION FI_ReduceColor LIB "FreeImage.dll" ALIAS "_FreeImage_ColorQuantize@8" _
                                                                (dib AS long, quantize AS long) AS long

Declare Function FreeImage_Threshold Lib "FreeImage.dll" Alias "_FreeImage_Threshold@8" ( _
           ByVal Bitmap As Long, _
           ByVal Threshold As Byte) As Long

Declare Function FreeImage_Dither Lib "FreeImage.dll" Alias "_FreeImage_Dither@8" ( _
           ByVal Bitmap As Long, _
           ByVal DitherMethod As long) As Long

'zip compression
' ZLib functions
Declare Function FreeImage_ZLibCompress Lib "FreeImage.dll" Alias "_FreeImage_ZLibCompress@16" ( _
           ByVal TargetPtr As Long, _
           ByVal TargetSize As Long, _
           ByVal SourcePtr As Long, _
           ByVal SourceSize As Long) As Long

Declare Function FreeImage_ZLibUncompress Lib "FreeImage.dll" Alias "_FreeImage_ZLibUncompress@16" ( _
           ByVal TargetPtr As Long, _
           ByVal TargetSize As Long, _
           ByVal SourcePtr As Long, _
           ByVal SourceSize As Long) As Long

Declare Function FreeImage_ZLibGZip Lib "FreeImage.dll" Alias "_FreeImage_ZLibGZip@16" ( _
           ByVal TargetPtr As Long, _
           ByVal TargetSize As Long, _
           ByVal SourcePtr As Long, _
           ByVal SourceSize As Long) As Long
           
Declare Function FreeImage_ZLibGUnzip Lib "FreeImage.dll" Alias "_FreeImage_ZLibGUnzip@16" ( _
           ByVal TargetPtr As Long, _
           ByVal TargetSize As Long, _
           ByVal SourcePtr As Long, _
           ByVal SourceSize As Long) As Long


'Flip and rotating functions
DECLARE FUNCTION FI_FlipHorizontal LIB "FreeImage.dll" ALIAS "_FreeImage_FlipHorizontal@4" _
                                                                                (dib AS long) AS long
DECLARE FUNCTION FI_FlipVertical LIB "FreeImage.dll" ALIAS "_FreeImage_FlipVertical@4" _
                                                                                (dib AS long) AS long
DECLARE FUNCTION FI_Rotate LIB "FreeImage.dll" ALIAS "_FreeImage_RotateClassic@12" _
                                                                (dib AS long, angle AS double) AS long

'Global adjust functions
DECLARE FUNCTION FI_AdjustGamma LIB "FreeImage.dll" ALIAS "_FreeImage_AdjustGamma@12" _
                                                                (dib AS long, gamma AS double) AS long
DECLARE FUNCTION FI_AdjustBrightness LIB "FreeImage.dll" ALIAS "_FreeImage_AdjustBrightness@12" _
                                                            (dib AS long, percentage AS double) AS long
DECLARE FUNCTION FI_AdjustContrast LIB "FreeImage.dll" ALIAS "_FreeImage_AdjustContrast@12" _
                                                            (dib AS long, percentage AS double) AS long
DECLARE FUNCTION FI_Invert LIB "FreeImage.dll" ALIAS "_FreeImage_Invert@4" (dib AS long) AS long
Declare Function FreeImage_AdjustGammaInt Lib "FreeImage.dll" Alias "_FreeImage_AdjustGamma@12" ( _
           ByVal Bitmap As Long, _
           ByVal Gamma As Double) As Long

Declare Function FreeImage_AdjustBrightnessInt Lib "FreeImage.dll" Alias "_FreeImage_AdjustBrightness@12" ( _
           ByVal Bitmap As Long, _
           ByVal Percentage As Double) As Long

Declare Function FreeImage_AdjustContrastInt Lib "FreeImage.dll" Alias "_FreeImage_AdjustContrast@12" ( _
           ByVal Bitmap As Long, _
           ByVal Percentage As Double) As Long

Declare Function FreeImage_InvertInt Lib "FreeImage.dll" Alias "_FreeImage_Invert@4" ( _
           ByVal Bitmap As Long) As Long

Declare Function FreeImage_GetHistogramInt Lib "FreeImage.dll" Alias "_FreeImage_GetHistogram@12" ( _
           ByVal Bitmap As Long, _
           ByRef HistogramPtr As Long, _
           ByVal Channel As long) As Long
  
Declare Function FreeImage_GetAdjustColorsLookupTableInt Lib "FreeImage.dll" Alias "_FreeImage_GetAdjustColorsLookupTable@32" ( _
           ByVal LookupTablePtr As Long, _
           ByVal Brightness As Double, _
           ByVal Contrast As Double, _
           ByVal Gamma As Double, _
           ByVal Invert As Long) As Long

Declare Function FreeImage_AdjustColorsInt Lib "FreeImage.dll" Alias "_FreeImage_AdjustColors@32" ( _
           ByVal Bitmap As Long, _
           ByVal Brightness As Double, _
           ByVal Contrast As Double, _
           ByVal Gamma As Double, _
           ByVal Invert As Long) As Long
  

'Copy (Crop) & paste parts of an image
DECLARE FUNCTION FI_Copy LIB "FreeImage.dll" ALIAS "_FreeImage_Copy@20" (dib AS long, _
                                    left AS long, top AS long, right AS long, bottom AS long) AS long
DECLARE FUNCTION FI_Paste LIB "FreeImage.dll" ALIAS "_FreeImage_Paste@20" (dstdib AS long, _
                                    srcdib AS long, left AS long, top AS long, alpha AS long) AS long
Declare Function FreeImage_Clone Lib "FreeImage.dll" Alias "_FreeImage_Clone@4" (ByVal Bitmap As Long) As Long


'Freeing the image
DECLARE SUB FI_UnloadImage LIB "FreeImage.dll" ALIAS "_FreeImage_Unload@4" (dib AS long)

'Multipage bitmap support (at this time only read and only GIF for the type QFGifImage!)
DECLARE FUNCTION FI_OpenMultiBitmap LIB "FreeImage.dll" ALIAS "_FreeImage_OpenMultiBitmap@24" _
                            (fif AS long, Filename AS string, create_new AS long, read_only AS long, _
                                                    keep_cache_in_memory AS long, Flags AS long) AS long
DECLARE FUNCTION FI_CloseMultiBitmap LIB "FreeImage.dll" ALIAS "_FreeImage_CloseMultiBitmap@8" _
                                                                    (mpdib AS long, Flags AS long) AS long
DECLARE FUNCTION FI_GetPageCount LIB "FreeImage.dll" ALIAS "_FreeImage_GetPageCount@4" _
                                                                                (mpdib AS long) AS long
DECLARE FUNCTION FI_LockPage LIB "FreeImage.dll" ALIAS "_FreeImage_LockPage@8" (mpdib AS long, _
                                                                                PageNum AS long) AS long
DECLARE SUB FI_UnlockPage LIB "FreeImage.dll" ALIAS "_FreeImage_UnlockPage@12" (mpdib AS long, _
                                                                    PageHandle AS long, Changed AS long)

'Memory functions
DECLARE FUNCTION FI_OpenMemory LIB "FreeImage.dll" ALIAS "_FreeImage_OpenMemory@8" _
                                                            (IOFlag AS integer, MemSize AS long) AS long
DECLARE FUNCTION FI_LoadFromMemory LIB "FreeImage.dll" ALIAS "_FreeImage_LoadFromMemory@12" _
                                                    (fif AS long, Stream AS long, Flags AS long) AS long
DECLARE FUNCTION FI_SaveToMemory LIB "FreeImage.dll" ALIAS "_FreeImage_SaveToMemory@16" _
                                        (fif AS long, dib AS long, Stream AS long, Flags AS long) AS long
DECLARE FUNCTION FI_CloseMemory LIB "FreeImage.dll" ALIAS "_FreeImage_CloseMemory@4" _
                                                                                (Stream AS long) AS long
DECLARE FUNCTION FI_ReadMemory LIB "FreeImage.dll" ALIAS "_FreeImage_ReadMemory@16" _
                            (ByRef Buffer AS long, Size AS long, Length AS long, Stream AS long) AS long
DECLARE FUNCTION FI_AcquireMemory LIB "FreeImage.dll" ALIAS "_FreeImage_AcquireMemory@12" _
                                 (Stream AS long, pBuffer AS long, pSize AS long) AS long
           
Declare Function FreeImage_WriteMemory Lib "FreeImage.dll" Alias "_FreeImage_WriteMemory@16" ( _
           ByVal BufferPtr As Long, ByVal Size As Long, ByVal Count As Long, ByVal Stream As Long) As Long
           
Declare Function FreeImage_LoadMultiBitmapFromMemory Lib "FreeImage.dll" Alias "_FreeImage_LoadMultiBitmapFromMemory@12" ( _
           ByVal Format As long, ByVal Stream As Long, ByVal Flags As long) As Long

Declare Function FreeImage_SaveMultiBitmapToMemory Lib "FreeImage.dll" Alias "_FreeImage_SaveMultiBitmapToMemory@16" ( _
           ByVal Format As long, ByVal Bitmap As Long, ByVal Stream As Long, ByVal Flags As long) As Long




' Multipaging functions
Declare Function FreeImage_OpenMultiBitmapInt Lib "FreeImage.dll" Alias "_FreeImage_OpenMultiBitmap@24" ( _
           ByVal Format As long, _
           ByVal Filename As String, _
           ByVal CreateNew As Long, _
           ByVal ReadOnly As Long, _
           ByVal KeepCacheInMemory As Long, _
           ByVal Flags As long) As Long

Declare Function FreeImage_CloseMultiBitmapInt Lib "FreeImage.dll" Alias "_FreeImage_CloseMultiBitmap@8" ( _
           ByVal Bitmap As Long, _
           ByVal Flags As long) As Long

Declare Function FreeImage_GetPageCount Lib "FreeImage.dll" Alias "_FreeImage_GetPageCount@4" ( _
           ByVal Bitmap As Long) As Long

Declare Sub FreeImage_AppendPage Lib "FreeImage.dll" Alias "_FreeImage_AppendPage@8" ( _
           ByVal Bitmap As Long, _
           ByVal PageBitmap As Long)

Declare Sub FreeImage_InsertPage Lib "FreeImage.dll" Alias "_FreeImage_InsertPage@12" ( _
           ByVal Bitmap As Long, _
           ByVal Page As Long, _
           ByVal PageBitmap As Long)

Declare Sub FreeImage_DeletePage Lib "FreeImage.dll" Alias "_FreeImage_DeletePage@8" ( _
           ByVal Bitmap As Long, _
           ByVal Page As Long)

Declare Function FreeImage_LockPage Lib "FreeImage.dll" Alias "_FreeImage_LockPage@8" ( _
           ByVal Bitmap As Long, _
           ByVal Page As Long) As Long

Declare Sub FreeImage_UnlockPageInt Lib "FreeImage.dll" Alias "_FreeImage_UnlockPage@12" ( _
           ByVal Bitmap As Long, _
           ByVal PageBitmap As Long, _
           ByVal ApplyChanges As Long)

Declare Function FreeImage_MovePageInt Lib "FreeImage.dll" Alias "_FreeImage_MovePage@12" ( _
           ByVal Bitmap As Long, _
           ByVal TargetPage As Long, _
           ByVal SourcePage As Long) As Long

Declare Function FreeImage_GetLockedPageNumbersInt Lib "FreeImage.dll" Alias "_FreeImage_GetLockedPageNumbers@12" ( _
           ByVal Bitmap As Long, _
           ByRef PagesPtr As Long, _
           ByRef Count As Long) As Long

' Filetype request functions
Declare Function FreeImage_GetFileType Lib "FreeImage.dll" Alias "_FreeImage_GetFileType@8" ( _
           ByVal Filename As String, _
           ByVal Size As Long) As long

Declare Function FreeImage_GetFileTypeFromHandle Lib "FreeImage.dll" Alias "_FreeImage_GetFileTypeFromHandle@12" ( _
           ByVal IO As Long, _
           ByVal Handle As Long, _
           ByVal Size As Long) As long

Declare Function FreeImage_GetFileTypeFromMemory Lib "FreeImage.dll" Alias "_FreeImage_GetFileTypeFromMemory@8" ( _
           ByVal Stream As Long, _
           ByVal Size As Long) As long


' Image type request functions
Declare Function FreeImage_GetImageType Lib "FreeImage.dll" Alias "_FreeImage_GetImageType@4" ( _
           ByVal Bitmap As Long) As long



'NB Not all types are supported by FreeImage.dll for reading AND writing.
'
'QFImage:
'--------
'All public functions for QFImage are only modify the FI-Image given by the handle. This means:
'- the image is not loaded into the QFImage.Image.BMP
'- this increase the speed without several temporarly loading processes
'- prevents memory leaks, most FreeImage-Functions returning a copy of the original image
'- IF after image processing the original image is not freed, you'll quickly run into memory problems...
'
'Example:
'
'dim myfimage as qfimage
'myfimage.LoadFromFile("test.jpg", FI_LOAD_PROP)      'load the JPG
'myfimage.ResizeImage(200, 200, FI_FILTER_BICUBIC)    'resize to 200*200
'myfimage.ReduceColor(FIQ_WUQUANT)                    'reduce colors to 256
'myfimage.ShowImage                                    'get the image into myfimage.image.bmp (do not forget!)
'myfimage.UnloadImage                                 'unload the FI-Image (don't forget, otherwise memory leaks!)
'
'
'
'QFGifImage:
'-----------
'- has Methods: .OpenFromFile, .IsAnimGIF, .StartAnim, .StopAnim and .SaveFrames
'- support only GIF's with GIF_MAX_PAGES (see on top)
'
'There are some problems with optimized GIF's they store not the whole frames but only the edited pixel
'At this time the position of such frames in 'mother-frame 0' are unknown...


'The Type QFImage
TYPE QFImage EXTENDS QIMAGE
PUBLIC:
    Handle AS long
    Width AS integer
    Height AS integer
    Size AS integer
    Bpp AS integer
    Colors AS integer
    TypeImage AS integer
    TypeString AS string * 40
    LoadOption AS integer
    SaveOption AS integer

PRIVATE:
    OrigWidth AS integer
    OrigHeight AS integer

PUBLIC:
WITH QFImage
'----------------------Public functions--------------------------------------------------
'GetImageType
'Get the image type of a given filename from the extension
'The type is returned and stored in QFImage...Not all FI-Types are supported.
FUNCTION GetImageType(sSourceFile AS string) AS integer
DEFSTR fExt

    fExt=UCASE$(RIGHT$(sSourceFile,LEN(sSourceFile)-RINSTR(sSourceFile,".")))
    IF fExt <> "" THEN
        SELECT CASE fExt
            CASE "BMP","DIB","RLE": .TypeImage = FIF_BMP: .TypeString = FIF_STR_BMP
            CASE "JPG","JPEG","JFI","JFIF": .TypeImage = FIF_JPEG: .TypeString = FIF_STR_JPEG
            CASE "GIF": .TypeImage = FIF_GIF: .TypeString = FIF_STR_GIF
            CASE "JNG": .TypeImage = FIF_JNG: .TypeString = FIF_STR_JNG
            CASE "PNG": .TypeImage = FIF_PNG: .TypeString = FIF_STR_PNG
            CASE "ICO": .TypeImage = FIF_ICO: .TypeString = FIF_STR_ICO
            CASE "TGA": .TypeImage = FIF_TARGA: .TypeString = FIF_STR_TARGA
            CASE "TIF","TIFF": .TypeImage = FIF_TIFF: .TypeString = FIF_STR_TIFF
            CASE "PCX": .TypeImage = FIF_PCX: .TypeString = FIF_STR_PCX
            CASE "IFF","LBM": .TypeImage = FIF_IFF: .TypeString = FIF_STR_IFF
            CASE "MNG": .TypeImage = FIF_MNG: .TypeString = FIF_STR_MNG
            CASE "PBM": .TypeImage = FIF_PBM: .TypeString = FIF_STR_PBM
            CASE "PGM": .TypeImage = FIF_PGM: .TypeString = FIF_STR_PGM
            CASE "PPM": .TypeImage = FIF_PPM: .TypeString = FIF_STR_PPM
            CASE "RAS": .TypeImage = FIF_RAS: .TypeString = FIF_STR_RAS
            CASE "SGI": .TypeImage = FIF_SGI: .TypeString = FIF_STR_SGI
            CASE "WAP","WBMP","WBM": .TypeImage = FIF_WBMP: .TypeString = FIF_STR_WBMP
            CASE "PSD": .TypeImage = FIF_PSD: .TypeString = FIF_STR_PSD
            CASE "CUT": .TypeImage = FIF_CUT: .TypeString = FIF_STR_CUT
            CASE "XPM": .TypeImage = FIF_XPM: .TypeString = FIF_STR_XPM
            CASE "XBM": .TypeImage = FIF_XBM: .TypeString = FIF_STR_XBM
            CASE "DDS": .TypeImage = FIF_DDS: .TypeString = FIF_STR_DDS
            CASE "G3": .TypeImage = FIF_FAXG3: .TypeString = FIF_STR_FAXG3
            CASE ELSE
                .TypeImage = FIF_BMP
                .TypeString = FIF_STR_BMP
        END SELECT
    ELSE
        .TypeImage = FIF_BMP
        .TypeString = FIF_STR_BMP
    END IF
    Result=.TypeImage
END FUNCTION

'LoadFromFile
'Loads an image file into the object
'The LoadOption is one of the defined open/save options and overwrite qfimage.LoadOption.
'If you wish to use the object property instead the FUNCTION parameter you have set before, use FI_LOAD_PROP.
'Returns TRUE IF OK, otherwise FALSE
FUNCTION LoadFromFile(sSourceFile AS string, iLoadOption AS integer) AS integer
DEFINT lopt

    .GetImageType(sSourceFile)
    IF iLoadOption = FI_LOAD_PROP THEN
        lopt = .LoadOption
    ELSE
        lopt = iLoadOption
    END IF
    .Handle = FI_LoadImage(.TypeImage, sSourceFile, lopt)
    IF .Handle THEN
        .Width = FI_GetWidth(.Handle)
        .Height = FI_GetHeight(.Handle)
        .OrigWidth = .Width
        .OrigHeight = .Height
        .Size = FI_GetSize(.Handle)
        .Bpp = FI_GetBpp(.Handle)
        .Colors = 2^qfimage.Bpp
        Result=True
    ELSE
        Result=False
    END IF
END FUNCTION

'ShowImage - Loads a (BMP) copy of the FI-Image from FI-Structure into qfimage
FUNCTION ShowImage(imgHandle AS long) AS integer
DEFLNG fiHandle, ptrbuf, sizebuf
DIM tmpStream AS QMEMORYSTREAM
DIM fbmp AS QBITMAP

    Result = False
    IF imgHandle THEN
        fiHandle = FI_OpenMemory(0,0)                                   ' Open a FreeImage memorystream
        IF fiHandle THEN
            IF FI_SaveToMemory(FIF_BMP, imgHandle, fiHandle, BMP_DEFAULT) THEN     ' Save as bmp in FI memorystream
                FI_AcquireMemory(fiHandle, VARPTR(ptrbuf), VARPTR(sizebuf))        ' Get the FI memorystream address and size
                tmpStream.Position = 0
                tmpStream.MemCopyFrom(ptrbuf,sizebuf)                   ' Copy from FI memorystream into RQ memorystream
                tmpStream.Position = 0
                fbmp.LoadFromStream(tmpStream)                          ' Load the bmp from stream
                tmpStream.Close                                         ' Close RQ memorystream
                qfimage.BMP = fbmp.BMP                                  ' Copy bmp -> qfimage
                Result = True
            END IF
            FI_CloseMemory(fiHandle)                                    ' Close the FreeImage memorystream
        END IF
    END IF
END FUNCTION

' ConvertImage
FUNCTION ConvertImage(iConvOpt AS integer) AS long
DEFLNG oHandle=0

    SELECT CASE iConvOpt
        CASE FI_CONV_GREY: oHandle = FI_ConvToGrey(.Handle)
        CASE FI_CONV_4BIT: oHandle = FI_ConvTo4Bit(.Handle)
        CASE FI_CONV_8BIT: oHandle = FI_ConvTo8Bit(.Handle)
        CASE FI_CONV_16BIT: oHandle = FI_ConvTo16Bit(.Handle)
        CASE FI_CONV_24BIT: oHandle = FI_ConvTo24Bit(.Handle)
        CASE FI_CONV_32BIT: oHandle = FI_ConvTo32Bit(.Handle)
    END SELECT
    Result = oHandle
END FUNCTION

' SaveToFile - File format (type) is extracted from file extension
' The SaveOption is one of the defined open/save options and overwrite qfimage.SaveOption.
' IF you wish to use the object property instead the FUNCTION parameter, use FI_SAVE_PROP.
' Note that some file formats need conversion into 8Bpp or grayscale to save properly (GIF, IFF, WBMP...)
FUNCTION SaveToFile(sDestFile AS string, iSaveOption AS integer) AS integer
DEFSTR fExt
DEFINT sopt
DEFLNG qft

    fExt = UCASE$(FIELD$(sDestFile,".",2))
    SELECT CASE fExt
        CASE "BMP","DIB","RLE": qft = FIF_BMP
        CASE "JPG","JPEG","JFI","JFIF": qft = FIF_JPEG
        CASE "GIF": qft = FIF_GIF
        CASE "PNG": qft = FIF_PNG
        CASE "JNG": qft = FIF_JNG
        CASE "ICO": qft = FIF_ICO
        CASE "TGA": qft = FIF_TARGA
        CASE "TIF","TIFF": qft = FIF_TIFF
        CASE "PBM": qft = FIF_PBM
        CASE "PGM": qft = FIF_PGM
        CASE "PPM": qft = FIF_PPM
        CASE "WAP","WBMP","WBM": qft = FIF_WBMP
        CASE "XPM": qft = FIF_XPM
        CASE ELSE
            qft = FIF_BMP
    END SELECT

    IF iSaveOption = FI_SAVE_PROP THEN
        sopt = .SaveOption
    ELSE
        sopt = iSaveOption
    END IF
    Result = FI_SaveImage(qft, .Handle, sDestFile, sopt)
END FUNCTION

'ResizeImage
'Resize the Image with specified method (see filter)
'Note, that resizing needs 24Bpp images (ConvertImage())
FUNCTION ResizeImage(iWidth AS long, iHeight AS long, iMethod AS long) AS integer
DEFLNG oHandle

    oHandle = .Handle
    .Handle = FI_Resize(oHandle, iWidth, iHeight, iMethod)
    IF .Handle THEN
        FI_UnloadImage(oHandle)
        .Width = FI_GetWidth(.Handle)
        .Height = FI_GetHeight(.Handle)
        .Size = FI_GetSize(.Handle)
        .Bpp = FI_GetBpp(.Handle)
        .Colors = 2^qfimage.Bpp
        Result = True
    ELSE
        .Handle = oHandle
        Result = False
    END IF
END FUNCTION

' ReduceColor
' Reduce the colors of an 24bit image to 8bits (see quantize methods)
FUNCTION ReduceColor(iMethod AS long) AS integer
DEFLNG oHandle

    oHandle = .Handle
    .Handle = FI_ReduceColor(oHandle, iMethod)
    IF .Handle THEN
        FI_UnloadImage(oHandle)
        .Width = FI_GetWidth(.Handle)
        .Height = FI_GetHeight(.Handle)
        .Size = FI_GetSize(.Handle)
        .Bpp = FI_GetBpp(.Handle)
        .Colors = 2^qfimage.Bpp
        Result = True
    ELSE
        .Handle = oHandle
        Result = False
    END IF
END FUNCTION

'FlipImage Vertical or Horiz
SUB FlipVertical
    IF .Handle THEN
        IF FI_FlipVertical(.Handle) THEN
            .ShowImage(.Handle)
        END IF
    END IF
END SUB

SUB FlipHorizontal
    IF .Handle THEN
        IF FI_FlipHorizontal(.Handle) THEN
            .ShowImage(.Handle)
        END IF
    END IF
END SUB

' RotateImage
FUNCTION RotateImage(dAngle AS double) AS integer
DEFLNG oHandle

    oHandle = .Handle
    .Handle = FI_Rotate(oHandle, dAngle)
    IF .Handle THEN
        FI_UnloadImage(oHandle)
        .Width = FI_GetWidth(.Handle)
        .Height = FI_GetHeight(.Handle)
        .Size = FI_GetSize(.Handle)
        .Bpp = FI_GetBpp(.Handle)
        .Colors = 2^qfimage.Bpp
        .ShowImage(.Handle)
        Result=True
    ELSE
        .Handle = oHandle
        Result=False
    END IF
END FUNCTION

' InvertImage
FUNCTION InvertImage() AS integer
DEFLNG oHandle

    oHandle = .Handle
    .Handle = FI_Invert(oHandle)
    IF .Handle THEN
        FI_UnloadImage(oHandle)
        .Width = FI_GetWidth(.Handle)
        .Height = FI_GetHeight(.Handle)
        .Size = FI_GetSize(.Handle)
        .Bpp = FI_GetBpp(.Handle)
        .Colors = 2^qfimage.Bpp
        Result=True
    ELSE
        .Handle = oHandle
        Result=False
    END IF
END FUNCTION

' AdjustImage
' Adjust Gamma, Brightness & contrast by specified amount
FUNCTION AdjustImage(iAdjOpt AS integer, dAdjPara AS double) AS integer
    SELECT CASE iAdjOpt
        CASE FI_ADJ_GAMMA
          Result = FI_AdjustGamma(.Handle, dAdjPara)
        CASE FI_ADJ_BRIGHT
          Result = FI_AdjustBrightness(.Handle, dAdjPara)
        CASE FI_ADJ_CONTRAST
          Result = FI_AdjustContrast(.Handle, dAdjPara)
        CASE ELSE
          Result = False
    END SELECT
END FUNCTION

' UnloadImage - unload the FI-Image
FUNCTION UnloadImage() AS integer
    Result = FI_UnloadImage(.Handle)
    .Handle=0
END FUNCTION
END WITH

CONSTRUCTOR
    Handle = 0
    Width = 0
    Height = 0
    Size = 0
    Bpp = 0
    Colors = 0
    TypeImage = FIF_BMP
    TypeString = FIF_STR_BMP
    LoadOption = BMP_DEFAULT
    SaveOption = BMP_DEFAULT
END CONSTRUCTOR

END TYPE

'The Type QFGifImage
'Only for Multipage-Gif's (animated) and only read functions (exception: frame saving)!
'To determine, IF your image is an animated GIF use the method .IsAnimGIF.
'
TYPE QFGifImage EXTENDS QIMAGE
PUBLIC:
    Filename AS string * 256
    Width AS integer
    Height AS integer
    Size AS integer
    Bpp AS integer
    Colors AS integer
    TypeImage AS integer
    TypeString AS string * 40
    Loops AS integer
    LoopNum AS integer
    Interval AS integer
    Animate AS integer
    FrameCount AS integer
    FrameNum AS integer
    FrameLen(GIF_MAX_FRAMES) AS integer

PRIVATE:
    Handle AS long
    Timer AS QTIMER
    fHandle(GIF_MAX_FRAMES) AS long
    Frame(GIF_MAX_FRAMES) AS QIMAGE

PUBLIC:

WITH QFGifImage
'Determine IF the file is an animated GIF, ready to show with QFGifImage-Object.
'The number of frames is stored in .FrameCount
'Returns TRUE IF OK, otherwise FALSE
FUNCTION IsAniGIF(sSourceFile AS string) AS integer
    .Handle = FI_OpenMultiBitmap(FIF_GIF, sSourceFile, 0, 1, 0, GIF_DEFAULT)
    IF .Handle THEN
        .FrameCount = FI_GetPageCount(.Handle)
        FI_CloseMultiBitmap(.Handle, GIF_DEFAULT)
        IF (.FrameCount < 2) OR (.FrameCount > GIF_MAX_FRAMES) THEN
            .IsAniGIF = False
        ELSE
            .IsAniGIF = True
        END IF
    ELSE
        .IsAniGIF = False
    END IF
END FUNCTION

'Loads the GIF-File into the object
'The animation must be started with .StartAnim
'Before you start the animation you can set the FrameLen(i) parameter (in 1/100s) for each frame,
'standard is 10 (1/10s).
'Returns TRUE IF OK, otherwise FALSE
FUNCTION LoadFromFile(sSourceFile AS string) AS integer
DEFINT i

    .Handle = FI_OpenMultiBitmap(FIF_GIF, sSourceFile, 0, 1, 0, GIF_DEFAULT)
    IF .Handle THEN
        .FrameCount = FI_GetPageCount(.Handle)
        IF (.FrameCount < 2) OR (.FrameCount > GIF_MAX_FRAMES) THEN
            FI_CloseMultiBitmap(.Handle, GIF_DEFAULT)
            .FrameCount = 0
            .Handle = 0
            .LoadFromFile = False
        ELSE
            .Filename = sSourceFile
            .Size = 0
            FOR i=0 TO .FrameCount - 1
                .FrameLen(i) = 0
                .fHandle(i) = FI_LockPage(.Handle, i)
                FI_SaveImage(FIF_BMP, .fHandle(i), "_FI_TMP_GIF_FRAME" + FORMAT$("%3.3d",i) + ".BMP", BMP_DEFAULT)
                .Frame(i).Autosize = 1
                .Frame(i).BMP = "_FI_TMP_GIF_FRAME" + FORMAT$("%3.3d",i) + ".BMP"
                .BMP = .Frame(0).BMP
                .Size = .Size + FI_GetSize(.fHandle(i))
                FI_UnlockPage(.Handle, .fHandle(i), 0)
            NEXT
            FI_CloseMultiBitmap(.Handle, GIF_DEFAULT)
            .Width = .Frame(0).Width
            .Height = .Frame(0).Height
            .Bpp = 8
            .Colors = 256
            .TypeImage = FIF_GIF
            .TypeString = "Animated GIF"
            .LoadFromFile = True
$IFNDEF _QFI_TEST
            FOR i=0 TO .FrameCount - 1
                Kill("_FI_TMP_GIF_FRAME" + format$("%3.3d",i) + ".BMP")
            NEXT
$ENDIF
            .Animate = 0
            .FrameNum = 0
            .Loops = 0
            .LoopNum = 0
            .Timer.Interval = 100
            .Timer.Tag = 0
            .Timer.Enabled = 0
        END IF
    ELSE
        .LoadFromFile = False
    END IF
END FUNCTION

'Start the animation at specified frame number
'The actual frame number is stored in .FrameNum
SUB StartAnim(iFrame)
    .BMP = .Frame(iFrame).BMP
    .Width = .Frame(0).Width
    .Height = .Frame(0).Height
    .Timer.Tag = iFrame
    .FrameNum = iFrame
    IF .FrameLen(.FrameNum) > 0 THEN
        .Timer.Interval = .FrameLen(.FrameNum) * 10
    ELSE
        .Timer.Interval = .Interval * 10
    END IF
    .Timer.Enabled = True
    .Animate = True
    .LoopNum = 0
END SUB

SUB StopAnim
    .Timer.Enabled = False
    .Animate = False
END SUB

'Check animation timer
SUB CheckTimer(Sender as QTIMER)
    IF (.Animate) AND (.LoopNum >= 0) THEN
        Sender.Enabled = False
        .BMP = .Frame(Sender.Tag).BMP
        .FrameNum = Sender.Tag
        IF .FrameLen(.FrameNum) > 0 THEN
            Sender.Interval = .FrameLen(.FrameNum) * 10
        ELSE
            Sender.Interval = .Interval * 10
        END IF
        Sender.Tag = Sender.Tag + 1
        IF Sender.Tag = .FrameCount THEN
            Sender.Tag = 0
            .FrameNum = 0
            IF .Loops > 0 THEN
                .LoopNum = .LoopNum + 1
                IF .LoopNum = .Loops THEN
                    .LoopNum = -1
                END IF
            END IF
        END IF
        Sender.Enabled = True
    ELSE
        Sender.Enabled = False
    END IF
END SUB

'Saving the frames of the GIF-File into Files with 'FileName + _FrameXX.bmp'
'The FileName property must be set and a GIF must be loaded ;-)
SUB SaveFrames
DEFINT i
DEFSTR outf
DIM fbmp AS QBITMAP
DIM rct AS QRECT

    outf = FIELD$(.FileName,".",1) + "_Frame"
    fbmp.Width = .Frame(0).Width
    fbmp.Height = .Frame(0).Height
    rct.Left=0: rct.Right=fbmp.Width-1
    rct.Top=0: rct.Bottom=fbmp.Height-1

    FOR i=0 TO .FrameCount - 1
        fbmp.CopyRect(rct, QFGifImage.Frame(i), rct)
        fbmp.SaveToFile(outf + FORMAT$("%3.3d",i) + ".bmp")
        DoEvents
    NEXT
END SUB

' UnloadImage - unload the GIF-Image
FUNCTION UnloadImage() AS integer
    .Timer.Enabled = False
    .Animate = False
    Result = FI_CloseMultiBitmap(.Handle, GIF_DEFAULT)
    .Handle=0
END FUNCTION
END WITH

CONSTRUCTOR
    FileName = ""
    Handle = 0
    Timer.Interval = 100
    Timer.Enabled = False
    Timer.OnTimer = QFGifImage.CheckTimer
    Width = 0
    Height = 0
    Size = 0
    Bpp = 0
    Colors = 0
    TypeImage = FIF_GIF
    TypeString = FIF_STR_GIF
    Loops = 0
    LoopNum = 0
    Interval = 10
    Animate = False
    FrameCount = 0
    FrameNum = 0
END CONSTRUCTOR

END TYPE

