Website: www.chestysoft.com Email: info@chestysoft.com
csImageFile - COM Object for Image Manipulation
Version 4.2
Introduction
This component enables image files of the type JPG, GIF, BMP, PNG, PSD, PCX, TIF and WBMP to be created, manipulated, resized, or edited. Functions are available for adding text to the image as well as for drawing lines and shapes, with optional antialiasing. Conversions can be made between file formats. It is a non-visual component developed for server side scripting, especially Active Server Pages. It can also be used by other COM enabled tools such as Visual Basic and Cold Fusion.
The sample code in these instructions assumes VBScript is used with ASP. Other languages will require some changes to syntax particularly with object creation and the use of brackets to enclose function parameters. Some of the important syntax differences will be covered at the end of these instructions.
An image is read into memory from disk or from a data stream or a new image can be created. Image processing operations can be performed, such as resizing, cropping or rotating. The image can also be merged with another to create a composite image or watermark. The resulting image can then be saved to disk, or streamed to a browser or database.
As of version 4.0 the GIF file format is fully supported. However, there are still some patents in force in some countries concerning LZW compression. If your country is affected by one of these patents you can disable LZW compression by setting the UseLZW property to false. This will prevent GIFs from being read and will ensure that any GIFs exported are in an uncompressed format. It also prevents LZW TIFs from being read. Animated GIFs are not supported and only the first frame will be extracted on reading.
Support for PNG images is limited. Transparency is restricted to a single colour and alpha channel information will be lost once an image is loaded. Data on gamma correction, chromaticity, text and keywords will also be lost. Not all TIF compression formats are supported and only "Baseline TIFF", LZW, Group 3 and Group 4 compressed TIFs can be read.
Some meta data, or "File Info" can be read from and written to JPG and PSD files. This data can also be read from and saved to files using both the .FFO and .XMP extensions. The supported properties are listed later in these instructions. Exif attributes stored in JPG files can be accessed as read only.
Before use the ActiveX file csImageFile.dll should be registered on the server using REGSVR32.EXE. Regsvr32 is usually to be found in the Windows System folder, and it runs at the command prompt using the syntax:
regsvr32 dllname
where dllname is the path and name of the dll to register. Chestysoft has a free utility that performs this function through a Windows interface. For more information on this, visit the Chestysoft web site, or follow this link.
The methods and properties described in these instructions are grouped into the following sections:
Input/Output, Image Manipulation, Image Editing, Text, File Info, Exif Attributes and File Utilities. There is also a section on how to stream an image to the browser.
The trial version of csImageFile is supplied as a separate DLL called csImageFileTrial.dll. It has a fixed expiry date which can be found by reading the Version property. It has all the functionality of the full version but stops working after the expiry date.
Object Creation
The code:
Set Image = Server.CreateObject("csImageFile.Manage")
- creates an instance of the object called "Image" in an ASP script.In the trial version, use:
Set Image = Server.CreateObject("csImageFileTrial.Manage")
Visit the Chestysoft web site for details of how to buy the full version - www.chestysoft.com
Input / Output
Methods for Input / Output
Readfile Path - This loads an image into memory from disk where Path must be the full physical path and filename of the image. The file extension must match the file format.
Example:
Image.ReadFile "C:\images\something.jpg"
WriteFile Path - This saves the current image to disk. Path must be the full path and filename of the new file. The extension must be "jpg", "bmp", "png", "pcx", "psd", "gif", "tif" or "wbmp", and this will determine the format of the file. It can be a different format to the file that was read in. If it is a JPG file, the current value of JpegQuality will be used when saving the file. If it is a GIF or PNG file, the values of Transparent and BGColor will be used to set colour transparency.
The OverwriteMode property determines whether the new file overwrites an existing file with the same name, or is renamed. The actual name used when the file was saved is stored in the FileName property. Both properties are described later under properties. To summarise, OverwriteMode is 0 (default) to allow files to be saved when the name already exists, 1 to prevent files from being saved if the name exists and 2 to rename with a numbered suffix if the name exists.
ReadStream ImgType, FileData - This reads an image into memory from binary data. This may be from the csASPUpload component, another instance of csImageFile, a VBScript variable or a database. The image type, ImgType, must be specified as a string value be "jpg", "gif", "bmp", "png", "pcx", "psd", "tif" or "wbmp". This can include the period character of the extension, so ".jpg" and "jpg" are both valid. FileData is a variant array containing the file information as binary data.
To read a file directly from csASPUpload:
Image.ReadStream "jpg", UploadObj.FileData(0)
This will read in a JPG file assuming it has been uploaded using the csASPUpload object called UploadObj, and it is the first file in the array (or the only file).
To read data from a database field, the data must first be passed to a VBScript variable:
FileData = RSet("Image")
Image.ReadStream "jpg", FileData
This would read in a JPG file from a binary data field in a database, assuming the field name is "Image" and a recordset called "RSet" has been opened. The VBScript variable must be used to convert the data into the correct format. Avoid using a session variable, as this would stay in memory for some time after the page had finished processing.
ReadData ImgType, FileData - This method is now obsolete. Use ReadStream.
ReadURL Url - This loads an image into memory from a remote web server where Url is the location of the image. The file extension will be used to determine the file type. If this is not a graphic file type, the Content-Type will be used to determine the file type. A username and password can be sent with the request by setting the following properties before calling ReadURL. This information is sent as plain text for Basic Authentication. It is not suitable if the server is using Integrated Windows Authentication.
URLUserName - String. Username to be passed with ReadURL.
URLPassword - String. Password to be passed with ReadURL.
DPMtoDPI(dpm) - This function converts a dots per metre value to dots per inch.
DPItoDPM(dpi) - This function converts a dots per inch value to dots per metre.
Properties for Input / Output
JpegQuality - Integer value between 1 and 100, default value is 90. It determines the amount of JPEG compression used when a file is saved in that format. A high value is a high quality, large file size.
BGColor - 6 character hexadecimal RGB value of the background colour. Default value is white ("ffffff"). BGColor is used in conjunction with the Transparent property to set transparency for GIF or PNG output and when foreground transparency is required in the merge functions. It is also used to determine the background colour when rotations are performed that are not multiples of 90 degrees.
Transparent - Boolean value. When true any output GIF or PNG will have the colour specified by BGColor set as the transparent colour. It is also used to permit foreground transparency in merge functions. Reading a PNG file that has a colour with full transparency will set BGColor and Transparent.
FileSize - Read only. This is the size of the image in memory as it was when it was originally loaded from disk or from a data stream.
NewFileSize(Type) - Read only. This is the file size that will be produced if the current image is saved in the format specified by Type. Type must be the string value "jpg", "bmp", "png", "pcx", "psd", "gif", "tif" or "wbmp".
JPGData - The image as binary data, in JPG format. Use it to write to a binary data field in a database. It is also used to stream an image to a web browser using the Response.BinaryWrite method. Streaming an image to the browser is described later in these instructions.
Example:
RSet("Image") = Image.JPGData
This would write the data to the database field "Image", assuming a recordset called "RSet" had been opened.
BMPData - The image as binary data, in bitmap format.
GIFData - The image as binary data, in GIF format. If the UseLZW property is false the GIF will be uncompressed.
PNGData - The image as binary data, in PNG format. Note that only one colour may be set as transparent. The transparent colour will be defined by BGColor if the Transparent property is true.
WBMPData - The image as binary data, in wireless bitmap format.
PCXData - The image as binary data, in PCX format.
PSDData - The image as binary data, in PSD format.
TIFData - The image as binary data, in TIF format.
ColorDepth - The number of bits per pixel for the current image. It is an integer value and will be 1, 4, 8 or 24. The default value for a new image is 24. Setting ColorDepth to 8 or 4 can convert a 24 bit image into a paletted image.
Width - The width of the image in memory, in pixels.
Height - Height in pixels of the image in memory. This value changes as the image is processed. It is read only, resize the image using the Resize or Scale methods.
Width - The width of the image in memory, in pixels.
Note that Height and Width will both be zero if no image is currently in memory.
BMPHandle - Integer. The Windows handle of the image stored in memory. This is intended for use by other COM tools such as Visual Basic to input or output an image. Reading this property actually returns the handle of a copy of the image so modifications done using the handle do not affect the image in memory. In ASP it is the most efficient way to pass images between instances of the component.
Example:
Image.BMPHandle = Image1.BMPHandle
PalHandle - Integer. The Windows handle of the palette of the image stored in memory. This can be used along with BMPHandle to gain access to image data. Not all images require a palette.
DPI - Integer. The pixel density of the image in dots per inch. When read from an image the X value is used. When writing an image DPI is used to set both X and Y pixel density. Note that PNG, GIF and WBMP images do not use this property.
OverwriteMode - Integer value 0, 1 or 2. Used with the WriteFile method to decide what to do with duplicate file names. The default is 0 and this causes files to be saved with the name specified in WriteFile, even if a file by that name already exists. 1 will prevent WriteFile from saving a file if the file name exists. 2 will cause the file to be renamed with ~n added at the end of the name where n is the lowest available number. A typical use of OverwriteMode is to set it to 2 when reading in files from an upload component to prevent deletion of duplicate file names.
OverwriteChr - String. If OverwriteMode is set to 2 and a numbered suffix is added to the file name the value of OverwriteChr is used to separate the file name and the suffix number. The default is '~' but this can prevent the file from being downloaded on Windows 2003 or if URLScan is being used.
FileName - String, read only. After saving a file with WriteFile the full path and name actually used to save the file is stored in this property. It is sometimes needed when OverwriteMode is used with a value of 1 or 2.
UseLZW - Boolean. When false support for compressed GIFs is disabled meaning that GIFs cannot be read and exported GIFs are uncompressed. Default is true.
CompressionType - Integer value 0, 1 or 2. The compression method used when saving a TIF image. The default is 0 for no compression. 1 is Packbits compression and 2 is Group 4 which canonly be used with black and white images. This property is set when a TIF is loaded.
ProgressiveJpeg - Boolean. If true a JPG will be saved using progressive compression instead of baseline. This property is set when a JPG is loaded. Default is false. Note that Internet Explorer does not display a progressive JPG until the entire file is loaded, which is the opposite of what the name suggests.
WasCMYK - Boolean, read only. Set to true if a JPG, TIF or PSD was read in CMYK format. It indicates that the image has been converted to RGB.
Version - The version of the csImageFile.dll file. In the trial version this will also return the expiry date.
Image Manipulation
Methods for Image Manipulation
Scale Factor - The image in memory will be scaled by Factor percent. Factor must be an integer.
Example:
Image.Scale 50
Note that there is no equals sign and no brackets in VBScript.
Resize Xnew, Ynew - The image in memory will be resized, the new width and height are given by Xnew and Ynew. If either value is zero, the other will be used and the aspect ratio will be maintained.
Example:
Image.Resize 100, 0
This resizes the image to become 100 pixels wide. The aspect ratio will be unchanged, so the height will change proportionally. Note that there is no equals sign or brackets.
If the Resample property is true, a smoothing function will be applied during resizing and scaling. This produces an image with smoother edges at the expense of some processing speed. The smoothing function used is determined by the value of the FilterType property - an integer between 1 and 6.
Crop X1, Y1, X2, Y2 - The parts of the image outside the rectangle defined by (X1, Y1) and (X2, Y2) will be removed. Note that coordinates measure across and down from the top left of the image.
Rotate Angle - This rotates the image in memory by Angle degrees, anticlockwise. This may be a real number. If the angle is not a right angle, the resulting image will be centred on a larger rectangle the colour of which will be determined by the BGColor property. If Resample is true the image will be smoothed during rotation (24 bit images only). The rotate method can be demanding on server processing power.
FlipX - Performs a reflection about an axis parallel to the X-axis running through the centre of the image.
FlipY - Performs a reflection about an axis parallel to the Y-axis running through the centre of the image.
NewScale Factor - This is identical to the Scale method introduced for Visual Basic users to avoid a clash of names.
NewImage Width, Height, Color - This loads a plain, coloured rectangular image into memory, dimensions Width x Height. Color is a six character string representing the hexadecimal "rrggbb" value.
Brightness Value - This adjusts the brightness of the image. Value must be between 0 and 100 where 0 is very dark, 100 is very bright and 50 is unchanged.
Contrast Value - This adjusts the contrast of the image. Value must be between 0 and 100 where 0 is zero contrast, 100 is maximum contrast and 50 is unchanged.
Sharpen - This applies a sharpening filter to the image.
SharpenBy Value - Applies a sharpening filter but by a varying amount. Value is between 1 and 16 where 1 is more sharpening and 8 is the same as the Sharpen method.
Blur - This applies a blurring filter to the image.
BlurBy Value - Applies a blurring filter but by a varying amount. Value is between 1 and 32 where 1 is more blurring and 16 is the same as the Blur method.
GreyScale - This converts the image to a 256 colour greyscale image
ConvertToBW - This converts the image to a 1-bit black and white image.
ColorAdjust Value, Red, Green, Blue - This adjusts the brightness of one or more of the primary colours. Value must be between 0 and 100 where 0 reduces brightness, 100 increases and 50 is unchanged. Red, Green and Blue are Boolean values. If all three are true it is identical to the Brightness method. When used after a GreyScale command it produces an image that is viewed through a coloured filter.
OLEColorToStr(Color) - This function takes a 4 byte OLE_COLOR value, Color, and returns a 6 character string of the form "RRGGBB".
StrToOLEColor(ColorStr) - This function takes a 6 character colour string and returns a 4 byte OLE_COLOR value.
Properties for Image Manipulation
TransPercent - Float value. Used in the Merge functions this specifies the percentage transparency of the foreground image. By setting this to a high value a watermark can be produced. Default value is zero.
Tile - Boolean value. Used in the Merge functions. When true the foreground image is tiled to fill the background and the coordinates are ignored. Default value is false.
Resample - Boolean. Determines whether the image is resampled during a resize, scale or rotate operation. False by default.
FilterType - Integer value 1 to 6. Determines the filter used when the image is resampled during a resize or scale operation (but not for rotations which use a different filter). Filters are 1 - Bilinear, 2 - Hermite, 3 - Bell, 4 - B-Spline, 5 - Lanczos, 6 - Mitchell. Default value is 1.
The Merge Functions
There are 4 methods available for combining the current image with a second image. MergeFront and MergeBack take the second image from a file on the server. MergeFrontBin and MergeBackBin take the second image as a binary data stream which can come from another instance of the component or from a database. The "Front" methods make the current image the foreground and the "Back" methods make the current image the background. The foreground image can be partially transparent by giving the TransPercent property a value bigger than zero. TransPercent is a percentage, taking a value between 0 and 100, 0 is fully opaque, 100 is fully transparent (invisible). A single colour in the foreground can be fully transparent by setting the Transparent property to true and setting BGColor to the required "rrggbb" value.
The foreground image can be made to tile over the background by setting the Tile property to true. This ignores the X and Y coordinates and completely covers the background image. It would normally be used with some transparency settings, perhaps to create a watermark.
If the foreground image is 24 bit and the background image uses a palette the result will only contain the colours of the palette. This can be prevented by using the MergeBack function and using ColorDepth to change the paletted image to 24 bit before merging.
MergeFront Background, X, Y - Background is the full path and filename for another image. The image in memory is placed onto this background image. The top left corner is X and Y pixels across and down from the top left of the background image.
MergeBack Foreground, X, Y - Foreground is the full path and filename for another image. This foreground image is placed onto the image in memory. The top left corner is X and Y pixels across and down from the top left of the memory image.
MergeFrontBin BackgroundData, ImgType, X, Y - This is the same as the MergeFront method except it reads the background image from binary data. BackgroundData is a varaint array containing another image (see also ReadStream). The image in memory is placed onto this background image. The top left corner is X and Y pixels across and down from the top left of the background image. ImgType is "jpg", "gif", "bmp", "png", "psd", "pcx","tif" or "wbmp" to indicate the format of image data.
Example 1:
FileData = RSet("Image")
Image.MergeFrontBin FileData, "jpg", 25, 50
This places the image in memory onto another JPG image, read from a database field. The top left corner of the image from memory will be at coordinates 25, 50 on the background image.
Example 2:
Image.MergeFrontBin Image1.JPGData, "jpg", 25, 50
This places the image in memory onto another JPG image, stored in a second instance of csImageFile called Image1. The top left corner of the image from memory will be at coordinates 25, 50 on the background image.
MergeBackBin ForegroundData, ImgType, X, Y - This is the same as the MergeBack method except it reads the background image from binary data. ForegroundData is a varaint array containing another image (see also ReadStream). This image is placed on top of the image in memory. The top left corner is X and Y pixels across and down from the top left of the background image. ImgType is "jpg", "gif", "bmp", "png", "psd", "pcx", "tif" or "wbmp" to indicate the format of image data.
Image Editing
Methods for Image Editing
Arc X1, Y1, X2, Y2, X3, Y3, X4, Y4 - Draws an elliptically curved line the colour of PenColor. The arc follows the perimeter of the ellipse bounded by (X1, Y1) and (X2, Y2), and moves anticlockwise from the start point to the end point. The start point is defined by the intersection of the ellipse with a line drawn from the centre to the point (X3, Y3). The end point is defined by the intersection of the ellipse with a line drawn from the centre to the point (X4, Y4).
Chord X1, Y1, X2, Y2, X3, Y3, X4, Y4 - Draws a shape bounded by an arc and a line that joins the endpoints of the arc. The arc is an elliptically curved line that follows the perimeter of the ellipse bounded by (X1, Y1) and (X2, Y2), and moves anticlockwise from the start point to the end point. The start point is defined by the intersection of the ellipse with a line drawn from the centre to the point (X3, Y3). The end point is defined by the intersection of the ellipse with a line drawn from the centre to the point (X4, Y4). The shape is filled using the pattern defined by BrushStyle and the colour defined by BrushColor.
Ellipse X1, Y1, X2, Y2 - Draws a circle or ellipse that fits into the rectangle defined by the top left corner (X1, Y1) and the bottom right corner (X2, Y2). The shape is filled using the pattern defined by BrushStyle and the colour defined by BrushColor.
Pie X1, Y1, X2, Y2, X3, Y3, X4, Y4 - Draws a pie shaped wedge defined by an arc of an ellipse and lines joining the ends of the arc with the centre of the ellipse. The arc follows the perimeter of the ellipse bounded by (X1, Y1) and (X2, Y2), and moves anticlockwise from the start point to the end point. The start point is defined by the intersection of the ellipse with a line drawn from the centre to the point (X3, Y3). The end point is defined by the intersection of the ellipse with a line drawn from the centre to the point (X4, Y4). The shape is filled using the pattern defined by BrushStyle and the colour defined by BrushColor.
Rectangle X1, Y1, X2, Y2 - Draws a rectangle defined by the top left corner (X1, Y1) and the bottom right corner (X2, Y2). The shape is filled using the pattern defined by BrushStyle and the colour defined by BrushColor.
RoundRect X1, Y1, X2, Y2, X3, Y3 - Draws a rectangle defined by the top left corner (X1, Y1) and the bottom right corner (X2, Y2). The corners will be rounded with a curve matching an ellipse with width X3 and height Y3. The shape is filled using the pattern defined by BrushStyle and the colour defined by BrushColor.
Line X1, Y1, X2, Y2 - Draws a draws a line from point (X1, Y1) up to but not including the point (X2, Y2). The style, colour and width of the line are determined by the properties PenStyle, PenColor and PenThickness.
DrawLine X1, Y1, X2, Y2 - Alternative name for the Line method for Visual Basic users.
FloodFill X, Y - Fills an area on the current image with BrushColor spreading outward from the point (X, Y) until a different colour is reached. All the pixels filled will have the same original colour as the pixel at (X, Y).
FillToBorder X, Y, Color - Fills an area on the current image with BrushColor spreading outward from the point (X, Y) until a boundary of Color is reached. Color must be a 6 character string representing the hexadecimal "rrggbb" value.
AddPoint X, Y - Add a point to use as a vertex by the Polygon method.
Polygon - Draws a polygon using the points added by AddPoint as vertices. The shape is filled using the pattern defined by BrushStyle and the colour defined by BrushColor. The points stored by AddPoint are cleared after the polygon is drawn.
SetBitmapBrush Path - Makes the bitmap file with physical path Path into the pattern to be used for filled shapes. It must be in bitmap format. This will override the BrushStyle setting.
SetBitmapBrushHandle Handle - Sets a bitmap to be the pattern used for filling shapes. The bitmap is defined by its Windows handle, Handle, which is an integer value. This could be used with the BMPHandle property to get the pattern from another instance of csImageFile.
ClearBitmapBrush - This removes any bitmap that was used as a fill pattern and reverts back to using BrushStyle and BrushColor.
Example:
Image.SetBitmapBrush "c:\images\pattern.bmp"
Image.Rectangle 10, 10, 50, 50
This will draw a rectangle and fill it with the image pattern.bmp. If this is smaller than the rectangle it will be tiled.
Note that using a bitmap as the fill pattern will not work adequately for full colour pattern images unless the server is running in a full colour mode.
Properties for Image Editing
Pixel(X, Y) - Six character string representing the hexadecimal "rrggbb" value. Read or write an individual pixel on the current image.
Example:
Image.Pixel(10, 10) = "000000"
This will make the pixel at (10, 10) black.
PenColor - Six character string representing the hexadecimal "rrggbb" value. This is the colour used for drawing lines and outlines of shapes.
PenThickness - Integer. The width in pixels for lines and outlines of shapes. Must be non-zero. Line widths are only shown greater than 1 for solid line styles.
PenStyle - Enumeration. Values 0 to 5. PenStyle determines the pattern used to draw a line or shape outline. Use Clear (PenStyle = 5) when the outline is not required on filled shapes.
|
0 |
Solid |
3 |
DashDot |
|
1 |
Dash |
4 |
DashDotDot |
|
2 |
Dot |
5 |
Clear |
BrushColor - Six character string representing the hexadecimal "rrggbb" value. This is the colour used for filling shapes when the BrushStyle is not Clear.
BrushStyle - Enumeration. Values 0 to 7. BrushStyle determines the pattern used when filling shapes. The fill pattern is the same colour as PenColor. Use Clear (BrushStyle = 1) when no fill is required.
|
0 |
Solid |
4 |
Cross |
|
1 |
Clear |
5 |
DiagCross |
|
2 |
BDiagonal |
6 |
Horizontal |
|
3 |
FDiagonal |
7 |
Vertical |
Antialias - Boolean. When 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. Default value for Antialias is false.
Adding Text to an Image
Text can be placed on the image using the method:
Text X, Y, TextString - where X and Y are the coordinates of the top left corner of the rectangle containing the text, measured from the top left corner of the image. TextString is the text as a widestring. Text will start on the next line if a carriage return, line feed or CRLF pair is inserted. New in version 4.1 - this command supports Unicode characters subject to an appropriate font being used.
There are a number of properties controlling the appearance of text, listed below. If the Antialias property (described earlier) is set to true the text will be drawn antialiased to give it a smoother appearance.
TextFont - String value for the name of the font face. The default value is the system font of the server. This default will be used if a value for TextFont is specified but the font face is unavailable.
TextColor - 6 digit Hex RGB value for the text colour. This is a string of the form "RRGGBB". Example, "FF0000" is red. Default value is black.
TextSize - Height of the text in pixels. Default value is 18.
TextBG - 6 digit Hex RGB value for the text background. Default value is white.
TextOpaque - Boolean value. If true the text background is the colour of TextBG, if false the text background is transparent. Default is true.
TextBold, TextItalic, TextUnderline, TextStrikeout - Boolean values to set text styles. All default to false.
TextAngle - This is the angle of rotation of the text, in degrees. It must be an integer. The default is zero. Only true type fonts can be drawn rotated.
Note that the text properties require an equals sign to assign a value to them but Text is a method:
Image.TextSize = 20
Image.TextBold = true
Image.Text 100, 50, "Some Text"
TextHeight(Text) - This returns the height in pixels taken up by the text "Text".
TextWidth(Text) - This returns the width in pixels taken up by the text "Text".
TextJustify - Integer value 0, 1 or 2. If the text contains carriage returns this property determines the justification. 0 = Left, 1 = Centre, 2 = Right. Default is 0 (Left).
FontNames - Collection. This returns a list of the names of all the fonts installed on the server in alphabetical order. It can be accessed using For..Each. FontNames.Count returns the total number of fonts available, and FontNames.Item(X) returns the name of the font at position X in the list.
Example:
For Each Font in Image.FontNames
Response.Write Font & "<br>"
Next
This will list all the fonts installed on the server.
TextWrap - Boolean value. Set to true if text must continue over multiple lines. The line of text will break at a space between characters. Wrapped text will always be left justified and cannot be antialiased. For multi-line text that must be justified or antialiased use the Text method with carriage return characters. Defaults to false.
TextRectX - When TextWrap is true TextRectX is the length of the rectangle containing text, in pixels. If zero, text will extend to the right edge of the image before wrapping to the next line. Default is zero.
TextRectY - When TextWrap is true TextRectY is the width of the rectangle containing text, in pixels. If zero, text will fill as many lines as required up to the height of the image. Default is zero.
File Info (JPEG Meta Data)
The JPEG file format allows for text describing the image to be embedded in the file header. This is used in a number of applications including journalism (IPTC text). If a JPEG is loaded that contains File Info readable by csImageFile the property HasFileInfo is set to true and the relevant properties are set. To save a JPEG with file info the relevant data properties must be set. The HasFileInfo property will be set to true when any of the properties are written to. File Info can be read from or written to a separate file, either the older .FFO format or the newer XML based .XMP format. PSD files also support File Info. The file info properties do not work with TIF files.
File Info Properties
HasFileInfo - Boolean. When an image is loaded that contains File Info this property is set to true. It also determines whether File Info is exported with a JPEG. Setting any File Info property sets HasFileInfo to true. False by default.
FFO_Caption - String.
FFO_CaptionWriter - String.
FFO_Headline - String.
FFO_Specialinstructions - String.
FFO_Category - String.
FFO_Byline - String.
FFO_BylineTitle - String.
FFO_Credit - String.
FFO_Source - String.
FFO_ObjectName - String.
FFO_City - String.
FFO_ProvinceState - String.
FFO_CountryName - String.
FFO_OTR - String. (Original Transmission Reference)
FFO_CopyrightNotice - String.
FFO_ImageURL - String.
FFO_Urgency - Integer. Not saved/empty if set to 0.
FFO_DateCreated - Date.
FFO_CopyrightFlag - Boolean.
The following properties are aliases of properties used above. They reflect the fact that Adobe Photoshop 7 uses different property names from previous versions.
FFO_Title - String. Alias of FFO_ObjectName.
FFO_Author - String. Alias of FFO_Byline.
FFO_AuthorsPosition - String. Alias of FFO_BylineTitle.
Setting one property value also sets the corresponding alias property value, so FFO_Title will always have the same value as FFO_ObjectName.
The following property extends the copyright status to work with Adobe Photoshop 7 where 3 copyright states are possible, "Copyrighted Work", "Public Domain" and "Unmarked".
FFO_Marked - Boolean. Defaults to true.
"Copyrighted Work" corresponds to FFO_CopyrightFlag = true and FFO_Marked = true.
"Public Domain" corresponds to FFO_Marked = false and either value for FFO_CopyrightFlag.
"Unmarked" corresponds to FFO_CopyrightFlag = false and FFO_Marked = true.
In .xmp files these values are interpreted slightly differently:
"Copyrighted Work" corresponds to FFO_CopyrightFlag = true and either value for FFO_Marked.
"Public Domain" corresponds to FFO_Marked = false and FFO_CopyrightFlag = false.
"Unmarked" corresponds to FFO_CopyrightFlag = false and FFO_Marked = true.
The Keywords and Supplemental Categories properties are zero based arrays of strings. Some additional properties and methods are needed to read and write them.
FFO_Keywords (Index) - String. The keyword defined by the integer Index.
FFO_KeywordsCount - Integer, read only. The number of items in the list.
FFO_KeywordsAdd (Keyword) - Adds the string Keyword to the end of the list.
Returns the new number of items in the list as an integer.
FFO_KeywordsDelete(Index) - Deletes the keyword defined by the integer Index.
FFO_KeywordsClear - Deletes all the keywords.
FFO_KeywordsInsert(Index, Keyword) - Inserts the string Keyword
at position Index in the list. Index is an integer.
FFO_SuppCat (Index) - String. The category defined by the integer Index.
FFO_ SuppCatCount - Integer, read only. The number of items in the list.
FFO_ SuppCatAdd (Cat) - Adds the string Cat to the end of the list.
Returns the new number of items in the list as an integer.
FFO_ SuppCatDelete(Index) - Deletes the category defined by the integer Index.
FFO_ SuppCatClear - Deletes all the categories.
FFO_SuppCatInsert(Index, Cat) - Inserts the string Cat at position
Index in the list. Index is an integer.
File Info Methods
FFO_Clear - Deletes all File Info values and sets HasFileInfo to false.
FFO_Save FileName - Writes the File Info data to a file (.FFO file). FileName
is the physical path and file name, complete with extension. The format used is determined by the extension, either .FFO or .XMP.
FFO_Load FileName - Loads File Info data from a file. FileName is the
physical path and file name, complete with extension. The file must be either FFO or XMP format.
OverwriteMetaData FileName - This writes the File Info and Exif data of the current image to the JPG file specified by FileName. It leaves the image data of FileName unchanged and should be used if only the File Info data of a JPG is to be edited. Repeated loading and saving of a JPG image should be avoided as the image can be altered when it is recompressed.
Example:
Image.ReadFile "c:\directory\image.jpg"
Image.FFO_Caption = "New Caption"
Image.OverwriteMetaData "c:\directory\image.jpg"
This will change the Caption property of the image and modify it on disk without changing the image data.
Exif Attributes
Exif attributes can be stored in JPG files and are written by many digital cameras and some software packages and they contain information about the image and the camera settings and conditions when the image was created. csImageFile makes this data available on a read only basis and will preserve this data when a JPG is saved, unless it is specifically cleared. The data consists of a zero based array of name and value pairs in string format. When reading this data it may be necessary to refer to the Exif specification to interpret it correctly.
Exif Properties and Methods
ExifValueByIndex(Index) - Returns the value of the Exif attribute as a string given the index within the array. Index is an integer.
ExifValueByName(Name) - Returns the value of the Exif attribute as a string given the name of the attribute. Name is a string.
ExifName(Index) - Returns the name of the Exif attribute as a string given the index of the attribute. Index is an integer.
ExifCount - The number of Exif attributes as an integer.
ExifClear - Method to clear all the attributes. After calling ExifClear any JPG image saved will have no Exif attributes.
Example:
Set Image = Server.CreateObject("csImageFileTrial.Manage")
Image.ReadFile "c:\path\to\image.jpg"
For I = 0 to Image.ExifCount - 1
Response.Write Image.ExifName(I) & ": " & Image.ExifValueByIndex(I)
Response.Write "
"
Next
This will list all the attributes recorded in the image.
Exif Data Types
csImageFile is not intended as a full Exif editor but the ability to read this data has been added so it can be extracted or used programmatically. Some knowledge of the Exif attributes will probably be needed in order to extract information. The attributes that are stored in BYTE, SHORT or LONG format are returned as strings of their decimal values. Where there are multiple values they are shown as comma separated lists of decimal values. RATIONAL and SRATIONAL values are shown as a numerator, a forward slash and a denominator, e.g. 72/1. Comma separated lists are used where multiple values are used. UNDEFINED data types are returned as hexadecimal strings of their byte values. Where multiple values are used they are again shown as a comma separated list.
File Utilities
There are a number of file utility functions included for convenience. They are not intended to be a comprehensive set, because asp has the built in File System Object to cover most file utilities. These are the functions most likely to be useful while manipulating images.
FileExists(FileName) - Returns a Boolean value. FileName is the physical path and file name of the file in question.
CurrentDir - Returns the physical path of the directory containing the script. It is complete with the trailing backslash character.
ParentDir(Directory)- Directory is a string value and must be a full directory path. The return value is the parent directory.
Example:
Response.Write Image.ParentDir(Image.CurrentDir)
This would display the parent directory to the one containing the current script.
DirName - String. This is the directory that will be listed in the FileList collection. It is a full physical path and can include a filter in the file name:
Image.DirName = "C:\images\"
This will assign all the files in the "images" directory to the FileList collection.
Image.DirName = "C:\images\*.jpg"
This will assign all the files in the "images" directory with a .jpg extension to the FileList collection.
FileList - Collection of strings. When a directory is assigned to the DirName property this collection will be populated by a list of the files in that directory. As a Collection it can be accessed by index or in a For .. Each loop and it has a count property.
Example:
Image.DirName = "C:\images\*.jpg"
For Each JPG in Image.FileList
Response.Write JPG & "<br>"
Next
This would display all the .jpg files in the specified directory.
Delete(FileName) - This deletes the file FileName. Note that it is permanently deleted, NOT placed in the Recycle Bin.
Copy OldName, NewName - This copies the file OldName to the location and name given by NewName. Again, full paths are required.
Rename OldName, NewName - This renames the file OldName to NewName. Full paths are required, and so renaming to a different directory is the equivalent of moving the file.
GetFileName(Path) - This returns the file name, complete with extension but without the directory structure where Path is a full physical path to a file.
GetExtension(Path) - This returns the extension, complete with the period character where Path is a full physical path to a file.
AppendToFile FileName, NewLine - This appends the string NewLine to the text file FileName. If the text file does not exist, it will be created if possible. The full server path is required.
Example:
Image.AppendToFile Image.CurrentDir & "test.txt, "Hello"
This will append the line "Hello" at the end of a text file called test.txt which is in the same directory as the current script. If the file does not exist it will create it.
AppendToFile is the only command in this component for manipulating text files. It is useful for maintaining a simple log or to assist with testing. There is a full set of commands for dealing with text files in the built in File System Object component.
All the file handling routines require that the Internet Guest Account has the appropriate permissions on the server, otherwise errors will result.
Streaming an Image to the Browser
An active server page will return html output by default. An html page is formatted text which can include spaces to display images. The images themselves are not part of the html, they are separate files, the location of which is specified inside the IMG tag. An asp page can be an image, if the ContentType is set to "image/gif" or "image/jpeg", and the binary data of the image is output using the Response.BinaryWrite command. The asp generated image is displayed by placing the path to the asp "image" inside the IMG tag.
For example, this page will display the image produced by "resize.asp":
<html>
<head><title>HTML page containing an image</title></head>
<body>
<img src=resize.asp>
</body>
</html>
Resize.asp may look like this:
<%@ language=vbscript %>
<%
Response.Expires = 0
Response.Buffer = true
Response.Clear
Set Image = Server.CreateObject("csImageFile.Manage")
Image.ReadFile "c:\images\bigimage.jpg"
Image.Scale 25
Response.ContentType = "Image/Jpeg"
Response.BinaryWrite Image.JPGData
Response.End
%>
When the first html page is loaded it looks for the image at "resize.asp", runs the script and is sent a stream of binary data in jpg format, so the browser displays the image. It is not possible to place the BinaryWrite command inside the IMG tag to produce the image, it must be in a separate file.
If the line setting the ContentType is missing it should still display in Internet Explorer but not in Netscape. It is important to specify the correct ContentType to maintain compatibility between web browsers.
It is useful to know that parameters can be passed to the asp image script in the url string.
Example:
<img src=image.asp?NewSize=150>
Language Specific Issues
csImageFile is compatible with other COM enabled languages although it was originally intended for use with ASP. Here is some information that should be useful if csImageFile is to be used with Cold Fusion or Visual Basic.
Cold Fusion
A COM object can only be used with Cold Fusion when it is running on a Windows platform. The object is created with the <cfobject> tag:
<cfobject action="create" name="Image" class="csImageFile.Manage">
Each command must be placed inside a
<cfset Image.ReadFile("c:\images\bigimage.jpg")>
<cfset Image.Resample=true>
<cfset Image.Scale(20)>
<cfset Image.WriteFile("c:\images\smallimage.jpg")>
Cold Fusion cannot stream an image directly to the browser, so any dynamically produced image must be saved to a temporary file first and then displayed using a <cfcontent> tag.
For more on using csImageFile with Cold Fusion visit www.chestysoft.com/imagefile/cf.htm.
Visual Basic
For best results import the csImageFile type library into VB by selecting "Project" from the menu bar, then "References". The dialogue box will then show available type libraries. Scroll down to "csImageFile Library", check the box and click OK. This will add the "manage" class from csImageFile to the Object Browser making it available for early binding.
To create an instance of the object called "Image" use the following:
Dim Image As manage
Set Image = CreateObject("csImageFile.Manage")
Displaying an image from csImageFile in a VB picture box is not simple as it involves an API call to create a bitmap. There is a description of this and some sample code at: www.chestysoft.com/imagefile/vbimage.asp.
Revision History
The current version of csImageFile is 4.2
New in Version 1.1:
Text output.
New in Version 1.2:
Uncompressed GIF output.
Foreground transparency introduced to the merge functions.
The NewImage method added.
The ReadStream method now reads in database fields making the ReadData method obsolete.
File utilities included for copying, renaming and deleting files and for obtaining the physical path on the server.
New in Version 2.0:
Support for file types PNG, PCX and WBMP added.
ReadURL method added to allow loading of images from a remote server.
Methods added for drawing lines and shapes and accessing individual pixels.
FloodFill, FillToBorder, FlipX and FlipY methods added.
TextWrap, TextRectX and TextRectY properties added to allow text to be written onto multiple lines.
FontNames collection gives access to a list of fonts available on the server.
ColorDepth property gives greater control over colour depth of saved images.
BMPHandle and PalHandle properties give direct access to the internal image data for use with other COM tools
such as Visual Basic.
New in Version 2.1:
Brightness and Contrast functions added.
Optional resampling added to resize and scale.
Pixel density (DPI) is now recorded and can be modified.
Partial transparency (watermarking) and tiling added to merge functions.
New in Version 3.0:
File Info properties added (JPEG metadata).
Sharpen and Blur functions added.
GreyScale method added.
ColorAdjust method added.
Colour depth can be reduced to produce a paletted image.
OverwriteMode added to control renaming uploaded files.
New in version 4.0
Support for PSD and TIF files added.
Support for compressed GIF files added.
File Info properties now include support for .XMP file format.
EXIF attributes can now be read from JPG files.
FileList collection added.
ReadURL can now identify files from the MIME type.
Basic Authentication password and username added to ReadURL method.
ConvertToBW method added.
New in version 4.1
TIF support extended to include LZW and Group 4 compression.
JPG and TIF images using CMYK colour space can be read.
OLE_COLOR conversion functions added.
Polygon method added.
SharpenBy and BlurBy methods added.
ProgressiveJpeg property added.
Use of a bitmap as the fill pattern included.
Unicode support added to Text method.
New in version 4.2
Antialias property for text and drawing functions.
TextJustify property.
Carriage returns can be used with the Text method.
OverwriteChr property.
WasCMYK property.
TIF support extended to include Group 3 compression.
Other Components From Chestysoft
Visit the Chestysoft web site for details of other asp components.
ASP Components
csASPUpload - Process file uploads through a browser. Ideal for use with csImageFile.
csFileDownload - Control file downloads with an ASP script.
csDrawGraph - COM object to draw pie charts, bar charts and line graphs.
csWAPDraw - Create and edit wireless bitmaps for WAP devices.
csIniFile - Use Windows style inifiles in your ASP applications.
csASPZipFile - Create zip files and control downloads.
OCX Controls
csXGraph - An OCX control to draw pie charts, bar charts and line graphs.
csXImage - An OCX control to display and manipulate images.
Chestysoft, January 2004.
www.chestysoft.com