GpImage2

Visual FoxPro class to access Gdi+, for earlier versions starting from VFP6


GpImage2 is a wrapper class that allows you to access all the main Gdi+ functions. Works great with all VFP versions, although it is not recommneded for VFP9 users, since we have available the GdiPlusX project, taht is a much complete project.
With GPIMAGE, drawing becomes super easy, and lots of other functionalities are available for VFP developers.

GDI+ Image class is a VFP class to load, save and transform BMP, JPEG, GIF, PNG and TIFF images. It provides also conversion to/from Picture object, copying to/retrieving from clipboard, capturing of screen or any window.

New Methods included let you draw rectangles, lines, ellipsis, pies, strings and pictures on images. Brings the possibility to control alignment, size, orientation, rotation, of any shape, text or picture.

Description:
This class is based on GDI+ and requires gdiplus.dll which is freely available and can be installed on Win98 and higher. If you have not installed WinXP or .NET runtime then you can download this DLL fromhttp://www.microsoft.com/downloads/details.aspx?FamilyID=6a63ab9c-df12-4d41-933c-be590feaa05a&DisplayLang=en
or directly:
http://download.microsoft.com/download/platformsdk/redist/3097/W98NT42KMeXP/EN-US/gdiplus_dnld.exe

You can find some good information about GdiPlus on Microsoft official site:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdicpp/GDIPlus/GDIPlusreference/flatgraphics.asp

And also great explanations and examples about GDI+ at
http://www.bobpowell.net/

gpImage.prg file contains three classes. gpInit class declares required API functions and initializes GDI+. The single instance of this class must be created before use of gpImage or graphics classes and must exist all the time when GDI+ is used. Properties and methods of gpImage and Graphics classes are described below.



Properties:
ImageFormatformat of image: "BMP", "JPEG", "TIFF" etc. (read only)
PixelFormatpixel format of image, for example "24bppRGB" (read/write)
ImageWidthwidth of image (read only)
ImageHeightheight of image (read only)
HorizontalResolutionhorizontal resolution in dpi (read/write)
VerticalResolutionvertical resolution in dpi (read/write)

Methods:
Create(tnWidth, tnHeight, tcPixelFormat)Creates an empty image object
tcPixelFormat is optional; if omitted, default is 32bppARGB NEW
Load(tcFileName)Loads an image from file
FromResource(tcFileName, tcBitmapName)Loads an image from bitmap resource in EXE/DLL file. Resource can be identified by name: img.FromResource("dxdiag.exe", "DIRECTX"), or by number: img.FromResource("shell32.dll", "#309").
FromPicture(toPicture)Creates an image object from Picture object
GetPicture()Returns Picture object
FromClipboard()Creates an image object from clipboard content
ToClipboard()Copies an image to clipboard
Thumbnail(tnWidth, tnHeight)Creates thumbnail of specified size
SaveAsBMP(tcFileName)Stores image in BMP file
SaveAsJPEG(tcFileName, tnQuality, tnTransform)Stores image in JPEG file.
Optional parameter tnQuality specifies quality of JPEG compression, 0 - highest compression, 100 - highest quality, default value - 75.
Optional parameter tnTransform specifies type of transformation without loss of information, any of EncoderValueTransform values.
SaveAsGIF(tcFileName)Stores image in GIF file
SaveAsTIFF(tcFileName, tnCompress, tnColorDepth)Stores image in TIFF file.
Parameter tnCompress specifies type of compression, any of EncoderValueCompression values, optional.
Parameter tnColorDepth specifies number of colors in bits per pixel (1,4,8,16,24,32,48,64), optional.
SaveAsPNG(tcFileName)Stores image in PNG file
SaveAsMultipageTIFF(tcFileName, tnCompress, tnColorDepth)Stores image as first page of multipage TIFF file
SaveAddPage(tnImage)Adds specified image as page of multipage file. Parameter tnImage is a value, returned by GetImage() function of another image object.
GetImage()Returns pointer to GDI+ image object which can be used in API functions and SaveAddPage() function.
GetPixelColor(x, y)Returns color value of pixel
GetPixelAlpha(x, y)Returns alpha value of pixel
SetPixel(x, y, tnColor, tnAlpha)Sets color and alpha values of pixel
Crop(x, y, tnWidth, tnHeight)Crops an image
RotateFlip(rotateFlipType)Rotates and flips an image
Resize(tnWidth, tnHeight, tnInterpolationMode)Resizes an image
GetPageCount()Returns number of pages in multipage (TIFF) file
SelectPage(tnPage)Selects the specified page
GetFrameCount()Returns number of time frames in multiframe (GIF) file
SelectFrame(tnFrame)Selects the specified time frame
Capture(thWnd)Captures the window, specified by handle or desktop, if handle is not specified


Now we introduced a new class that is responsible for drawing on the image selected / created - Graphics, that contains some new functions. Take care that to use this functions, you MUST first call GpInit and GpImage.

gdip = CreateObject("gpInit")
img  = CreateObject("gpImage")
oGr  = CreateObject("Graphics",img.getimage()) && to work with Image Context
   or
oGr  = CreateObject(“Graphics”,Thisform.Hwnd,”HWND”) && to work directly on the desired form NEW

see example file TESTDRAW.PRG





Properties:
StringMeasureDetermines if measurement of string is always needed; StringW, StringH, StringChars and StringLines will always be updated after drawing any string. DEFAULT = .T.
StringWString Width of last string (read only)
StringHString Height of last string (read only)
StringCharsString Characters fitted in string (read only)
StringLinesString Lines filled in string (read only)
SmoothingModeSpecifies rendering quality, with possible values indicated by GDIPLUS_SmoothingMode_* constants
InterpolationModeSpecifies the interpolation mode associated with this graphics object

  Methods:

CreateFromImage(tnImageHandle)Creates Graphics from Image Handle NEW
CreateFromHWND(tnFormHWND)Creates Graphics from Form’s HWND NEW
SetPen(tnColor, tnWidth, tnUnit)Sets the pen to be used by “DrawRect”, “DrawLine”; tnWidth (1) and tnUnit (0)are optional NEW
More great information about PEN at http://www.bobpowell.net/pensone.htm
DrawLine(x1, y1, x2, y2)Draws a Line between two points x1y1 and x2y2, based on “SetPen”
DrawRect(x, y, tnWidth, tnHeight)Draws a rectangle based on “SetPen”
DrawEllipse(x, y, tnWidth, tnHeight)Draws an ellipse based on “SetPen”
DrawPie(x, y, tnWidth, tnHeight, nStart, nSweep)Draws a pie slice based on “SetPen”
nStart = starting point to start draw
nSweep = Size in angles of the slice (0-360) NEW
DrawArc(x, y, tnWidth, tnHeight, nStart, nSweep)Draws an arc, using same parameters of “DrawPie”; Portion of circle within the rectangle defined by the angles NEW
DrawPolygon(taPoints)Draws a polygon based on “SetBrush”
taPoins = 2-D array with integer positions
    column1 = X ; column 2 = Y
also connects first and last points to close the figure drawn.  NEW
SetBrush(tnColor, tnAlpha)Sets the Brush to be used by “FillRect” and “DrawString”
Sets color and alpha values of pixel
Alpha ranges from 0 (transparent) to 255 (opaque) NEW
More great information on BRUSHES at http://www.bobpowell.net/brushesone.htm
SetHatchBrush(tnHatchStyle, tnBackCol, tnBackAlpha, tnForeCol, tnForeAlpha)Creates a HatchBrush object based on a hatch style, a foreground color, and a background color
tnHatchStyle is numeric constant. See codes in Gpimage.h NEW
SetTextureBrush(tcFileName, tnWrapMode)Creates a TextureBrush object based on an image and a wrap mode. The size of the brush defaults to the size of the image, so the entire image is used by the brush. tnWrapMode is numeric constant. See codes in Gpimage.h NEW
SetGradientBrush(tnX, tnY, tnWidth, tnHeight, tnColor1, tnColor2, tnGradientMode)Creates a LinearGradientBrush object based on a rectangle, two colors, and a gradient mode. NEW
FillRect(x, y, tnWidth, tnHeight)Draws and Fills a rectangle based on “SetBrush”
FillEllipse(x, y, tnWidth, tnHeight)Draws and Fills an ellipse based on “SetBrush”
FillPie(x, y, tnWidth, tnHeight, nStart, nSweep)Draws and Fills a pie slice based on “SetPen”
nStart = starting point to start draw
nSweep = Size in angles of the slice (0-360) NEW
FillPolygon(taPoints)Draws and Fills a polygon based on “SetBrush”
taPoins = 2-D array with integer positions
    column1 = X ; column 2 = Y  NEW
SetRect(x, y, tnWidth, tnHeight)Sets a rectangle in which “DrawString” will draw the text
TranslateTransform(tnX, tnY)Translates by (x,y) the graphics object NEW
RotateTransform(tnAngle)Sets the rotaion by the specified angle, based on the matrix created by “TranslateTransform” NEW
ResetTransformResets the transform matrix NEW
SetAlignment(thAlignment, tvAlignment, tFlags)Sets the horizontal, vertical and flags for the “DrawString” alignment. The three parameters are numeric constants. See codes in Gpimage.h NEW
DrawString(tcText, tcFontName, tnFontSize, tcFontStyle, tlMeasureString)Draws a String on the image, based to “SetBrush”, “SetAlignment” and “SetRect”. tcFontStyle is character
“B” – Bold
“I” – Italic
“U” – Undeline
“S” – Superscript
tlMeasureString is optional; .T. sends string measures to properties StringW, StringH, StringChars and StringLines NEW
More great information on DRAWING STRINGS at  http://www.bobpowell.net/begintext.htm
MeasureString(tcText, tcFontName, tnFontSize, tcFontStyle)Same parameters as “DrawString” – updates properties StringW, StringH, StringChars and StringLines NEW
DrawImage(tcImageFile, x, y, tnWidth, tnHeight)Draws a picture on the image
tcImageFile can be either the file name or handle of another loaded image in another instance of gpimage (see examples) NEW
tnWidth and tnHeight are optional
More great information on DRAWING IMAGES at http://www.bobpowell.net/imagesone.htm
DrawImageScaled(tcImageFile, x, y, tnWidth, tnHeight)Draws a picture on the image Scaled to the size of the virtual rectangle
DrawImageRectRect(tcFileName, dstx, dsty, dstwidth, dstheight, srcx, srcy, srcwidth, srcheight)Draws the specified portion of the specified Image object at the specified location and with the specified Size. This method will draw the image using the IMAGEATTRIBUTES predefined in REMAPTABLE and SETCOLORMATRIX (see below) NEW
RemapTable(tnOldColor, tnNewColor, tnOldAlpha, tnNewAlpha)Converts the colors in an image according to a color remap table. Makes possible to change some desired colors. This command creates an ImageAttributes. To apply the changes, draw the Remapped Image using DRAWIMAGERECTRECT NEW
See example file REMAPPINGCOLORS.PRG
SetColorMatrix(taColMatrix)The ColorMatrix structure contains a 5x5 matrix of real numbers. Using this matrix it is possible to make adjustments in image colors.
See example file MATRIX.PRG
Check also in MSDN article “Using a Color Matrix to Transform a Single Color” NEW
More great information about COLOR MATRICES at http://www.bobpowell.net/negativeimage.htm
ChangeColors(tnRed, tnGreen, tnBlue, tnAlpha)This is the easiest way to convert colors.
tnRed, tnGreen, thBlue and tnAlpha represent the percentage of a single color you need to add / decrease in the image. Ranges from -100 to +100
All 4 parameter are needed

It has also 2 predefined color matrices
To use them, sen only one parameter
1 for Black and White convesion
2 for negative conversion

Soon I will be adding some new matrices that deal with brightness and contrast. NEW

To better understand this method you should run example file TESTGPIMAGE.SCX and CHANGECOLORS.PRG
GetGraphicsGets the graphics handle


Now you can also work with IMAGEATTRIBUTES, changing or creating new ColorMatrix’es, RemappingTables of colors. With this feature, you can transform any image to Bçack and White, negative, adjust brightness / contrast, increase or decrease Red, Green, Blue or Alpha Color Attributes very easily. With no more than 5 lines of code you can produce the effects below:

APPLYING COLORMATRICES see example file MATRIX.PRG, CHANGECOLORS.PRG, CHANGECOLORS2.PRG

ORIGINAL
B&W
NEGATIVE
RED – 20%
GREEN – 20%
BLUE – 20%
RED + 20%
GREEN + 20%
BLUE + 20%


REMAPPING TABLE OF COLORS see example file REMAPPINGCOLORS.PRG


It is possible to change one or some specific colors in an image according to a color remap table. In this case, we changed the red from the 1st image to Blue; Then Yellow became Black.

DRAWING IMAGES AND TEXT WITH TRANSPARENCY see example file TRANSPARENT.PRG


USING TEXTURE AND HATCH-STYLE BRUSHES see example file BRUSHES.PRG



GRADIENT BRUSHES see example file BRUSHESGRADIENT.PRG , GRADIENTFORM2.SCX








































gpImage.h file contains definitions of ImageFormat, PixelFormat, EncoderValueTransform, rotateFlipType, InterpolationMode, Wrap mode for brushes, HatchBrush styles, Pen Dash style, Pen Units, StringAlignment enumeration, StringFormatFlags enumeration and FontType constants.


Other useful Functions Included

GetRed(tnColor)Returns “RED” component of a color NEW
GetGreen(tnColor)
Returns “GREEN” component of a color NEW
GetBlue(tnColor)Returns “BLUE” component of a color NEW
PointF(x, y)Returns String with float Coordinates NEW
RectF(x, y, w, h)
Returns String with float Rectangle NEW
  
In The examples folder you can also find a very simple but useful class named GPPIE.PRG, that produced the example below. Try it running OBJPIE.PRG in the same folder.



GPPIE allows many customizations, such as changing all colors, defining backgrounds, legends and styles. It can also produce B&W graphics, as shown below. You can choose to show the created graphics in a form or saving it as an image file, that can be shown in a report, or wherever you imagine.



Another useful class included is GDIPSTRING.PRG. You can use it to “draw” strings on reports, on the vertical and upside-down ! Running under VFP7 and above.
Below you can see an image saved from a REPORT PREVIEW under VFP7. Really easy to use.
Run and Preview TESTE.FRX in the examples folder to see how it works




License:
This class is free; use it on your own risk. If you use this source code in a product, acknowledgment is not required but would be appreciated. You are not authorized to distribute or sell the class unless specific permission is given by the author.

Author:
Alexander Golovlev
Saratov,
Russian Federation
May 10, 2003

Added functions by
Cesar Ch
vfpimaging@hotmail.com
May 2, 2005
Notes by Cesar Ch: I added the functions from the graphics class. These just do the easy job, once all the initialization, structures, handles were already available by the original class by Alexander Golovlev.

Don’t miss to visit http://www.bobpowell.net/
He gifted us with lots and lots of great and complete information about using GDI+ in our applications. Although his work is directed to VB and .NET users, it’s very easy to apply most things in Visual Foxpro. The names of the Functions and Properties are very similar. For sure you’ll get many good ideas.

After downloading the file, Unzip and run TESTDRAW.PRG and TESTGPIMAGE.SCX for good examples using the new features of the class.
FOR MORE CODE SAMPLES, VISIT THE FAQS PAGE !

No comments:

Post a Comment