csXImage Version 5.0 - Online Manual

Introduction

These instructions are also available in pdf format. We recommend using the PDF version if a printable manual is required.

This is an OCX control that enables processing of graphic images. A comprehensive range of over 200 functions is available to load and save images, resize and edit images, draw text and shapes and interact with hardware devices such as printers, scanners and cameras. Most commonly used graphics file formats are supported.

A free trial version of csXImage is available. If you are reading this instruction manual for the first time, it is likely that you have just downloaded and installed the trial version. When you use the trial version, a line of text will be displayed at the top of any image as you view it in the control. The trial version is fully functional, with the exception of three methods (AcquireToFile, ReadMetaData and OverwriteMetaData) which are available only in the full version and the addition of this text to your image is the only other difference between the trial and full versions. This means that you can fully test whether this control is suitable for your application before considering whether to license the full version.

Using these Instructions

These instructions are divided into a number of sections covering different types of functions available in csXImage. A full Table of Contents is available below and an index listing all functions in Alphabetical order is included at the end for easy reference.

Click on one of the links below to go directly to the section of interest:

Table of Contents

1. Import and Export of Images

Images can be read into the control and exported from the control in several different ways. The most common method is to load files from disk and save files to disk. Alternatively, images can be read from a remote URL via the internet, pasted to a web page, uploaded by FTP, copied to or pasted from the clipboard, transferred to/from other image controls, saved as binary data in a memory buffer or captured from screen. Image files can be dragged and dropped onto the control. Images can also be read from scanners and cameras or sent to printers. This functionality is described in Section 8.

1.1. Saving and Loading Files To/From Disk

Images are loaded into the control using LoadFromFile and saved to disk using SaveToFile.

LoadFromFile (FileName As String) - Reads the file from disk, loads the image into the control and displays the image. FileName must be a complete path to the file. The following file types are supported: .bmp, .gif, .jpg, .jpeg, .jpe, .png, .wbmp, .wbm, .pcx, .psd, .tif, .tiff and .pdf. csXImage will recognise the file format from the file content even if the file has an incorrect or missing extension.

To load images from .pdf files, use OpenPDF and related functions instead.

LoadDialog ( ) As Boolean - Displays a standard File Open dialogue box allowing the user to browse to an image file on disk, which is then loaded. The return value is True if a file is loaded and False if the user clicks the Cancel button or an error occurs when loading the file.

ImageCount (FileName As String) As Long - Read-only property. Gives the number of images contained within a file. FileName must be a complete path to the file, including the file extension. Note that reading of multiple images is only possible with TIFF or PDF files, so for other files this function will normally return the value 1.

FileName can alternatively be either (1) a full HTTP reference to a remote URL, beginning with "http://" or "https://", or (2) an image encoded as a string in Base64 format.

ReadImageNumber As Long - Specifies the image that will be read from a file or a variant array in TIFF or PDF format containing multiple images. This property is used by the LoadFromFile, LoadFromURL and ReadBinary2 methods. (Default = 1).

SaveToFile (FileName As String) - Saves the file to disk. FileName must be a complete path to the file, including the file extension. The extension must be .bmp, .gif, .jpg, .jpeg, .jpe, .png, .wbmp, .wbm, .pcx, .psd, .tif, .tiff or .pdf. If it is .gif or .png, transparency will be defined by the Transparent and BGColor properties. If it is .jpg, .jpeg or .jpe, the compression quality will be defined by the JPEGQuality property. If the file already exists, it will be overwritten without warning.

If UseSelection is True, SaveToFile will save only the selected region of the image.

SaveDialog ( ) As Boolean - Displays a standard File Save dialogue box allowing the user to save an image to disk. The return value is True if a file is saved and False if the user clicks the Cancel button or an error occurs when saving the file.

NewFileSize (Format As TxGraphicsFormat) As Long - Returns the file size in bytes if the current image is saved to disk in the graphics format given in Format, which can take one of the following values:

If UseSelection is True, NewFileSize will return the file size if only the selected region of the image is saved to disk.

If FileType is gfPDF or gfTIF and a multi-page PDF or TIFF has been created in memory using the AddToPDF or AddToTIF function, the size of the prepared multi-page PDF or TIFF file will be returned instead of the file size of the current image.

LastFileName As String - Read-only property. Returns the full path and name of the last file that was loaded using the LoadFromFile, LoadDialog or LoadFromURL commands, or saved using the SaveToFile, SaveDialog, WriteTIF, WriteTIFDialog, WritePDF or WritePDFDialog commands, whichever was most recent.

PDF is not an image file format and these files are treated differently for loading images. Images can be present in PDF files as embedded objects and csXImage can find and extract some of these images. Due to wide variation in the formatting of images and methods of embedding them in PDF files, csXImage is not guaranteed to read all images from all files.

Images in PDF files do not necessarily correspond to pages in the document. Therefore, csXImage does not convert PDF pages to images and is not a PDF viewer.

Images in PDF files can be read using LoadFromFile and LoadFromURL, but for PDF files containing multiple images it can be more efficient to use the following functions to load the PDF contents into memory and then extract images from it.

OpenPDF (FileName As String) - Loads the contents of a PDF file into memory prior to using the LoadPDFImage method to extract images from the file.

OpenPDFDialog ( ) As Boolean - Displays a standard File Open dialogue box allowing the user to browse to a PDF file on disk, which is then loaded for extraction of images as if using OpenPDF. The return value is True if a file is loaded and False if the user clicks the Cancel button or an error occurs when loading the file.

OpenPDFFromURL (URL As String) - Loads the contents of a PDF file into from a URL. This function operates in a similar way to the LoadFromURL function.

ClosePDF ( ) - Releases the memory used by OpenPDF. It is not strictly necessary to call this function as the memory will be released on a later call to OpenPDF or when the instance of csXImage is itself unloaded.

PDFImageCount As Long - Read-only property. Returns the number of images that csXImage can find in the PDF file currently loaded using OpenPDF.

LoadPDFImage (Index As Long) - Loads the image indicated by Index from the current PDF file.

The following VB code shows how to use the above functions:

ImageBox1.OpenPDF "filename"
If ImageBox1.PDFImageCount >= 1 Then
  ImageBox1.LoadPDFImage 1
End If
ImageBox1.ClosePDF

1.2. Image Transfer via the Internet

Three functions are available to read images from and send images to a web site using HTTP. These are LoadFromURL, CopyBinaryFromURL and PostImage. As an alternative to PostImage, images can also be sent to an FTP server using the FTPImage function. Other functions detailed below support the operation of these functions.

LoadFromURL (URL As String) - Reads a file from a URL. URL must be a complete HTTP reference to the file. It is not necessary to include 'http://' at the start of the string. Note that on some operating systems used by web servers, e.g. UNIX, file names are case-sensitive, so incorrect use of upper/lower case may result in no image being loaded.

If the URL requires authentication a user name and password can be sent with the request by setting the properties URLUserName and URLPassword otherwise a dialogue will pop-up for the user to enter the user name and password.

When reading more than one image from a multi-page TIFF or PDF file, the LoadFromURL command will transfer the whole file each time a single image is read, which can be very time consuming. For this situation, the CopyBinaryFromURL command should be used instead. For PDF files the OpenPDFFromURL function is also an efficient option.

CopyBinaryFromURL (URL As String) As Variant - Reads a file from a URL and writes the contents of the file as binary data to an OLE Variant array. URL must be a complete HTTP reference to the file as for the LoadFromURL command. This command copies any file, but its main purpose is to enable the whole of a multi-page TIFF or PDF file to be read in one go and saved as binary data so that individual images can then be read using the ReadBinary2 command without requiring further data transfer.

HTTPTimeout As Long - The time before the LoadFromURL, CopyBinaryFromURL or PostImage methods will time-out if receiving no response. The value is the number of seconds. A value of zero means that there will be no time-out. (Default = 60).

URLUserName As String - The user name to be sent with a LoadFromURL or PostImage command if the server requires authentication.

URLPassword As String - The password to be sent with a LoadFromURL or PostImage command if the server requires authentication.

HTTPUserAgent As String - Specifies the user agent header sent with the HTTP request when LoadFromURL is called. This property can also be used when ImageCount is used with a URL.

PostImage (URL As String, FileName As String, FormVarName As String, FileType As TxGraphicsFormat) As Boolean - Uploads the image to a web server as a "multipart/form-data" HTTP POST. URL must be a fully qualified address (including 'http://') of a script, e.g., ASP, which is able to process the upload. This method emulates a POST as if it originated from a page of HTML using the <input type="file"> tag and HTML form variables can be included. FileName is the name of the file complete with extension. It can be an empty string, but the processing script may require a file name. FormVarName is the name of the form variable associated with the file, which can also be an empty string. The AddFormVar method is used to create additional form variables if they are required.

The image file format is specified by FileType. If FileType is gfPDF or gfTIF and a multi-page PDF or TIFF has been created in memory using the AddToPDF or AddToTIF function, the prepared multi-page PDF or TIFF file will be uploaded instead of the current image held in the control.

If the server requires authentication, the type of authentication must be set using the AuthenticationType property and the user name and password can be set using URLUserName and URLPassword. If the user name and password are not given, a dialogue will pop-up for user entry.

Return value will be False if PostImage fails, either because the connection to the URL failed or the script returned an error message.

AuthenticationType As TxAuthenticationType - The type of authentication required by the server for a call to the PostImage function. If Windows Integrated Authentication (NTLM) is to be used, this property must be set to atIntegrated otherwise the upload will fail. With Basic Authentication or no authentication, AuthenticationType must be set to atBasic. As this is the default value, the property can be left unused. The user name and password can be coded into the application by setting the URLUserName and URLPassword properties. If these properties are not set, a dialogue box will be used to collect the log in details from the user.

AuthenticationType can be either:

PostReturnFile As String - The contents of the file returned to the browser following a call to the PostImage function. This can be used to help debug the server side script receiving the posted image.

PostReturnCode As Long - The HTTP return code following a call to the PostImage function. This will normally be 200 for a successful post operation. A value of 0 indicates that the connection to the server failed and a value of 500 indicates an error in the server side script.

UseAuthenticationDialog As Boolean - Read/Write property. If this is set to True a dialogue will be displayed for the user to enter the uername and password if authentication is required when using PostImage. If the dialogue is not used, the values set for URLUserName and URLPassword will be used instead. (Default = False).

AddFormVar (Name As String, Value As String) - Adds an HTML form variable with the given Name and Value to the list of form variables that will be sent with the PostImage method. This list is automatically cleared after PostImage is executed.

FTPImage (FileName As String, HostName As String, FileType As TxGraphicsFormat) As Boolean - Uploads the image to an FTP server identified by HostName. FileName is the name of the file to be saved complete with extension and must include the path to the directory from the root directory of the FTP server. If the directory on the server does not already exist, it will be created.

The user name and password required to log into the FTP server can be set using URLUserName and URLPassword.

The image file format is specified by FileType. If FileType is gfPDF or gfTIF and a multi-page PDF or TIFF has been created in memory using the AddToPDF or AddToTIF function, the prepared multi-page PDF or TIFF file will be uploaded instead of the current image held in the control.

Return value will be False if FTPImage fails. In the case of failure, the FTPError property can be read to obtain an error message.

FTPPassiveMode As Boolean - If set to True, FTPImage will use passive mode, otherwise active mode is used. (Default = True).

FTPError As String - Read-only property. Returns an error message if the FTPImage function fails.

1.3. Clipboard Operations

csXImage can pass an image to the Windows clipboard or receive an image from the clipboard using the Copy and Paste functions.

Copy ( ) - Copies the currently loaded image to the Windows clipboard, in Bitmap format.

If UseSelection is True, Copy will only copy the selected region of the image.

Paste ( ) - Retrieves an image from the Windows clipboard, if one is available in an appropriate format. Paste replaces an image already loaded into the control, without warning.

1.4. Exchanging Images with Other Controls

The BMPHandle property provides a universal way of transferring an image to another control, or receiving an image that is already held in memory. Other functions are available with more specific uses.

BMPHandle As Long - Returns a Windows handle to a copy of the bitmap image. Setting this property copies the image referenced by the new handle value into the control. csXImage does not take ownership of the handle unless the ReleaseBMPHandle property has been set to False, in which case the original copy of the image will be freed from memory.

This property can be used, for example, to copy an image to csXImage from a VB PictureBox control, in which case, the syntax would be in the form:

ImageBox1.BMPHandle = Picture1.Picture.Handle

Likewise, an image can be copied from a VB Image control:

ImageBox1.BMPHandle = Image1.Picture.Handle

If an image is copied from the Image property of a VB PictureBox, the handle must not be released as the PictureBox will not clear the memory used for transferring the image and a memory leak will result. In this case, the following code should be used:

ImageBox1.ReleaseBMPHandle = False
ImageBox1.BMPHandle = Picture1.Image.Handle

The same applies if an image is copied from one instance of csXImage to another, i.e.:

ImageBox2.ReleaseBMPHandle = False
ImageBox2.BMPHandle = ImageBox1.BMPHandle

Note that the above two examples are the only known situations in which ReleaseBMPHandle should be set to False.

If UseSelection is True, the handle returned by BMPHandle will be of a bitmap including only the selected region of the image.

ReleaseBMPHandle As Boolean - This property is used to determine whether the handle is released to its original owner when the BMPHandle property is set. See above examples for further explanation. (Default = True).

Picture As IPictureDisp - Read-only property. Provides the image data in a format that can be transferred to any object with a "Picture" property, e.g. a PictureBox or ListImage in VB. For example, the following code copies an image from a csXImage object called "ImageBox1" to a VB PictureBox object called "Picture1":

Picture1.Picture = ImageBox1.Picture

PictureData As Variant - Read-only property. Provides the image data in a format that can be transferred to an Image object in MS Access. For example, the following code copies an image from a csXImage object called "ImageBox1" to a MS Access Image object called "Image1":

Image1.PictureData = ImageBox1.PictureData

1.5. Storing Images in Memory

Images can be written to and read back from an OLE variant array as binary data. This is a fast method for moving images around in an application as the image will be stored in RAM rather than written to disk. A typical use of this feature would be to save successive versions of an image in a temporary buffer for an "Undo" command.

WriteBinary (Format As TxGraphicsFormat) As Variant - Writes an image as binary data to an OLE Variant array. The graphics format is defined by Format. If Format is gfTIF or gfPDF and a multi-page TIFF or PDF has been created in memory using the AddToTIF or AddToPDF function, the prepared multi-page TIFF or PDF will be written to the OLE Variant array instead of the current image.

This method is a function and must be called by assigning to a variable. For example, in VB, the syntax would be of the form:

VariantName = WriteBinary (gfBMP)

If UseSelection is True, WriteBinary will write only the selected region of the image to the OLE Variant array.

ReadBinary2 (OLEInput As Variant) - Reads an image as binary data from OLEInput, which is an OLE Variant array. If OLEInput contains multi-page TIFF or PDF data, the image to be read is defined by the ReadImageNumber property. Data saved in PDF format cannot be read by ReadBinary2.

ReadBinary (Format As TxGraphicsFormat, OLEInput As Variant ) - This method has been superseded by ReadBinary2 which does not require the graphics format to be specified as it is automatically detected. ReadBinary only remains available to ensure compatibility with applications developed using older versions of csXImage. For new applications, ReadBinary2 should be used instead.

ImageCountBinary2 (OLEInput) As Long - Read-only property. Gives the number of images contained in the OLE Variant array OLEInput. Multiple images can only be read from variant arrays stored in TIFF or PDF format. For other formats this function will normally return the value 1.

ImageCountBinary (Format As TxGraphicsFormat, OLEInput) As Long - Read-only property. This property has been superseded by ImageCountBinary2 which does not require the graphics format to be specified as it is automatically detected. ImageCountBinary only remains available to ensure compatibility with applications developed using older versions of csXImage. For new applications, ImageCountBinary2 should be used instead.

1.6. Base64 Encoding

Images can be imported or exported using base64 encoding. Base64 was traditionally used for attaching binary data to documents such as emails. It can be used, for example, to store an image in a string field in a database.

WriteBase64 (Format As TxGraphicsFormat) As String - Returns a string containing an image in base64 encoding. The graphics format is defined by Format. If Format is gfTIF or gfPDF and a multi-page TIFF or PDF has been created in memory using the AddToTIF or AddToPDF function, the prepared multi-page TIFF or PDF will be written to the string instead of the current image.

This method is a function and must be called by assigning to a variable. For example, in VB, the syntax would be of the form:

StringName = WriteBase64 (gfBMP)

If UseSelection is True, WriteBase64 will write only the selected region of the image to string.

ReadBase64 (Base64Input As String) - Reads an image from a base64 encoded string. If Base64Input contains multi-page TIFF data, the image to be read is defined by the ReadImageNumber property. Data saved in PDF format cannot be read by ReadBase64.

1.7. Screen Capture

The whole screen, or a single window, can be captured using CaptureScreen or CaptureWindow.

CaptureScreen ( ) - Captures a full screenshot into the control. This is similar to using PrintScreen to capture a screenshot into the clipboard.

CaptureWindow (Handle As Long) - Captures an image of a window into the control. Handle is the Windows handle to the required window. This operates in a similar way to the Alt-PrintScreen Windows command which copies the active window to the clipboard, except that CaptureWindow can be used on any window.

1.8. File Drag & Drop

An image file in a supported format can be loaded into csXImage by dragging and dropping the file onto the control.

DragDropActive As Boolean - The drag and drop feature can de disabled by setting this property to False. (Default = True).

DragDropCancel ( ) - This method can be called from the OnStartDragDrop event procedure to cancel the current drag and drop operation. It has no effect if called at any other time.

DragDropFileName As String - Read-only property. When called from the OnStartDragDrop event procedure this returns the full path and name of the file being loaded. It returns an empty string if called at any other time.

1.9. Supported Graphics File Formats

csXImage supports the reading and writing of files in most popular formats commonly encountered. These formats are summarised here. Functions of the control which relate to a particular file format are also detailed in this section. Except where otherwise specified, csXImage fully supports reading and writing of files in these formats.

1.9.1. BMP (Bitmap)

BMP is the standard graphics format for Windows systems. The image is stored uncompressed and can be in either 24-bit RGB or paletted format. The palette can be either 256 colour, 16 colour or monochrome.

1.9.2. TIFF or TIF (Tagged Image File Format)

The TIFF file format is a very flexible format which allows images to be stored in many different ways.

The TIFF specification defines a set of 'baseline' requirements which allows for images to be stored as 24-bit RGB, paletted (256 or 16 colour), greyscale, or black and white.

The image can either be stored uncompressed or using the PackBits compression algorithm which is a simple run-length compression scheme. Black and white images may also be compressed using Modified Huffman Compression. Both these compression schemes are 'lossless', i.e., the image quality is not impacted by the compression.

csXImage fully supports the above 'baseline' TIFF requirements.

In addition, the following extensions of the TIFF format are supported:

TIFF files can store data in other formats including JPEG, YCbCr and LAB formats. These are not currently supported by csXImage.

TIFF images can include ICC colour profiles. See the section on JPEG format for further information about how csXImage handles these.

The following functions are available for the reading and writing of multi-page TIFF files:

InsertTIF (Source As String, Dest As String, Page As Long) - Inserts the image as an additional page into an existing TIFF file. The existing file is read from disk, and a new file is saved with the additional image added. The new file can either overwrite the existing one, or be saved with a different name. Source must be a complete path to the existing file, Dest is a complete path to the new file to be created, and Page is the position in the TIFF file where the image will be inserted with the first image in the file being Page = 1.

Source and Dest can be identical, in which case, the existing file is replaced. If Dest is an empty string, the existing file will be replaced. If Source cannot be found, Dest will be created new with only the single image. If Page is set to zero, the image will be inserted at the end of the file.

The following VB example shows how the InsertTIF function can be used to combine 5 images, currently held in files '1.tif', '2.tif', etc., into a single multi-page file called 'multi.tif':

ImageBox1.LoadFromFile "1.tif"
ImageBox1.SaveToFile "multi.tif"
For i = 2 To 5
  ImageBox1.LoadFromFile Str(i) & ".tif"
  ImageBox1.InsertTIF "multi.tif", "", 0
Next i

If UseSelection is True, InsertTIF will save only the selected region of the image.

DeleteTIF (Source As String, Dest As String, First As Long, Count As Long) - Deletes a range of consecutive images from an existing TIFF file and saves the file, either overwriting the existing file, or creating a new file. Source must be a complete path to the existing file, Dest is a complete path to the new file to be created, First is the position in the TIFF file of the first image to be deleted and Count is the number of images to be deleted. For example, if First is 4 and Count is 3, the images numbered 4, 5 and 6 would be deleted.

Source and Dest can be identical, in which case, the existing file is replaced. If Dest is an empty string, the existing file will be replaced.

Multiple images can be saved to a TIFF file by building the TIFF pages in memory using the following functions:

AddToTIF (Page As Long) - Stores the image temporarily in memory as a page which is ready to be written to a TIFF file. Page is the number of the page in the TIFF file where the image will be saved. If Page is set to zero, the image will be positioned at the end of the file.

WriteTIF (FileName As String) - Saves a TIFF file to disk. The file will include all the images that have previously been stored using the AddToTIF function. FileName must be a complete path to the file.

WriteTIFDialog As Boolean - Similar to the WriteTIF command, this function saves a TIFF file to disk including all the images that have previously been stored using the AddToTIF function. A standard File Save dialogue box is displayed allowing the user to select the file path and name. The return value is True if a file is saved and False if the user clicks the Cancel button or an error occurs when saving the file.

ClearTIF ( ) - Clears all the images from memory that have been stored using AddToTIF.

TIFF file compression is handled by the Compression property.

Compression As TxCompression - Defines the compression method, if any, that will be used when the file is saved. This will only apply to certain file formats as described in the table below. If a value for Compression is specified which is invalid for the file format and/or colour depth being used, the default of no compression will be applied. When an image is loaded from a file that is already using one of these compression methods, the property will be set accordingly.

The value can be:

WasCMYK As Boolean - Read-only property. Indicates whether the current image was originally read from a file using CMYK colour format. This can apply to images read from TIFF, PSD or JPEG format files.

1.9.3. JPEG or JPG (Joint Photographic Experts Group)

The JPEG file format is probably the most common method for saving full colour images, typically photographs, when a high level of compression is required. It uses a 'lossy' compression method, which means that the image read from a saved file will not be identical to the original image before it was saved.

Repeated loading and saving of a JPEG file will result in deterioration of the quality, and should be avoided, but at the levels of compression typically used for saving photographs, the loss of quality is hardly noticeable when the file is saved once from its original.The type of compression used by JPEGs does not produce good quality images that contain sharp edges and text as these edges often become blurred on saving, even using a low compression level. The JPEGQuality property controls the amount of compression used when a JPEG is saved.

JPEG compression / quality is not a universal value and different software packages use different scales. It cannot be read directly from an image, although csXImage has a read-only property, JPEGApproxQuality, that gives an approximate value. This could be useful when reading images that have already been compressed in order to save them again with a similar level of compression. If JPEGQuality is set to a higher value than that originally used to save the image, the new image will have a larger file size without gaining any quality, and it is better to avoid this if possible.

JPEG files stored in CMYK colour space can be read by csXImage and are automatically converted to RGB. Saving of JPEG files in CMYK colour space is not currently supported.

IPTC text (File Info) and Exif data can be stored in JPEG files. Support for these features is described in Section 12.

JPEG (and TIFF) images can contain information that defines how the colours should appear when displayed. A system that is frequently used is defined by the International Color Consortium (ICC) and csXImage can preserve this information when editing JPEG images. A description of colour profiles and colour management is beyond the scope of these instructions.

The default behaviour of csXImage is to discard the colour profile on opening a JPEG or TIFF. To overrule this, set the KeepICCProfile property to True before loading the image. If the current image contains an ICC colour profile, the HasICCProfile property will be set to True. An existing profile can be removed by calling the ClearICCProfile method.

The support for ICC profiles is limited to preserving or discarding existing information. There is no functionality to read information about the profile or to edit it in any way.

The following functions specific to JPEG files are available:

JPEGQuality As Integer - When an image is saved in JPEG format (file extensions .jpg, .jpeg or .jpe), the quality can be varied between a high quality image, which gives a large file, or a lower quality image, which gives a smaller file. This property can take a value from 1 to 100. 100 is the highest quality, 1 is very low quality. (Default = 90).

ProgressiveJPEG As Boolean - If true a JPEG will be saved using progressive compression instead of baseline. This property is set when a JPEG is loaded. (Default = False).

JPEGApproxQuality As Long - Read-only property. When a JPEG is loaded, this property contains an approximate value for the compression (quality) used when the image was saved. The value is an integer in the range 0 to 100. It corresponds to the same range of values as JPEGQuality except that 0 indicates that the value is undefined.

JPEGApproxQualityError As Double - Read-only property. When a JPEG is loaded, this property contains an indication of the accuracy of the JPEGApproxQuality property. A lower value indicates a higher level of accuracy. A value of less than 1 indicates that JPEGApproxQuality is a reliable measure of the quality while a value of tens or hundreds indicates that JPEGApproxQuality is merely an approximate estimate.

JPEGHigherSpeed As Boolean - When set to True any JPEG will be loaded using a reduced colour depth. The image will load at a higher speed at the expense of some image quality. Set the property before calling LoadFromFile, ReadBinary2 or LoadFromURL. (Default = False).

KeepICCProfile As Boolean - Determines whether an embedded ICC colour profile will be stored when opening a JPEG or TIFF image. This property must be set to True to save an existing profile with a JPEG or TIFF image. (Default = False).

HasICCProfile As Boolean - Read-only property. Indicates whether the current image contains an ICC colour profile. It will only return True if KeepICCProfile has been set before loading the image.

ClearICCProfile ( ) - Clears an ICC colour profile from the current image.

1.9.4. GIF (Graphics Interchange Format)

GIF format saves files using 256 colours (8-bit colour). It can compress images with large areas of a single colour very efficiently and is commonly used in web pages for backgrounds, logos, etc. The compression is 'lossless'.

GIF images support the use of a single transparent colour. Functions related to transparency are described in Section 6.

1.9.5. PSD (Photoshop Format)

This is the standard format used by Adobe Photoshop to save images. A PSD file can contain multiple layers of an image, as well as the composite image created by combining the layers together. As csXImage only holds a single image, it simply reads the composite image and ignores the layers. A PSD file saved by csXImage will only have a composite image and no layers.

PSD files stored in CMYK colour space can be read by csXImage and are automatically converted to RGB. Saving of PSD files in CMYK colour space is not currently supported.

Reading and writing of File Info (IPTC text) in PSD files is supported.

1.9.6. PNG (Portable Network Graphics)

The PNG format provides an efficient lossless compression of image data and it uses the same compression method as zip files. It provides a wide range of colour depths, but these are not all supported for writing by csXImage, although they can be read. Supported colour depths are 24 bit, 8 bit, 4 bit and 1 bit.

PNG files support the use of transparency which can be in the form of a single transparent colour, as used in GIF files, or an "alpha channel" which describes a level of transparency for each individual pixel. csXImage can extract this information when a PNG image is loaded. If the image is saved again in PNG format, the alpha channel or transparency information will be saved as part of the image.

The alpha channel will be preserved if the image is resized, cropped, rotated or flipped. Other edits will cause the alpha channel to be discarded although the image will first be merged with the background.

A PNG image can specify a background colour. This is to be shown behind transparent pixels if a viewer is unable to show whatever is behind the image. csXImage can display the image either using this background colour, or using the colour of the form or other container behind the control. csXImage will merge a PNG containing an alpha channel with this background when the image is exported to another format, or when the alpha channel is removed due to editing as described above. If no background colour is specified, white will be used by default.

It is not possible to edit an alpha channel directly but the data can be passed to a second instance of csXImage where it can be edited, then passed back.

Properties and methods related to transparency in PNG files are described in detail in Section 6.

PNG images containing a colour palette (colour images that are 8 bit or less) can specify a variable amount of transparency for each palette entry. This information is also preserved when loading and saving, but it is removed when the image is edited, except for resize, crop, rotate and flip operations These images will not be merged with a background when exported or edited, but the transparency is used in merge functions. csXImage cannot edit this type of transparency information except for the simple case where only one colour is fully transparent.

1.9.7. PCX Format

PCX is an old format for saving images of all colour depths (RGB, paletted, greyscale or black and white). It is not commonly used today, but archived images in this format may be encountered.

1.9.8. WBMP or WBM (Wireless Bitmap)

The WBMP format is used by WAP devices. It only supports black and white images.

1.9.9. PDF (Portable Document Format)

csXImage can save images to PDF files. The images are always saved one per page, with the page size set equal to the image size.

The image export methods which support PDF are SaveToFile and PostImage.

Multiple images can be saved to a PDF file by building the PDF pages in memory using the following functions:

AddToPDF (Page As Long) - Stores the image temporarily in memory as a page which is ready to be written to a PDF file. Page is the number of the page in the PDF file where the image will be saved. If Page is set to zero, the image will be positioned at the end of the file.

WritePDF (FileName As String) - Saves a PDF file to disk. The file will include all the images that have previously been stored using the AddToPDF function. FileName must be a complete path to the file.

WritePDFDialog As Boolean - Similar to the WritePDF command, this function saves a PDF file to disk including all the images that have previously been stored using the AddToPDF function. A standard File Save dialogue box is displayed allowing the user to select the file path and name. The return value is True if a file is saved and False if the user clicks the Cancel button or an error occurs when saving the file.

ClearPDF ( ) - Clears all the images from memory that have been stored using AddToPDF.

The following VB example shows how to use the above functions. Here, five images currently held in files '1.jpg' to '5.jpg' are written to a PDF file with five pages:

ImageBox1.ClearPDF
For i = 1 To 5
  ImageBox1.LoadFromFile Str(i) & ".jpg"
  ImageBox1.AddToPDF (i)
Next i
ImageBox1.WritePDF "NewFile.pdf"

An image can be inserted into an existing PDF file using the InsertPDF function.

InsertPDF (Source As String, Dest As String, Page As Long) - Inserts the image as an additional page into an existing PDF file. The existing file is read from disk, and a new file is saved with the additional image added. The new file can either overwrite the existing one, or be saved with a different name. Source must be a complete path to the existing file, Dest is a complete path to the new file to be created, and Page is the position in the PDF file where the image will be inserted with the first page in the file being Page = 1.

Source and Dest can be identical, in which case, the existing file is replaced. If Dest is an empty string, the existing file will be replaced. If Source cannot be found, Dest will be created new with only the single image. If Page is set to zero, the image will be inserted at the end of the file.

The following properties allow the property tags of PDF files to be set before they are saved. They are all strings and their use is self-explanatory. All are empty strings by default.

PDFTitle As String.

PDFSubject As String.

PDFAuthor As String.

PDFKeywords As String.

PDF (Portable Document Format) is copyright of Adobe Systems Incorporated.

2. Image Properties

This section describes properties of the image currently loaded in the control.

ColorFormat As TxColorFormat - The ColorFormat property defines the depth of colour in the image. The value of ColorFormat can be changed in order to convert the image to a different format.

ColorFormat can take one of the following values:

ImageHeight As Long - Read-only property. The height of the loaded image, in pixels. To change the height of an image, an appropriate method should be used, e.g., ResizeImage.

ImageWidth As Long - Read-only property. The width of the loaded image, in pixels. To change the width of an image, an appropriate method should be used, e.g., ResizeImage.

XDPI As Long - The horizontal pixel density of the image, in pixels per inch (dots per inch or DPI).

YDPI As Long - The vertical pixel density of the image, in pixels per inch (dots per inch or DPI).

XPelsPerMeter As Long - The horizontal pixel density of the image, in pixels per meter.

YPelsPerMeter As Long - The vertical pixel density of the image, in pixels per meter.

Note: The values of XDPI and XPelsPerMeter will remain consistent with each other if one is changed by the user. For example, if the user sets the value of XDPI, XPelsPerMeter will also be updated. The same applies to YDPI and YPelsPerMeter.

ImageLoaded As Boolean - Read-only property. Indicates whether an image is currently loaded into the control.

OriginalFormat As TxGraphicsFormat - Read-only property. Shows the original file format of the image when it was read either from disk using LoadFromFile or LoadDialog, from a URL using LoadFromURL, or from binary data using ReadBinary2.

PixelColor (X As Long, Y As Long) As OLE_COLOR - The colour of the pixel at co-ordinates X, Y.

ColorCount (Color As OLE_COLOR) As Long - Read-only property. The number of pixels in the image having colour exactly equal to Color.

IsBlank As Boolean - Indicates whether or not the current image is a blank white page. This property is typically used to identify separator pages when scanning multiple pages in a document feeder, the blank pages having been added to the batch to indicate where one multi-page file should end and the next begin. The sensitivity of this property can be adjusted using the BlankTol and BlankBorder properties.

BlankTol As Long - When the IsBlank property is used to detect blank scanned pages, some allowance must be made for imperfections. For example, there may be some marks on the blank pages, or specks of dust on the scanner glass that could cause some black pixels to appear in the scanned image. This property allows the tolerance to be adjusted and represents the number of non-white pixels that are permitted per 1,000,000 total pixels in the image before a page is judged not to be blank. (Default = 100).

BlankBorder As Double - The IsBlank property will ignore some pixels around the edge of the page when checking for a blank page. This allows for cases where the paper is slightly misaligned in the scanner and a black edge appears on the scanned image. This property allows the size of this border to be modified. The value is the percentage of the image height and width that will be ignored as border. For example, setting BlankBorder to 10% when scanning 8.5" x 11" paper will mean that a top and bottom margin each of 1.1" and a left and right margin each of 0.85" will be ignored by the IsBlank property. (Default = 5.0).

3. Resizing and Rotating Images

A comprehensive range of functions is available to change the size or orientation of an image. These include ResizeImage and ScaleImage for making the image either larger or smaller, Flip to create a mirror image, Rotate to turn through any given angle and Crop to remove the edges of the image.

Note that these functions all affect the actual image, not just its appearance on screen. To change the displayed image size without resizing the underlying image, use the Zoom function described in Section 9.

ResizeImage (NewWidth As Long, NewHeight As Long) - Resizes the loaded image to the sizes given in NewWidth and NewHeight. The sizes are in pixels. If either NewWidth or NewHeight are set to zero, this value will be ignored, and the image will be resized using the other given measurement, and maintaining the current aspect ratio.

ScaleImage (ScalePercent As Single) - Resizes the loaded image, keeping the same aspect ratio. The image is scaled by a percentage value, ScalePercent. For example, if ScalePercent = 50, the image is reduced to half size.

If ResizeImage or ScaleImage are used with the Resample property set to True, the image will be automatically converted to a ColorFormat of cf24bit.

ResizeFit (MaxWidth As Long, MaxHeight As Long) As Boolean - Resizes the image, keeping the same aspect ratio, to fit within the dimensions MaxWidth and MaxHeight. This only reduces the size of images that are too large to fit, it does not increase the size of small images. ResizeFit is a boolean function which returns the value True if the image was resized.

AutoScale ( ) As Boolean - Resizes the image, keeping the same aspect ratio, to fit within the width and height of the control. This only reduces the size of images that are too large to be displayed, it does not increase the size of small images. AutoScale is a boolean function which returns the value True if the image was resized.

Flip (FlipMode As TxFlipMode) - Flips the loaded image in either the horizontal or vertical plane (produces mirror image).

FlipMode can be either:

Rotate (Angle As Double) - Rotates the image counter-clockwise. The amount of rotation in degrees is specified by Angle.

When an image is rotated by an angle that is not a multiple of 90 degrees, there will be an area around the image that must be filled with colour. The colour specified in the BGColor property is used.

When an image is rotated by an angle that is not a multiple of 90 degrees, and the image hasColorFormat of cf24bit, and the Resample property is set to True, an antialiasing technique is used to improve the quality of the rotated image.

Crop (X1 As Long, Y1 As Long, X2 As Long, Y2 As Long) - Crops the image to a rectangle bounded by the points (X1, Y1) and (X2, Y2). If any of the specified co-ordinates are outside the current image (i.e., negative or greater than the image width or height) blank space filled with colour BGColor is added to the outside of the image.

CropToSelection ( ) - Crops the image to a rectangle containing the selected region (see Section 10). If the selected region is non-rectangular, empty pixels are filled with the background colour BGColor.

AutoCrop ( ) - Crops the image to a rectangle, removing an outer border that is lighter or darker in colour than the rest of the image. The border is automatically detected. The property DetectBorderWhite should be set to determine whether a light or dark border is searched for. AutoCrop is equivalent to calling the DetectBorder command followed by CropToSelection.

DetectBorder ( ) As Boolean - Selects a rectangular area of the image, excluding a border that is lighter or darker in colour than the rest of the image. The property DetectBorderWhite should be set to determine whether a light or dark border is searched for. The return value is True if the detection is successful.

DetectBorderWhite As Boolean - If True, AutoCrop and DetectBorder search for a border that is whiter (or lighter) than the rest of the image. Set to False to search for a blacker (or darker) border. (Default = True).

Resample As Boolean - If set to True, this determines that an antialiasing technique is used to improve image quality of rotated, resized, scaled or zoomed images. (Default = False).

FilterType As Long - Determines the filter used when the image is resampled during a ResizeImage or ScaleImage operation (but not for Rotate which uses a different filter). Filters are 1 - Bilinear, 2 - Hermite, 3 - Bell, 4 - B-Spline, 5 - Lanczos, 6 - Mitchell. (Default = 1).

4. Modifying and Enhancing the Image

This section describes the functions that are available to change the appearance of an image.

Brightness (Value As Long, DoRed As Boolean, DoGreen As Boolean, DoBlue As Boolean) - Adjusts the brightness of the loaded image. Value must be an integer between 0 (minimum) and 100 (maximum).

DoRed, DoGreen, DoBlue, are boolean values indicating which of the three colours are adjusted. For normal brightness adjustment, set all three parameters to True.

If the image is in a grayscale format, i.e., it has ColorFormat of cfMonoBW, cf16Grayscale or cf256Grayscale, the values entered for DoRed, DoGreen and DoBlue are ignored. In this case, these parameters will default to True.

If UseSelection is True and the ColorFormat is cf24bit, the brightness is only adjusted in the selected region of the image.

Contrast (Value As Long, DoRed As Boolean, DoGreen As Boolean, DoBlue As Boolean) - Adjusts the contrast of the loaded image. Value must be an integer between 0 (minimum) and 100 (maximum).

DoRed, DoGreen, DoBlue, are boolean values indicating which of the three colours are adjusted. For normal contrast adjustment, set all three parameters to True;.

If the image is in a grayscale format, i.e., it has ColorFormat of cfMonoBW, cf16Grayscale or cf256Grayscale, the values entered for DoRed, DoGreen and DoBlue are ignored. In this case, these parameters will default to True.

If UseSelection is True and the ColorFormat is cf24bit, the contrast is only adjusted in the selected region of the image.

Sharpen ( ) - Sharpens the loaded image. This method requires no parameters.

Sharpen is exactly equivalent to the command SharpenBy (5).

SharpenBy (Value As Long) - Sharpens the loaded image. Value is an integer between 1 and 10 to specify the amount of sharpening. 1 gives a small sharpening effect, 10 gives a large effect.

Blur ( ) - Blurs the loaded image. This method requires no parameters.

Blur is exactly equivalent to the command BlurBy (5).

BlurBy (Value As Long) - Blurs the loaded image. Value is an integer between 1 and 10 to specify the amount of blurring. 1 gives a small blurring effect, 10 gives a large effect.

If UseSelection is True, Sharpen, SharpenBy, Blur and BlurBy only affect the selected region of the image.

ReduceRedEye ( ) - Reduces the red intensity for pixels in which the red intensity is significantly higher than the blue and green intensity. This method is intended for use on images where flash photography has resulted in a "red-eye" effect on the subject. It should be used in conjunction with selection of a region of the image, usually by using the SelectEllipse method to select the affected area of the eye. This method only operates on 24-bit images.

Invert ( ) - Converts the image to its negative by changing the colour of each pixel to the opposite colour, i.e., black is changed to white, white to black, etc.

Despeckle ( ) - Removes small marks, or specks, from an image. Small groups of pixels that are completely surrounded by pixels of another continuous colour are converted to that continuous colour.

DespeckleTol As Long - The maximum size of a group of pixels that will be removed using the Despeckle method. Valid values for DespeckleTol are in the range 1 to 9. A value of 1 means that only single pixel specks will be removed. With a value of 9, a group of pixels up to 3 pixels across and 3 pixels down will be removed. It is normally appropriate to leave this property at the default value, but on low resolution images a smaller value may be appropriate to prevent the Despeckle method removing punctuation marks or the dot on the letter 'i' from text. (Default = 9).

HLSAdjust (Hue As Double, Lightness As Double, Saturation As Double) - This can adjust one or more of the components in HLS colour space. The parameters are numbers between -100 and +100, where 0 is no change. Hue is measured on a circular scale and an adjustment of 100% in either direction brings it back to the starting point. Adjusting Lightness or Saturation by -100% will set them to zero while adjusting by +100% will double the existing value.

Example:

ImageBox1.HLSAdjust 0, 0, 30

This would increase the colour saturation of the image by 30%, leaving the hue and lightness unchanged.

Deskew ( ) - Straightens a misaligned image. This can be applied to any image, but is primarily intended for use with pages of horizontal text that have been scanned with the paper slightly misaligned in the scanner.

DeskewAngle As Double - Read-only property. Calculates and returns the angle in degrees that the image would need to be rotated by in order to straighten the image. This allows the angle to be found without actually doing the rotation as is done by the Deskew method.

DeskewMaxAngle As Long - The maximum angle of rotation that will be considered by the Deskew method or the DeskewAngle property. In calculating the angle required to deskew an image, angles in the range –DeskewMaxAngle degrees to +DeskewMaxAngle degrees are evaluated. If a wider range is considered, the calculation takes more time. The default value is sufficient for deskewing most misaligned scanned pages and could in most cases be reduced to speed up the processing of large images. (Default = 15).

CombineColors (Color As OLE_COLOR, DeltaRed As Long, DeltaGreen As Long, DeltaBlue As Long) - This converts similar colours in a range to a single colour. The new colour is defined by Color with allowed difference in the RGB components of the colour being defined by DeltaRed, DeltaGreen and DeltaBlue, which are all integers in the range 0 to 255.

A typical use of this function would be to set a single colour background to have identical colour values for each pixel so that the background can be filled with a new colour or made transparent for merging with another image.

ColorReplace (OldColor As OLE_COLOR, NewColor As OLE_COLOR) - This replaces any pixels coloured OldColor and changes them to NewColor. This command applies to 24 bit coloured images only. For other images use PaletteEntry to edit the colour palette.

The following functions are for working with the colour palettes of palettised images.

PaletteEntry (Index As Long) As OLE_COLOR - The colour used by entry Index in the colour palette for the current image. If this property is read for a 24-bit colour image or with a value of Index that is outside the valid range for the current image, a zero value, equivalent to the colour black, will be returned.

Changing a palette entry will change the colour of all the pixels in the image that use that palette entry.

PaletteSize As Long - Read-only property. Returns the number of palette entries. This depends on the value of the ColorFormat property. For cf256Color and cf256Grayscale, the value is 256. For cf16Color and cf16Grayscale, the value is 16. For cfMono and cfMonoBW, the value is 2. For cf24bit, the value zero is returned.

ColorIndex (Color As OLE_COLOR) As Long - Returns the first index used by Color. If the colour is not present in the palette the return value is -1.

FindUnusedColor ( ) As Long - Returns the index of the first entry in the palette that is not used by any pixels. The return value is -1 if all the palette entries are used by pixels or if the image is 24 bit.

The following functions convert between RGB and HLS colour space values.

RGBToHue (Color As OLE_COLOR) As Double - This takes an RGB colour value and returns the equivalent hue as a value between 0 and 360.

RGBToLightness (Color As OLE_COLOR) As Double - This takes an RGB colour value and returns the equivalent lightness as a value between 0 and 1.

RGBToSaturation (Color As OLE_COLOR) As Double - This takes an RGB colour value and returns the equivalent saturation as a value between 0 and 1.

HLSToRGB (Hue As Double, Lightness As Double, Saturation As Double) As OLE_COLOR - This takes three H, L, S, parameters and returns the equivalent RGB colour value. Hue is a number between 0 and 360. Lightness and Saturation are numbers between 0 and 1.

5. Merging Images and Watermarking

These functions are used for merging two images together. A wide range of options is provided allowing many different effects. The images can be simply merged with one smaller image copied over the top of a larger image, or a watermark effect can be obtained by using transparency in one of the images.

One image must be loaded into the control to start with. The second image can be read from a number of different sources including a file on disk, a variant array held in memory, or a bitmap handle. The following three functions cover each of these three options.

MergeFile (MergeImageFile As String) - Merges a second image with the current loaded image. The two images can have different sizes and different colour formats. The resulting image retains the size and colour format of the current image.

MergeImageFile is a String that must contain a complete path to the file containing the second image.

MergeBinary (Format As TxGraphicsFormat, MergeImageBin As OLEVariant) - This is identical to the MergeFile method, except that the second image is read from a variant array instead of from a file on disk.

MergeImageBin is the name of the variant array. Format defines the graphics format used in the variant array.

MergeHandle (Handle As Long) - This is identical to the MergeFile method, except that the second image is referenced by a handle to a bitmap. For example, this could be an image currently displayed in another control.

Handle is a handle to a bitmap.

When MergeHandle is used to merge with an image from either the Image property of a VB PictureBox, or another instance of csXImage, the ReleaseBMPHandle property should be set to False.

The following properties can be set to modify the behaviour of the MergeFile, MergeBinary and MergeHandle methods. Note that if the second (watermark) image is a GIF or PNG including transparency information, this information will be used in merging the images instead of the MergeTransparent, MergeTransparentColor and MergeTransparency properties.

MergeTransparent As Boolean - If MergeTransparent is True, one colour in the second image will be ignored in the merge process, i.e., it will be treated as if it is transparent. This can typically be used where the second image contains text or an image on a white background, and the background is to be treated as transparent (Default = False).

MergeTransparentColor As OLE_COLOR - Specifies the colour that is to be treated as transparent if MergeTransparent is True. (Default = White, &H00FFFFFF).

MergeTransparency As Double - A value between 0 and 100 indicating the percent overall transparency of the second (watermark) image. A value of 100 means that the watermark is 100% transparent and the main image will be unchanged. A value of 0 means that the watermark is opaque and will completely overstamp the main image. (Default = 0).

MergeLeft As Long - The distance in pixels between the left side of the main image and the left side of the second image. Used when MergeStyle is wmSingle only. (Default = 0).

MergeTop As Long - The distance in pixels between the top of the main image and the top of the second image. Used when MergeStyle is wmSingle only. (Default = 0).

MergeReverse As Boolean - Normally, the currently loaded image is the main (background) image and the second image is merged as a watermark. If MergeReverse is set to True, the images are reversed, i.e., the current image is used as the second (watermark) image, and the second image becomes the main image. The size and colour format is then taken from the second image. (Default = False).

MergeStyle As TxWMStyle - MergeStyle provides several options for the way that the merge will be implemented. The options are:

6. Transparency

Images saved in GIF or PNG format can include transparency information. Transparency can be one of three types:

When an image is loaded into csXImage, transparency information is available and is preserved when the image is saved. Alpha channel information is preserved when an image is resized, cropped, rotated or flipped. Other edits cause the alpha channel to be discarded although the image will first be merged with the background.

The following functions relate to single colour transparency:

Transparent As Boolean - Indicates that an image includes transparency information. This is only used by images to be saved in GIF or PNG formats. (Default = False).

TransparentColor As OLE_COLOR - The background, or transparent colour to be used in images with transparency. This is used by images to be saved in GIF or PNG formats. This colour is also used to fill in the background of rotated images using the Rotate method. (Default = White, &H00FFFFFF).

Note: this property was called BGColor in versions of csXImage before version 3.3. BGColor can still be used to ensure upward compatibility of applications.

The following functions are related to alpha transparency or palette transparency:

HasAlpha As Boolean - Read-only property. This indicates whether the currently loaded image contains an alpha channel.

BackgroundColor As OLE_COLOR - The colour of the background that will be shown behind transparent pixels when an image containing an alpha channel is exported. (Default = White, &H00FFFFFF).

HasBackground As Boolean - This determines whether the current image contains a background colour which will be stored when the image is exported in PNG format. (Default = False).

AlphaDisplayBackground As Boolean - csXImage will normally attempt to display an image with an alpha channel by merging transparent pixels with the background colour of the form or other container of the control. Backgrounds that are not plain, e.g., images, patterns or text, will not be merged. By setting this property to True, the BackgroundColor property will be used instead. (Default = False).

ExtraAlphaValue As Long - When an image containing an alpha channel is rotated by an angle that is not a multiple of 90 degrees, or cropped to co-ordinates that make the image bigger, the new area created will have an alpha value specified by this property. The value must be in the range 0 to 255 where 0 is fully transparent and 255 is fully opaque. (Default = 0).

ClearAlpha ( ) - This removes any alpha channel from the current image without merging it with the background.

CombineAlphaWithBG ( ) - This combines the image with the background colour, if it contains an alpha channel. The alpha channel is then removed.

NewAlpha (Value As Long) - This creates an alpha channel for the current image and sets the value for each pixel to Value, which must be an integer between 0 and 255. 0 means fully transparent and 255 means fully opaque. The ColorFormat of the image will be converted to cf24bit if it is not already.

AlphaPixel (X As Long, Y As Long) As Long - The alpha value of the pixel at co-ordinates X, Y. If the image has no alpha channel, or the values of X or Y are invalid, this will return the value -1.

AlphaText (X As Long, Y As Long TextString As String) - This method is similar to DrawText, but is used for writing antialiased text onto an image with an alpha channel. The alpha channel is preserved. It writes the text contained in TextString onto the image, starting at the point (X, Y).

TransparentPalette As Boolean - When True, the image contains a partially transparent palette. At the time of writing only PNG images support this. Setting TransparentPalette to True automatically sets Transparent to False and setting Transparent to True sets TransparentPalette to False. (Default = False).

TransparentArray (Index As Long) As Long - The values for palette transparency are stored in a zero based array where 0 is fully transparent and 255 is fully opaque. The first entry in TransparentArray corresponds to the first palette colour and the second to the second palette colour, and so on. csXImage stores values with Index from 0 to 255, although 1 bit and 4 bit images will not use all of them.

PaletteToAlpha ( ) - This method will convert a paletted image with transparency to a 24 bit colour image with an alpha channel. It can be used with single colour transparency and variable palette transparency. It will have no effect if Transparent and TransparentPalette are both False or if the colour depth is 24 bit.

The alpha channel can be edited by extracting it as a separate greyscale image and importing this into another instance of csXImage. This can be done either through a file saved to disk using SaveAlphaAsBMP and LoadAlphaAsBMP, or by passing the handle of the alpha channel using AlphaHDC.

SaveAlphaAsBMP (FileName As String) - If the current image contains an alpha channel this will save it as a greyscale bitmap. Full transparency is shown as black and full opacity is shown as white. FileName is the physical path to the saved file and it should have the extension .bmp.

LoadAlphaAsBMP (FileName As String) - This will load an alpha channel into the current image where FileName is the physical path to a greyscale bitmap file. This bitmap must be exactly the same width and height as the current image.

AlphaHDC As Long - Returns a Windows handle to a greyscale bitmap corresponding to the alpha channel. This works in a similar way to the BMPHandle property and is compatible with it. It can be used to pass an alpha channel between instances of csXImage so the data can be edited using the full range of component methods and properties. When importing an alpha channel with AlphaHDC, the imported image must have exactly the same dimensions as the current image.

Loading an image with palette transparency will set TransparentPalette and populate TransparentArray. A new image will default to TransparentArray containing all values of 255 and TransparentPalette will be False.

7. Drawing

A number of simple methods and properties are provided to enable drawing of lines, basic shapes and text on the image.

7.1. Pen and Brush Properties

The appearance of all objects drawn on the image is determined by Pen and Brush properties. Lines and the perimeters of shapes are drawn by the Pen. Shapes are filled by the Brush. Text is drawn by the Pen on a background filled by the Brush.

PenColor As OLE_COLOR - The colour of the Pen which will be used for drawing lines or the perimeters of shapes. (Default = Black, &H00000000).

PenMode As TxPenMode - Defines the way that the Pen will draw. Possible values are:

PenStyle As TxPenStyle - Defines the style in which the Pen draws lines. Possible values are:

Note: Dotted or dashed pen styles are only available when the PenWidth property is 1.

PenWidth As Long - Defines the maximum width of the Pen in pixels. (Default = 1).

BrushColor As OLE_COLOR - The colour of the Brush which will be used for filling shapes. (Default = White, &H00FFFFFF).

BrushStyle As TxBrushStyle - Defines the pattern for the Brush. Possible values are:

Antialias As Boolean - If Antialias is True, any text, lines or shapes drawn will be antialiased. The appearance will be controlled by the current value of the FilterType property and setting this to 3 or 4 will give a smoother appearance. Drawing an antialiased feature will automatically convert the image to a 24 bit colour depth (ColorFormat = cf24bit). (Default = False).

7.2. Drawing Lines

DrawLine (X1 As Long, Y1 As Long, X2 As Long, Y2 As Long) - Draws a straight line from X1, Y1 up to but not including X2, Y2 using the current Pen settings.

7.3. Drawing Shapes

Rectangle (X1 As Long, Y1 As Long, X2 As Long, Y2 As Long) - Draws a rectangle using the current Pen settings and filled using the current Brush settings. The rectangle is bounded by the points (X1, Y1) and (X2, Y2).

Ellipse (X1 As Long, Y1 As Long, X2 As Long, Y2 As Long) - Draws an ellipse using the current Pen settings and filled using the current Brush settings. The ellipse is bounded by the rectangle defined by the points (X1, Y1) and (X2, Y2).

CircleCR (X As Long, Y As Long, R As Long) - Draws a circle using the current Pen settings and filled using the current Brush settings. The centre of the circle is at X, Y and the radius is R.

Circle3XY (X1 As Long, Y1 As Long, X2 As Long, Y2 As Long, X3 As Long, Y3 As Long) - Draws a circle using the current Pen settings and filled using the current Brush settings. The perimeter of the circle passes through the points (X1, Y1), (X2, Y2) and (X3, Y3).

RoundRect (X1 As Long, Y1 As Long, X2 As Long, Y2 As Long, X3 As Long, Y3 As Long) - Draws a rectangle with rounded corners using the current Pen settings and filled using the current Brush settings. The rectangle is bounded by the points (X1, Y1) and (X2, Y2). The curve of the rounded corners matches the curvature of an ellipse with width X3 and height Y3.

Pie (X1 As Long, Y1 As Long, X2 As Long, Y2 As Long, X3 As Long, Y3 As Long, X4 As Long, Y4 As Long) - Draws a pie shaped section of an ellipse using the current Pen settings and filled using the current Brush settings. The ellipse is formed from a rectangle bounded by the points (X1, Y1) and (X2, Y2). The sides of the pie are defined by the intersections between the centre of the ellipse and the points (X3, Y3) and (X4, Y4).

Arc (X1 As Long, Y1 As Long, X2 As Long, Y2 As Long, X3 As Long, Y3 As Long, X4 As Long, Y4 As Long) - Draws an arc. The arc traverses the perimeter of an ellipse that is bounded by the points (X1, Y1) and (X2, Y2). The arc is drawn following the perimeter of the ellipse, counter-clockwise, from the starting point to the ending point. The starting point is defined by the intersection of the ellipse and a line defined by the centre of the ellipse and (X3, Y3). The ending point is defined by the intersection of the ellipse and a line defined by the centre of the ellipse and (X4, Y4).

Arc3XY (X1 As Long, Y1 As Long, X2 As Long, Y2 As Long, X3 As Long, Y3 As Long) - Draws an arc. The arc traverses the perimeter of a circle from (X1, Y1) to (X3, Y3) passing through (X2, Y2).

Chord (X1 As Long, Y1 As Long, X2 As Long, Y2 As Long, X3 As Long, Y3 As Long, X4 As Long, Y4 As Long) - Draws a shape that is defined by an arc and a line that joins the endpoints of the arc. The chord consists of a portion of an ellipse that is bounded by the points (X1, Y1) and (X2, Y2). The ellipse is bisected by a line that runs between the points (X3, Y3) and (X4, Y4).

The perimeter of the chord runs counter-clockwise from (X3, Y3), along the ellipse to (X4, Y4), and straight back to (X3, Y3). If (X3, Y3) and (X4, Y4) are not on the surface of the ellipse, the corresponding corners on the chord are the closest points on the perimeter that intersect the line.

PointAdd (X As Long, Y As Long) - Adds a point to be used as a vertex when drawing a polygon. See Polygon for an explanation of how to use this method.

Polygon ( ) - Draws a polygon. The polygon will be constructed by joining a series of points which act as vertices of the polygon. To use this method, first call PointAdd several times to define the vertices as points, then call Polygon to complete the drawing. After calling Polygon the list of points is automatically cleared in readiness for drawing another polygon.

BezierPointAdd (X As Long, Y As Long) - Adds a point to be used by the PolyBezier method.

PolyBezier ( ) - Draws a set of cubic Bezier curves using the points added by BezierPointAdd. The first curve is drawn from the first point to the fourth point, using the second and third points as control points. Each subsequent curve in the sequence needs exactly three more points. The ending point of the previous curve is used as the starting point, the next two points in the sequence are control points and the third is the ending point. The current Pen settings are used. The points stored by BezierPointAdd are cleared after calling PolyBezier.

FloodFill (X As Long, Y As Long) - Fills a region of the image with BrushColor. The fill starts at co-ordinates X, Y and moves outwards until a boundary is reached. The boundary is defined by FloodFillColor and FloodFillStyle. FloodFillStyle can be fsBorder, in which case, the fill continues to a boundary of pixels of FloodFillColor, or can be fsSurface, in which case pixels of FloodFillColor are filled.

FloodFillColor As OLE_COLOR - The colour that defines the boundary of the FloodFill method. (Default = Black, &H00000000).

FloodFillStyle As TxFloodFillStyle - Defines the behaviour of the FloodFill method. Possible values are:

7.4. Drawing Text

DrawText (X As Long, Y As Long, TextString As String) - Writes the text contained in TextString onto the image, starting at the point (X, Y) and using the font defined by property TextFont. The text can be written at an angle specified in the property TextAngle. The colour of the text is PenColor and the colour of the background to the text is BrushColor. The property TextTransparent can be set to True to give a transparent background. The text will be left or right justified, or centred, depending on the value of TextJustify. Note that the value of X will define the left side of the text for left-justification, the right side for right-justification, and the centre for centred text.

TextString is actually an OLE BSTR data type, which is a string of double-byte characters. It fully supports the use of Unicode characters. For Unicode to display correctly, TextFont must be set to a suitable font which contains the necessary characters and is installed on the system.

The control characters Carriage Return (CR - ASCII character 13) and Line Feed (LF - ASCII character 10) can be included as many times as required in TextString in order for the text to be printed on multiple lines. Blank lines can be inserted in a block of text by using two or more CR characters consecutively.

If the Antialias property is set to True the text will be drawn antialiased to give it a smoother appearance.

TextFont As IFontDisp - Defines the font to be used for the DrawText method. The TextFont property can be changed by referring to various sub-properties, e.g., Bold, Italic, Name, etc. For example, the following VB code sets the TextFont property of ImageBox1 to Arial 12 (Bold):

ImageBox1.TextFont.Name = "Arial"
ImageBox1.TextFont.Size = 12
ImageBox1.TextFont.Bold = True

Some programming environments do not support the TextFont property, so as an alternative, the following four properties can access some of the font sub-properties directly.

TextFontName As String - Equivalent to TextFont.Name.

TextFontSize As Long - Equivalent to TextFont.Size.

TextFontBold As Boolean - Equivalent to TextFont.Bold.

TextFontItalic As Boolean - Equivalent to TextFont.Italic.

TextAngle As Single - The angle in degrees, measures counter-clockwise from the horizontal, of text written by the DrawText method. (Default = 0).

TextTransparent As Boolean - If TextTransparent is True, text written by the DrawText method will have a transparent background. (Default = False).

TextTransparency As Long - Text can be made partially transparent by setting this property which defines the amount of transparency for text written by the DrawText method. The value is in percent and must be an integer from 0 to 100. 0 means the text is fully opaque and 100 means it is invisible. Setting it to a high value makes the text appear as a watermark. The image must be 24 bit colour for this property to have any effect. (Default = 0).

TextWidth (TextString As String) As Long - Read-only property. Returns the width, in pixels, that will be used if the string TextString is written onto the image using the DrawText method.

TextHeight (TextString As String) As Long - Read-only property. Returns the height, in pixels, that will be used if the string TextString is written onto the image using the DrawText method.

TextJustify As TxTextJustify - Defines the text justification (alignment) that will be used by the DrawText method. Possible values are:

8. Interacting with Hardware (Printers, Scanners and Cameras)

8.1. Printers

Functions are provided in csXImage to enable printing, either through a print dialogue, which includes a print preview, or by sending images directly to a printer, controlled by a number of properties.

In both cases the printing is started by PrintImage, with UsePrintDialog determining the mode of operation.

If it is desired to write an application with a customised print dialogue, then normal print functions can be used from most programming environments, independent of the functions described here.

PrintImage As Long - Read-only property. Starts printing, either through a dialogue, or immediately, depending on the value of the boolean property UsePrintDialog. The return value indicates the result of the printing as follows:

UsePrintDialog As Boolean - If set to True, a dialogue is displayed when PrintImage is called. This dialogue allows selection of printer and adjustment of various print properties. It also provides a print preview. If set to False, the image prints immediately when PrintImage is called. (Default = True).

The dialogue can be customised for use in other languages. See the explanation of properties PDS_Title etc. at the end of this section.

PrinterIndex As Long - The index number of the selected printer. Setting this property to -1 selects the default printer. (Default = -1).

PrintPaperSize As Long - An integer value indicating the paper size to be used for printing. These values are defined by the Windows operating system and there are a large number of possible values (approximately 100). All possible values are supported, but only the most common paper sizes are listed below for reference:

PrintUnits As TxPrintUnits - The units of measurement to be used for the properties PrintLeft & PrintTop which determine the position of the printed image. Possible values are:

PrintLeft As Double - The distance from the left side of the page to the left side of the image, in units specified by PrintUnits. Note that this property is not used if PrintFit or PrintCentre are set to True. (Default = 0).

PrintTop As Double - The distance from the top of the page to the top of the image, in units specified by PrintUnits. Note that this property is not used if PrintFit or PrintCentre are set to True. (Default = 0).

PrintCopies As Long - The number of copies to be printed. (Default = 1).

PrintScale As Double - The scaling factor of the printed image. The normal size of a printed image is determined by the size of the image in pixels and the resolution of the image in pixels per inch, or per meter (see properties XDPI etc.). If PrintScale is set to a value different from 100%, the image size will be adjusted accordingly. Note that this property is not used if PrintFit is set to True. (Default = 100).

PrintOrientation As TxPrinterOrientation - The orientation of the printed image. Possible values are:

PrintPaperSource As Long - An integer value indicating the paper source or tray to be used for printing. These values are defined by the Windows operating system and there are more possible values than listed here. All possible values are supported, the following being the more commonly used ones:

PrintFit As Boolean - If set to True, the size of the printed image is adjusted to fit the page. (Default = False).

PrintCentre As Boolean - If set to True, the printed image is positioned at the centre of the page. (Default = False).

PrintTitle As String - The document title that will be displayed in the printer manager when printing. (Default = 'Chestysoft csXImage').

PrinterCount As Long - Read-only property. The number of installed printers.

PrinterName (Index As Long) As String - Read-only property. The name of the printer referenced by Index.

SelectPrinterByName (Name As String) As Boolean - Sets PrinterIndex to the printer given by Name. The return value is True if a printer matching Name is found and selected.

The dialogue displayed when UsePrintDialog is set to True can be customised for use in languages other than English. All the text strings used for buttons, checkboxes etc. can be set to a different value using the following string properties prefixed with 'PDS_' (Print Dialogue String).

Note the possibility to include an ampersand (&) in some of the strings, e.g., PDS_Portrait, to indicate a short-cut key.

PDS_Title - The title at the top of the dialogue. (Default = 'Print Preview').

PDS_Printer - The label for the list of printers. (Default = 'Printer:').

PDS_Paper - The label for the list of paper sizes. (Default = 'Paper Size:').

PDS_Orientation - The text in the group/frame for selecting orientation. (Default = 'Orientation').

PDS_Portrait - The text for the option button for selecting portrait. (Default = 'P&ortrait').

PDS_Landscape - The text for the option button for selecting landscape. (Default = '&Landscape').

PDS_PaperDefault - The first entry in the list of paper sizes, indicating that the default paper size for the selected printer will be used. (Default = '(Printer Default)').

PDS_Position - The text in the group/frame for defining position. (Default = 'Position').

PDS_Left - The label for the left position. (Default = 'Left:').

PDS_Top - The label for the top position. (Default = 'Top:').

PDS_Units - The label for the measurement units. (Default = 'Units:').

PDS_Copies - The label for the number of copies. (Default = 'Copies:').

PDS_Scale - The label for the scale. (Default = 'Scale:').

PDS_Fit - The text on the checkbox for fitting to a page. (Default = '&Fit to Page').

PDS_Centre - The text on the checkbox for centring on a page. (Default = 'C&entre on Page').

PDS_Print - The text on the print button. (Default = '&Print').

PDS_Cancel - The text on the cancel button. (Default = '&Cancel').

8.2. Scanners and Cameras (TWAIN)

Images can be imported from a TWAIN compliant device such as a scanner or a webcam.

There are three steps involved in acquiring an image and the functions associated with each step are described in turn. The steps are:

  1. Selecting the TWAIN device to be used.
  2. Configuring the settings of the device, e.g. resolution.
  3. Acquiring the image.

8.2.1. Information about TWAIN

TWAIN is an industry standard for communication between software applications and devices for image acquisition. It was first developed in the early 1990s, but has been regularly updated since. The latest version number of the TWAIN specification is 2.3 and this was released in 2013.

csXImage is fully compatible with version 2.3 of the specification.

Overview

Communication in an application that uses csXImage can be summarised by the diagram below.

TWAIN Communications

TWAIN defines the communication between three elements. The first element is the Application. This refers to the software you will create using csXImage as a component. The second element is the Data Source Manager (DSM). This is a dynamic link library that exists on all systems where TWAIN is to be used. All communication goes through the DSM. The third element is the Source. If an image is being acquired from hardware such as a scanner, the Source is the device driver for the hardware. Only the device driver communicates directly with the hardware.

All communication follows the arrows shown on the diagram. So if the Application requests that an image is scanned, this request is first sent to the Data Source Manager, which relays the request to the Source. The Source controls the scanner to scan the image, then sends the image back to the Application via the Source Manager.

In the documentation for csXImage and in the naming of functions, the word Device is often used instead of Source.

TWAIN Versions and the Source Manager

For most of the time that TWAIN has been in use, the version number of the TWAIN specification was 1.x (i.e., 1.7, 1.8 etc.). In 2008, version 2.0 was released, and this has been updated several times, the latest version being 2.3 in 2013.

As well as adding some new features, version 2.0 introduced some significant changes, including:

csXImage checks whether or not the DSM is compatible with version 2.0 or above, and if it is, the newer memory management, communication and image transfer methods will be used. If the DSM is only capable of supporting version 1.x, then csXImage will revert to the legacy behaviour. It should not matter whether or not the source is compatible with version 2.0, as the DSM is backwards compatible and can communicate with older drivers. However, our experience shows that many older drivers behave badly when used with the newer DSM, so functions are provided in csXImage to manage this situation if necessary (see the properties TwainUseNewDSM and TwainCallbackMode).

The Data Source Manager is one of two files. It is either ‘TWAIN_32.DLL’, which should be found in the Windows directory, or it is ‘TWAINDSM.DLL’ which should be in the appropriate system directory. On 32-bit systems, this is the System32 directory. On 64-bit systems there can be two versions of TWAINDSM.DLL, a 32-bit version in the SysWOW64 directory and a 64-bit version in the System32 directory.

TWAIN_32.DLL is normally installed as part of the operating system and should always be present on all 32-bit or 64-bit versions of Windows. TWAINDSM.DLL is newer and it will be necessary to install this in order to support the 2.x versions of TWAIN. csXImage will work with whichever version it finds, so if you require that your application uses a particular version of the DSM, you must make sure that the chosen version is installed and available for use on the end user system.

The installer for csXImage copies the latest version of the 32-bit TWAINDSM.DLL to a directory called x86DSM under the installation path. If you want your application to use this file it should be copied to the appropriate location as described above (SysWow64 on a 64-bit system or System32 on a 32-bit system). The 64-bit TWAINDSM.DLL is installed automatically by the csXImage installer.

The following functions help to manage the version of TWAIN in use or provide information about the version.

TwainUseNewDSM As Boolean - By default, csXImage will first search for TWAINDSM.DLL in the appropriate system directory. If it is found, it will be used as the Data Source Manager. If it is not found, the older TWAIN_32.DLL will be used instead.

By setting this property to False, the behaviour is reversed, and TWAIN_32.DLL will be used as the first choice. Only if TWAIN_32.DLL is not found and TWAINDSM.DLL is found will TWAINDSM.DLL be used. This should never happen in practice, as TWAIN_32.DLL should always be available.

If this property is set it will cause the connection to the DSM to be closed and re-opened. It is therefore recommended that it should only be set in the first few lines of code before any other use of the TWAIN functions in csXImage. (Default = True).

TwainDSM2x As Boolean - Read-only Property. If this property returns True, the Data Source Manager currently in use supports version 2.0 or above of the TWAIN specification.

TwainDevice2x As Boolean - Read-only Property. If this property returns True, the device currently selected supports version 2.0 or above of the TWAIN specification.

TwainDeviceVersion As String - Read-only Property. The version number of the TWAIN specification supported by the device currently selected.

TwainDSMPath As String - Read-only Property. Gives the full path and file name of the Data Source Manager in use. This can be useful to confirm that the DSM in use is the one that is expected to be in use if multiple DSM files are available on the system.

TwainCallbackMode As Long - When using a new DSM compatible with TWAIN version 2.x, some problems can be experienced with older device drivers that are not compatible. In some cases this is due to the use of the new ‘callback’ method for communications between the source and the application.

This property has three possible values that determine whether or not callback will be used.

1 - Callback is always used if the DSM is version 2.x compatible.

2 - Callback is used if both the DSM and the device driver are version 2.x compatible.

3 - Callback is never used.

(Default = 2).

8.2.2. Selecting the Device

The first step to acquiring an image is to select the hardware device to be used. There are three alternative ways to do this. The first is to use the SelectTwainDevice method which will bring up a dialog box offering the user a choice from the list of devices installed on the system. Alternatively, the device number can be set directly using the CurrentTwainDevice property or the SelectTwainDeviceByName function can be called if the exact name is known.

Two other properties are provided to give access to information about the installed devices. These are TwainDeviceCount and T