Sign in Join
Wiki copytemporary

fcl-image: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: fcl-image

OldNewLine
1+## Introduction
2+
3+FCL-Image started life as "fpimage", pretty much as an attempt to implement a generally portable TImage like class, without the deep win32 and VCL ties.
4+
5+## Current file list
6+
7+The central units are *[[doc:fcl/fpimage|fpimage]]* and *[[doc:fcl/fpcanvas|fpcanvas]]* and these are further enhanced by OOP derivation.
8+
9+- **bmpcomn** A few structures and constants for the BMP fileformat
10+- **clipping** Some utility routines that help with clipping and intersecting of rects.
11+- **ellipses** Drawing of ellipses and arcs, and filling ellipses and pies.
12+ - TEllipseInfo
13+- **extinterpolation** interpolation filters for TFPCanvas.StretchDraw (
14+ - TBlackmanInterpolation
15+ - TBlackmanSincInterpolation
16+ - TBlackmanBesselInterpolation
17+ - TGaussianInterpolation
18+ - TBoxInterpolation
19+ - THermiteInterpolation
20+ - TLanczosInterpolation
21+ - TQuadraticInterpolation
22+ - TCubicInterpolation
23+ - TCatromInterpolation
24+ - TBilineairInterpolation
25+ - THanningInterpolation
26+ - THammingInterpolation
27+- **fpcanvas** Generic Canvas classes.
28+ - [[doc:fcl/fpcanvas/tfpcanvasexception.html|TFPCanvasException]]
29+ - TFPPenException
30+ - TFPBrushException
31+ - TFPFontException
32+ - TFPCustomCanvas
33+ - TFPCanvasHelper
34+ - TFPCustomFont
35+ - TFPCustomFontClass
36+ - TFPCustomPen
37+ - TFPCustomPenClass
38+ - TFPCustomBrush
39+ - TFPCustomBrushClass
40+ - TFPCustomInterpolation
41+ - TFPBaseInterpolation
42+ - [[doc:fcl/fpcanvas/tmitchelinterpolation.html|TMitchelInterpolation]]
43+ - TFPCustomCanvas
44+ - TFPCustomDrawFont
45+ - TFPEmptyFont
46+ - TFPCustomDrawPen
47+ - TFPEmptyPen
48+ - TFPCustomDrawBrush
49+ - TFPEmptyBrush
50+- **fpcolhash** an implementation of a color hash table.
51+ - TFPColorHashException
52+ - TFPColorHashTable
53+- **fpditherer** contains classes used to dither images.
54+ - FPDithererException
55+ - TFPBaseDitherer
56+ - TFPFloydSteinbergDitherer
57+- **fpimage** fpImage base definitions and classes
58+ - TFPCustomImageReader
59+ - TFPCustomImageWriter
60+ - TFPCustomImage
61+ - FPImageException
62+ - TFPPalette
63+ - TFPCustomImage
64+ - TFPMemoryImage
65+ - TFPCustomImageHandler
66+ - TFPCustomImageReader
67+ - TFPCustomImageWriter
68+ - TIHData
69+ - TImageHandlersManager
70+- **fpimgcanv** Image Canvas - canvas which draws on an image.
71+ - TFPImageCanvas
72+- **fpimgcmn** Image Common: small procedural Helpers (swap,crc)
73+- **fppixlcanv**
74+ - TPixelCanvas
75+- **fpquantizer** classes used to quantize images. See [1](http://lazarus.freepascal.org/index.php/topic,13468.0)
76+- **freetype** Encapsulating classes over freetype
77+- **freetypeh** Freetype header translation
78+- **ftfont** More freetype related font classes
79+- **pcxcomn** PCX fileformat records and types
80+- **pixtools** Pixel drawing routines.
81+- **pngcomn** PNG fileformat records and types
82+- **polygonfilltools** Routines for filling polygons (FPC 3.3.1 or newer)
83+- **pscanvas** TPostScriptCanvas implementation.
84+- **targacmn** Targa fileformat records and types
85+
86+**Readers and writers for various image formats** reside in dedicated units:
87+
88+- **fpreadbmp**, **fpwritebmp**: Reader and writer units for .bmp files
89+- **fpreadjpeg**, **fpwritejpeg**: Reader and writer units for .jpeg/.jpg files
90+- **fpreadpcx**, **fprwritepcs**: Reader and writer units for .pcx files
91+- **fpreadpng**, **fpwritepng**: Reader and writer units for .png files
92+- **fpreadpnm**, **fpwritepnm**: Reader and writer units for .pnm files
93+- **fpreadtga**, **fpwritetga**: Reader and writer units for .tga files
94+- **fpreadtiff**, **fpwritetiff**: Reader and writer units for .tiff/.tif files
95+- **fpreadxpm**, **fpwritexpm**: Reader and writer units for .xpm files
96+
97+**INC files uses in fpcanvas**
98+
99+- fpbrush
100+- fpcanvas
101+- fpcdrawh
102+- fpfont
103+- fphelper
104+- fpinterpolation
105+- fppen
106+
107+INC files uses in fpmake
108+
109+- fpcolors
110+- fpimage
111+- fphandler
112+- fpcolcnv
113+- fppalette
114+
115+Demos
116+
117+- drawing
118+- imgconv
119+
120+## Known Issues and limitations
121+
122+- fcl-image is written for maximal portability and maintainability and is quite slow. The main storage type is 16-bit RGBA, storing always 64-bit per pixel, and a function is called to get each pixel.
123+- pngwriter doesn't implement automatic detection of filters, and thus is always "filter none"
124+- most writers don't autodetect what format to save. You must correctly set the relevant writer options ( see also [bug 17621](http://bugs.freepascal.org/view.php?id=17621)).
125+- the color format can be counter intuitive, read [this thread](http://www.mail-archive.com/fpc-devel@lists.freepascal.org/msg16506.html)
126+- png only implements basic chunk types (idat,trns,plte,ihdr and iend). It e.g. can't handle chunks like pHYs,iCCP,gAMA,cHRM yet. ([bug 19209](http://bugs.freepascal.org/view.php?id=19209)).
127+
128+## Image formats
129+
130+Here is a table with the correct class to use for each image format, as well as comparing to the LCL.
131+
132+| Format | fcl-image reader unit | fcl-image writer unit | LCL class |
133+|----|----|----|----|
134+| Windows Bitmap. A very simple format, usually used without compression and without transparency, but it may also have them, although many applications don't support those extra features. (*.bmp) | fpreadbmp | fpwritebmp | TBitmap |
135+| A popular format for websites. It supports up to 8 bits per pixels, which are 256 distinct colors chosen from the 24-bit RGB color space. This limitation makes it unsuitable for complex images, but useful for simple graphics. The image is compressed without loss in quality and the format also supports animations. (*.gif) | fpreadgif\|\|- | TGIFImage | |
136+| The most popular format for websites, and an ISO standard since 1994. The format compressed the image but generates a small loss of quality. (*.jpeg, *.jpg) | fpreadjpeg | fpwritejpeg | TJpegImage |
137+| A format widely used in DOS applications, but now less popular. (*.pcx) | fpreadpcx | fpwritepcx\|\|- | |
138+| Portable Network Graphics. A popular format for it's efficient compression without quality loss. (*.png) | fpreadpng | fpwritepng | TPortableNetworkGraphic |
139+| \|Supports the formats Portable BitMaps (*.pbm), Portable GrayMaps (*.pgm) and Portable PixMaps (*.ppm) | fpreadpnm | fpwritepnm | TPortableAnyMapGraphic |
140+| The default file format for Adobe Photoshop® (*.psd) | fpreadpsd\|\|-\|\|- | | |
141+| Called either Truevision TGA File Format or TARGA File Format, this is a compressed format commonly used in games. (*.tga, *.tpic) | fpreadtga | fpwritetga\|\|- | |
142+| Tagged Image File Format (TIFF), originally created to have a common image format for scanners. (*.tiff, *.tif). Controlled by Adobe® | fpreadtiff | fpwritetiff | TTiffImage |
143+| X PixMap, an image format used by the X Window System which stores the data in ASCII text. Is also used as an icon format in UNIX applications. (*.xpm) | fpreadxpm | fpwritexpm | TPixmap |
144+| X Window Dump file format. Used by the program xwd which generates screenshots in the X Window System. (*.xwd) | fpreadxwd\|\|-\|\|- | | |
145+| Windows Icon. Is a list of small bitmaps in various color depths and sizes, with transparency support and no compression. (*.ico)\|\|-\|\|- | TIcon | | |
146+| Windows Cursor. Exactly the same format as the Windows Icon, but with an extra field in the header for the cursor hotspot. (*.cur)\|\|-\|\|- | TCursorImage | | |
147+| macOS icon. List of small images in various sizes. (*.icns)\|\|-\|\|- | TIcnsIcon | | |
148+
149+### Tiff
150+
151+Working features of the reader:
152+
153+- Black and white/lineart/1 bit (FPC trunk only, not in FPC 2.6.x)
154+- Grayscale 8,16bit (optional alpha),
155+- RGB 8,16bit (optional alpha),
156+- Orientation, except for rotated orientation
157+- compression: packbits, LZW, deflate
158+- endian
159+- multiple images/multipage
160+- strips and tiles
161+- Sets properties in the image Extras properties, which is used by the writer, so that reading/writing keeps many common tags like Artist, Copyright, DateAndTime, HostComputer, ImageDescription, Maker, Model, Software, DocumentName, XResolution, YResolution, Orientation, bit depts, page name, isThumbnail.
162+
163+Here is an incomplete list of open / not yet implemented features of the reader:
164+
165+- Compression: jpeg, CCITT Group 3, CCITT Group 4
166+- PlanarConfiguration 2
167+- ColorMap
168+- separate mask
169+- fillorder - not needed by baseline tiff reader
170+- bigtiff 64bit offsets
171+- XMP tag 700
172+- ICC profile tag 34675
173+- Orientation with rotation
174+
175+Working features of the writer:
176+
177+- Grayscale 8,16bit (optional alpha)
178+- RGB 8,16bit (optional alpha)
179+- Orientation except rotated
180+- multiple images, pages
181+- thumbnail
182+- Compression: deflate
183+
184+Here is an incomplete list of open / not yet implemented features of the writer:
185+
186+- Compression: LZW, packbits, jpeg, CCIT Group 3,CCIT Group 4,...
187+- Planar
188+- ColorMap
189+- separate mask
190+- fillorder - not needed by baseline tiff reader
191+- bigtiff 64bit offsets
192+- endian - currently using system endianess
193+- Orientation with rotation
194+
195+## Walk-through
196+
197+### Basic Canvas Setup
198+
199+You'll need a few things to start up. A canvas, image, and writer. The writer is to write images like PNG. The sample below will give you a 100x100 black png.
200+
201+``` Pascal
202+{$mode objfpc}{$h+}
203+program demo;
204+
205+uses classes, sysutils,
206+ FPImage, FPCanvas, FPImgCanv,
207+ FPWritePNG;
208+
209+var canvas : TFPCustomCanvas;
210+ image : TFPCustomImage;
211+ writer : TFPCustomImageWriter;
212+begin
213+ { Create an image 100x100 pixels}
214+ image := TFPMemoryImage.Create (100,100);
215+
216+ { Attach the image to the canvas }
217+ Canvas := TFPImageCanvas.Create (image);
218+
219+ { Create the writer }
220+ Writer := TFPWriterPNG.Create;
221+
222+ { Save to file }
223+ image.SaveToFile ('DrawTest.png', writer);
224+
225+ { Clean up! }
226+ Canvas.Free;
227+ image.Free;
228+ writer.Free;
229+end.
230+```
231+
232+### Drawing a Circle
233+
234+Drawing a circle requires a bit more then just giving a width. You'll need to setup the pen style, mode, width, and color to do this. FCL-Image comes with a few pen modes and styles, it will really be up to you to decide which you'll need. Its best for now to try with a few modes and styles to get a better understanding of what FCL-Image can do.
235+
236+``` Pascal
237+{$mode objfpc}{$h+}
238+program demo;
239+
240+uses classes, sysutils,
241+ FPImage, FPCanvas, FPImgCanv,
242+ FPWritePNG;
243+
244+var canvas : TFPcustomCanvas;
245+ image : TFPCustomImage;
246+ writer : TFPCustomImageWriter;
247+ {
248+ Colors range from 0 to 65535 in each primary color.
249+ They can also show as hexadecimal:
250+ $FFFF = 65535, $0000 = 0
251+ }
252+ passionRed: TFPColor = (Red: 65535; Green: 0; Blue: 0; Alpha: 65535);
253+begin
254+ image := TFPMemoryImage.Create (100,100);
255+ Canvas := TFPImageCanvas.Create (image);
256+ Writer := TFPWriterPNG.Create;
257+
258+ { Set the pen styles }
259+ with canvas do
260+ begin
261+ pen.mode := pmCopy;
262+ pen.style := psSolid;
263+ pen.width := 1;
264+ pen.FPColor := passionRed;
265+ end;
266+
267+ { Draw a circle }
268+ canvas.Ellipse (10,10, 90,90);
269+
270+ { Save to file }
271+ image.SaveToFile ('DrawTest.png', writer);
272+
273+ { Clean up! }
274+ Canvas.Free;
275+ image.Free;
276+ writer.Free;
277+end.
278+```
279+
280+### Drawing Alpha-Blended Shapes
281+
282+Alpha-blending means: When something is painted over an existing image the old pixels are allowed to shine through the new drawing. The amount of mixing is given by the `Alpha` value of the new color which is specified as fourth word parameter of the brush's FPColor. `Alpha=0` means: the new painting is fully transparent, `Alpha=$FFFF` means: the new drawing is fully opaque.
283+
284+In order to activate alpha-blending the `DrawingMode` of the canvas must be switched to `dmAlphaBlend`, and the brush color of a new shape must be extended by its `Alpha` value.
285+
286+``` pascal
287+program alphablend;
288+uses
289+ FPImage, FPImgCanv, FPCanvas, FPWritePNG;
290+var
291+ img: TFPMemoryImage;
292+ canvas: TFPImageCanvas;
293+begin
294+ img := TFPMemoryImage.Create(200, 200);
295+ canvas := TFPImageCanvas.Create(img);
296+ try
297+ canvas.DrawingMode := dmAlphaBlend; // This activates the alpha-blend mode
298+
299+ // Background
300+ canvas.Pen.Style := psClear;
301+ canvas.Brush.FPColor := colWhite;
302+ canvas.FillRect(0, 0, img.Width, img.Height);
303+
304+ // Yellow opaque rectangle
305+ canvas.Brush.FPColor := FPColor($FFFF, $FFFF, 0);
306+ canvas.Rectangle(10, 10, 190, 100);
307+
308+ // Overlapping semi-transparent red circle
309+ canvas.Brush.FPColor := FPColor($FFFF, 0, 0, $4000);
310+ canvas.Ellipse(60, 60, 140, 140);
311+
312+ // Overlapping semi-transparent blue circle
313+ canvas.Brush.FPColor := FPColor(0, 0, $FFFF, $8000);
314+ canvas.Ellipse(0, 100, 100, 200);
315+
316+ // Save to image file
317+ img.SaveToFile('alphablend.png');
318+ finally
319+ canvas.Free;
320+ img.Free;
321+ end;
322+end.
323+```
324+
325+### Brush Styles
326+
327+The **brush** defines how a closed area will be filled. There are several predefined styles to determine the fill pattern.
328+
329+- `bsSolid` - fills the area with uniform color
330+- `bsClear` - no fill
331+- `bsHorizontal` - draws horizontal lines of width 1 across the shape to be filled
332+- `bsVertical` - vertical lines
333+- `bsFDiagonal` - diagonal lines (45°, \\\\\\)
334+- `bsBDiagonal` - diagonal lines (45°, ///)
335+- `bsCross` - crossed vertical and horizontal lines (+)
336+- `bsDiagCross` - crossed diagonal lines (x)
337+
338+The fill color is given by the `FPColor` property of the `Brush`. The space between the lines of the non-solid patterns is not painted, i.e. is left transparent. If the canvas on which the brush is used descends from `TFPPixelCanvas` (e.g. `TFPImageCanvas` in unit *fpimgcanv*, or `TLazCanvas` in the LazUtils unit *lazcanvas*) the distance between the pattern lines can be adjusted by means of the `Canvas.HashWidth` property (Note that this does not apply to the `TCanvas` introduced by the Lazarus LCL.)
339+
340+Furthermore there are two additional possibilities for user-defined patterns:
341+
342+- `bsImage` - tiles the area to be filled with copies of the image provided by the `Brush.Image` which must be a `TFPCustomImage` descendant, e.g. `TFPMemoryImage`. The colors of the image are retained, and its alpha channel is supported. By default the image position refers to the image origin, but if the canvas descends from `TFPPixelCanvas` (e.g. `TFPImageCanvas` in unit *fpimgcanv*, or `TLazCanvas` in the LazUtils unit *lazcanvas*), it can be changed to be relative to the top/left shape bounding box by setting the property `Canvas.RelativeBrushImage` to `true`. Again this does not apply to the LCL `TCanvas` of Lazarus.
343+- `bsPattern` - provides a user-defined pattern in the `Brush.Pattern` property of type `TBrushPattern`. This is a 32-element array of 32-bit integers where every set bit is interpreted as a painted pixel using the `Brush.FPColor`; cleared bits are not painted and thus are transparent.
344+
345+**Example**
346+
347+The following mini project fills a rectangle by a user-defined blue checkerboard pattern, and saves the image as a transparent png file: ![](/wiki-images/e/e5/Checkerboard_rectangle.png)
348+
349+``` pascal
350+program FillTest;
351+uses
352+ FPImage, FPCanvas, FPPixlCanv, FPImgCanv, FPWritePNG;
353+const
354+ BRUSH_PATTERN: TBrushPattern = (
355+ $FF00FF00, $FF00FF00, $FF00FF00, $FF00FF00,
356+ $FF00FF00, $FF00FF00, $FF00FF00, $FF00FF00,
357+ $00FF00FF, $00FF00FF, $00FF00FF, $00FF00FF,
358+ $00FF00FF, $00FF00FF, $00FF00FF, $00FF00FF,
359+ $FF00FF00, $FF00FF00, $FF00FF00, $FF00FF00,
360+ $FF00FF00, $FF00FF00, $FF00FF00, $FF00FF00,
361+ $00FF00FF, $00FF00FF, $00FF00FF, $00FF00FF,
362+ $00FF00FF, $00FF00FF, $00FF00FF, $00FF00FF
363+ );
364+var
365+ image: TFPMemoryImage;
366+ canvas: TFPImageCanvas;
367+ writer: TFPCustomImageWriter;
368+begin
369+ image := TFPMemoryImage.Create(100, 100);
370+ try
371+ canvas := TFPImageCanvas.Create(image);
372+ try
373+ // Prepare the brush for the shape interior
374+ canvas.Brush.Style := bsPattern;
375+ canvas.Brush.FPColor := colBlue;
376+ canvas.Brush.Pattern := BRUSH_PATTERN;
377+
378+ // Prepare the pen for the shape border
379+ canvas.Pen.Style := psSolid;
380+ canvas.Pen.Width := 3;
381+ canvas.Pen.FPColor := colDkBlue;
382+
383+ // Fill shape
384+ canvas.Rectangle(10, 10, 90, 90);
385+
386+ // Save to file
387+ writer := TFPWriterPNG.Create;
388+ try
389+ // Activate alpha channel in saved image
390+ TFPWriterPNG(writer).UseAlpha := true;
391+ image.SaveToFile('rectangle.png', writer);
392+ finally
393+ writer.Free;
394+ end;
395+
396+ finally
397+ canvas.Free;
398+ end;
399+
400+ finally
401+ image.Free;
402+ end;
403+end.
404+```
405+
406+### Pen Modes
407+
408+The pen mode is how the pixel drawn will react to the pixels beneath it. So if its a white pixel and you draw a red pixel over it with the mode of pmXor then you'll get a vibrate blue pixel.
409+
410+- `pmBlack`
411+- `pmWhite`
412+- `pmNop`
413+- `pmNot`
414+- `pmCopy`
415+- `pmNotCopy`
416+- `pmMergePenNot`
417+- `pmMaskPenNot`
418+- `pmMergeNotPen`
419+- `pmMaskNotPen`
420+- `pmMerge`
421+- `pmNotMerge`
422+- `pmMask`
423+- `pmNotMask`
424+- `pmXor`
425+- `pmNotXor`
426+
427+### Pen Styles
428+
429+- `psSolid`
430+- `psDash`
431+- `psDot`
432+- `psDashDot`
433+- `psDashDotDot`
434+- `psinsideFrame`
435+- `psPattern`
436+- `psClear`
437+
438+### Drawing modes
439+
440+- `dmOpaque` -- painting over an existing image overwrites the pixels previously written.
441+- `dmAlphaBlend` -- painting over an existing image blends the old and new colors in the ratio of their `Alpha` value.
442+- `dmCustom` -- similar to `dmAlphaBlend`, but a function must be provided which defines how old and new colors are combined (`TFPCanvasCombineColors = function(const color1, color2: TFPColor): TFPColor of object;`).
443+
444+The following code applies the `dmAlphaBlend` `DrawingMode` to draw two semi-transparent circles over an opaque rectangle:
445+
446+``` Pascal
447+program alphablend;
448+uses
449+ FPImage, FPImgCanv, FPCanvas, FPWritePNG;
450+var
451+ img: TFPMemoryImage;
452+ canvas: TFPImageCanvas;
453+begin
454+ img := TFPMemoryImage.Create(200, 200);
455+ canvas := TFPImageCanvas.Create(img);
456+ try
457+ canvas.DrawingMode := dmAlphaBlend; // This activates the alpha-blend mode
458+
459+ // Background
460+ canvas.Pen.Style := psClear;
461+ canvas.Brush.FPColor := colWhite;
462+ canvas.FillRect(0, 0, img.Width, img.Height);
463+
464+ // Yellow opaque rectangle
465+ canvas.Brush.FPColor := FPColor($FFFF, $FFFF, 0);
466+ canvas.Rectangle(10, 10, 190, 100);
467+
468+ // Overlapping semi-transparent red circle
469+ canvas.Brush.FPColor := FPColor($FFFF, 0, 0, $4000);
470+ canvas.Ellipse(60, 60, 140, 140);
471+
472+ // Overlapping semi-transparent blue circle
473+ canvas.Brush.FPColor := FPColor(0, 0, $FFFF, $8000);
474+ canvas.Ellipse(0, 100, 100, 200);
475+
476+ img.SaveToFile('alphablend.png');
477+ finally
478+ canvas.Free;
479+ img.Free;
480+ end;
481+end.
482+```
483+
484+### Drawing text
485+
486+Here is an example, how to create a 200x100 image, painting a white background and some text and saving it as .png:
487+
488+``` Pascal
489+program fontdraw;
490+
491+{$mode objfpc}{$H+}
492+
493+uses
494+ Classes, SysUtils, FPimage, FPImgCanv, FTFont, FPWritePNG, FPCanvas;
495+
496+procedure TestFPImgFont;
497+var
498+ Img: TFPMemoryImage;
499+ Writer: TFPWriterPNG;
500+ ms: TMemoryStream;
501+ ImgCanvas: TFPImageCanvas;
502+ AFont: TFreeTypeFont;
503+begin
504+ Img:=nil;
505+ ImgCanvas:=nil;
506+ Writer:=nil;
507+ ms:=nil;
508+ AFont:=nil;
509+ try
510+ // initialize free type font manager
511+ FTFont.InitEngine;
512+ FontMgr.SearchPath:='/usr/share/fonts/truetype/ttf-dejavu/'; // not needed on Windows
513+ AFont:=TFreeTypeFont.Create;
514+
515+ // create an image of width 200, height 100
516+ Img:=TFPMemoryImage.Create(200,100);
517+ Img.UsePalette:=false;
518+ // create the canvas with the drawing operations
519+ ImgCanvas:=TFPImageCanvas.Create(Img);
520+
521+ // paint white background
522+ ImgCanvas.Brush.FPColor:=colWhite;
523+ ImgCanvas.Brush.Style:=bsSolid;
524+ ImgCanvas.Rectangle(0,0,Img.Width-1,Img.Height-1);
525+
526+ // paint text
527+ ImgCanvas.Font:=AFont;
528+ ImgCanvas.Font.Name:='DejaVuSans';
529+ ImgCanvas.Font.Size:=20;
530+ ImgCanvas.TextOut(10,30,'Test');
531+
532+ // write image as png to memory stream
533+ Writer:=TFPWriterPNG.create;
534+ ms:=TMemoryStream.Create;
535+ writer.ImageWrite(ms,Img);
536+ // write memory stream to file
537+ ms.Position:=0;
538+ ms.SaveToFile('testfont.png');
539+ finally
540+ AFont.Free;
541+ ms.Free;
542+ Writer.Free;
543+ ImgCanvas.Free;
544+ Img.Free;
545+ end;
546+end;
547+
548+begin
549+ TestFPImgFont;
550+end.
551+```
552+
553+### Reading an image file
554+
555+It is very easy to read image files with fcl-image, as the example below shows:
556+
557+``` Pascal
558+uses
559+ fpreadgif, fpimage;
560+
561+var
562+ image: TFPCustomImage;
563+ reader: TFPCustomImageReader;
564+begin
565+ Image := TFPMemoryImage.Create(10, 10);
566+ Reader := TFPReaderGIF.Create;
567+ Image.LoadFromFile(AFileName, Reader);
568+ // ...
569+```
570+
571+### Converting between two raster image formats
572+
573+To convert simply open in one format and save in the desired one, like in this example:
574+
575+``` Pascal
576+uses
577+ fpreadgif, fpimage, fpwritebmp;
578+
579+var
580+ image: TFPCustomImage;
581+ reader: TFPCustomImageReader;
582+ writer: TFPCustomImageWriter;
583+begin
584+ Image := TFPMemoryImage.Create(10, 10);
585+ Reader := TFPReaderGIF.Create;
586+ Writer := TFPWriterBMP.Create;
587+
588+ Image.LoadFromFile(AFileName, Reader);
589+ Image.SaveToFile(ADestFileName, Writer);
590+ //...
591+```
592+
593+### Rescaling a bitmap image
594+
595+In order to rescale a bitmap image to a new size we need an interpolation for calculating the intermediate new pixels. FCL-Image provides several interpolation classes; in all of them neighboring pixels are combined in some specific way to calculate the new pixel. The visual appearance of the result image depends on the type of the interpolation. Generally reducing the image size results in better image qualtity and magnification of the image size.
596+
597+In order to access an interpolation class we need a instance of TFPCustomCanvas. A convenient one is TFPImageCanvas which closely cooperates with a TFPCustomImage.
598+
599+``` Pascal
600+program project1;
601+uses
602+ FPImage, FPCanvas, FPImgCanv, FPReadJPEG, FPWriteJPEG;
603+const
604+ FILE_NAME = 'cheetah.jpg';
605+ MAX_SIZE = 512;
606+var
607+ srcImg, destImg: TFPMemoryImage;
608+ canvas: TFPImageCanvas;
609+ scaleFactor: Double;
610+begin
611+ // Create and load the source image
612+ srcImg := TFPMemoryImage.Create(0, 0);
613+ srcImg.LoadFromFile(FILE_NAME);
614+
615+ // Calculate the image scaling factor
616+ if srcImg.Width > srcImg.Height then
617+ scaleFactor := MAX_SIZE / srcImg.Width
618+ else
619+ scaleFactor := MAX_SIZE / srcImg.Height;
620+
621+ // Create the destination image in the requested size
622+ destimg := TFPMemoryImage.Create(round(srcImg.Width*scaleFactor), round(srcImg.Height*scaleFactor));
623+
624+ // Create a canvas for the destination image ...
625+ canvas := TFPImageCanvas.Create(destImg);
626+
627+ // ... and an interpolation
628+ canvas.Interpolation := TFPBaseInterpolation.Create;
629+
630+ // Use the interpolation to stretch the source image to the new size
631+ canvas.StretchDraw(0, 0, destImg.Width, destImg.Height, srcImg);
632+
633+ // Save destination image to file
634+ destImg.SaveToFile('resized.jpg');
635+
636+ // Clean up
637+ canvas.Interpolation.Free;
638+ canvas.Free;
639+ destImg.Free;
640+ srcImg.Free;
641+end.
642+```
643+
644+### Rotating a bitmap image by an arbitrary angle
645+
646+Using the `RotatePoint()` and `RotateRect()` functions in the Lazarus unit `GraphMath` it is rather easy to rotate the pixels in a bitmap by an arbitrary angle. `RotateRect()` is needed to calculate the size of the rotated image, and `RotatePoint` is used to calculate back to the unrotated pixel for each point in the rotated image.
647+
648+``` Pascal
649+uses
650+ Types, Math, FPImage, GraphMath;
651+
652+function CreateRotatedImage(AImage: TFPMemoryImage; Angle: Double): TFPMemoryImage; // Angle is in radians
653+var
654+ R: TRect;
655+ x, y: Integer;
656+ C, P: TPoint;
657+ delta: TPoint;
658+begin
659+ // Calculate bounds of the rotated image
660+ R := RotateRect(AImage.Width, AImage.Height, Angle);
661+ OffsetRect(R, -R.Left, -R.Top);
662+
663+ // Calculate center of rotated image
664+ C := Point((R.Left + R.Right) div 2, (R.Top + R.Bottom) div 2);
665+
666+ // Create the resulting image.
667+ Result := TFPMemoryImage.Create(R.Right - R.Left, R.Bottom - R.Top);
668+
669+ // Correction needed to center the rotated pixels
670+ delta := Point((AImage.Width - Result.Width) div 2, (AImage.Height - Result.Height) div 2);
671+
672+ // Iterate over all pixels in the result image and look up the corresponding
673+ // pixels in the unrotated image. Pixels in the rotated image which are outside
674+ // the unrotated image are set to be transparent.
675+ for y := 0 to Result.Height-1 do
676+ for x := 0 to Result.Width-1 do
677+ begin
678+ P := RotatePoint(Point(x, y) - C, -Angle) + C;
679+ P := P + delta;
680+ if (P.X >= 0) and (P.Y >= 0) and (P.X < AImage.Width) and (P.Y < AImage.Height) then
681+ Result.Colors[x, y] := AImage.Colors[P.X, P.Y]
682+ else
683+ Result.Colors[x, y] := colTransparent;
684+ end;
685+end;
686+```
687+
688+### Writing an 8-bit paletted bitmap file
689+
690+The following section is based on forum discussion <https://forum.lazarus.freepascal.org/index.php/topic,63215.msg478472.html#msg478472>.
691+
692+For creating a bmp file with a color palette set the `UsePalette` property of the `TFPCustomImage` to `true`. Add the FPColors of the palette entries to the image's `Palette` property. For painting on a canvas define colors by the FPColor values in the same way as with an unpaletted image; the palette index of the requested color is determined internally. When a color is not found in the existing palette, the color is added automatically. If this is not wanted you can also specify the colors by means of the palette index: `canvas.Brush.FPColor := image.Palette[1]`
693+
694+``` Pascal
695+program PaletteBMP;
696+
697+{$mode objfpc}{$H+}
698+
699+uses
700+ classes, fpcanvas, fpimage, fpimgcanv, fpwritebmp;
701+
702+var
703+ img: TFPMemoryImage;
704+ cnv: TFPImageCanvas;
705+ writer: TFPCustomimageWriter;
706+begin
707+ img := TFPMemoryImage.Create(100, 100);
708+ try
709+ img.UsePalette := true; // IMPORTANT!
710+ // colBlack is always available at index 0.
711+ img.Palette.Add(colYellow); // Index 1
712+ img.Palette.Add(colBlue); // Index 2
713+ img.Palette.Add(colGreen); // Index 3
714+
715+ cnv := TFPImageCanvas.Create(img);
716+ try
717+ cnv.Brush.FPColor := colYellow;
718+ cnv.Rectangle(10, 10, 45, 45);
719+
720+ cnv.Brush.FPColor := colBlue;
721+ cnv.Rectangle(55, 10, 90, 45);
722+
723+ cnv.Brush.FPColor := img.Palette[3];
724+ cnv.Rectangle(10, 55, 45, 90);
725+
726+ cnv.Brush.FPColor := colWhite; // not yet in palette
727+ cnv.Rectangle(55, 55, 90, 90);
728+ finally
729+ cnv.Free;
730+ end;
731+
732+ writer := TFPWriterBMP.Create;
733+ TFPWriterBMP(writer).BitsPerPixel := 8;
734+ try
735+ img.SaveToFile('test-8bpp.bmp', writer);
736+ finally
737+ writer.Free;
738+ end;
739+ finally
740+ img.Free;
741+ end;
742+end.
743+```
744+
745+### Color reduction
746+
747+When images are to be displayed on devices which support only a limited number of colors the number of distinct colors in the image must be reduced such that there is no significant loss in image quality. Two steps are involved in this process
748+
749+- color quantization: This creates a palette with a maximum allowed size and adds those colors that are a good approximation of all colors in the original image.
750+- dithering: The palette colors are distributed over the image so that the original image is best approximated.
751+
752+For this purpose, fcl-image contains the units fpquantizer and fpditherer. The following code is adapted from the forum post <https://forum.lazarus.freepascal.org/index.php/topic,13468.msg70495>. It reduces the input image to an image with the specified bits per pixels (4 bits per pixel --\> 16 colors, 8 bits per pixel --\> 256 colors):
753+
754+![](/wiki-images/6/60/Fcl-image_lenna_24bpp.png) ![](/wiki-images/b/ba/Fcl-image_lenna_8bpp.png)
755+
756+``` Pascal
757+uses
758+ fpimage, fpimgcanv, fpreadbmp, fpwritebmp, fpquantizer, fpditherer;
759+
760+procedure ReduceColors(SourceFile, TargetFile:String; BitsPerPixel: Integer);
761+var
762+ sourceImg, targetImg: TFPMemoryImage;
763+ reader: TFPReaderBMP;
764+ writer: TFPWriterBMP;
765+ quantizer: TFPMedianCutQuantizer = nil;
766+ palette: TFPPalette = nil;
767+ ditherer: TFPFloydSteinbergDitherer = nil;
768+begin
769+ if FileExists(SourceFile) then begin
770+ sourceImg := TFPMemoryImage.Create(0,0);
771+ targetImg := TFPMemoryImage.Create(0,0);
772+ reader := TFPReaderBMP.Create;
773+ writer := TFPWriterBMP.Create;
774+ try
775+ sourceImg.LoadFromFile(SourceFile);
776+ quantizer := TFPMedianCutQuantizer.Create;
777+ quantizer.ColorNumber := 1 shl BitsPerPixel;
778+ quantizer.Add(sourceImg);
779+ palette := quantizer.Quantize;
780+ ditherer := TFPFloydSteinbergDitherer.Create(palette);
781+ ditherer.Dither(sourceImg, targetImg);
782+ writer.BitsPerPixel := BitsPerPixel;
783+ targetImg.SaveToFile(TargetFile, writer);
784+ finally
785+ ditherer.Free;
786+ palette.Free;
787+ quantizer.Free;
788+ writer.Free;
789+ reader.Free;
790+ targetImg.Free;
791+ sourceImg.Free;
792+ end;
793+ end;
794+end;
795+```
796+
797+The same code can be used to reduce the colored input image to a dithered black-and-white image. Since here the palette consists of black and white only, the quantizer can be omitted: ![](/wiki-images/6/60/Fcl-image_lenna_24bpp.png) ![](/wiki-images/f/f9/Fcl-image_lenna_1bpp.png)
798+
799+``` Pascal
800+uses
801+ SysUtils,
802+ fpimage, fpimgcanv, fpreadbmp, fpwritebmp, fpditherer;
803+
804+procedure BlackAndWhite(SourceFile, TargetFile:String);
805+var
806+ sourceImg, targetImg: TFPMemoryImage;
807+ reader: TFPReaderBMP;
808+ writer: TFPWriterBMP;
809+ palette: TFPPalette = nil;
810+ ditherer: TFPFloydSteinbergDitherer = nil;
811+begin
812+ sourceImg := TFPMemoryImage.Create(0,0);
813+ targetImg := TFPMemoryImage.Create(0,0);
814+ reader := TFPReaderBMP.Create;
815+ writer := TFPWriterBMP.Create;
816+ try
817+ sourceImg.LoadFromFile(SourceFile);
818+ palette := TFPPalette.Create(2);
819+ palette.Add(colBlack);
820+ palette.Add(colWhite);
821+ ditherer := TFPFloydSteinbergDitherer.Create(palette);
822+ ditherer.Dither(sourceImg, targetImg);
823+ writer.BitsPerPixel := 1;
824+ targetImg.SaveToFile(TargetFile, writer);
825+ finally
826+ ditherer.Free;
827+ palette.Free;
828+ writer.Free;
829+ reader.Free;
830+ targetImg.Free;
831+ sourceImg.Free;
832+ end;
833+end;
834+```
835+
836+### Gamma correction
837+
838+FCL-Image can be used for image transformations, such as **gamma correction** (adjustment of pixel values to modify brightness, see <https://en.wikipedia.org/wiki/Gamma_correction>):
839+
840+``` Pascal
841+uses
842+ fpimage, fpreadjpeg, fpwritejpeg, math;
843+
844+procedure GammaCorrection(const ASrcFile, ADestFile: String; AGamma: Double);
845+var
846+ img: TFPMemoryImage;
847+ reader: TFPCustomImageReader;
848+ writer: TFPCustomImageWriter;
849+ i, j: Integer;
850+ clr: TFPColor;
851+begin
852+ Assert(AGamma <> 0.0);
853+
854+ img := TFPMemoryImage.Create(0, 0);
855+ try
856+ reader := TFPReaderJpeg.Create;
857+ try
858+ img.LoadFromFile(ASrcFile, reader);
859+ finally
860+ reader.Free;
861+ end;
862+
863+ for j := 0 to img.Height - 1 do
864+ for i := 0 to img.Width - 1 do
865+ begin
866+ clr := img.Colors[i, j];
867+ clr.Red := round(((clr.Red / 65535)**AGamma)*65535);
868+ clr.Green := round(((clr.Green / 65535)**AGamma)*65535);
869+ clr.Blue := round(((clr.Blue / 65535)**AGamma)*65535);
870+ img.Colors[i, j] := clr;
871+ end;
872+
873+ writer := TFPWriterJpeg.Create;
874+ try
875+ img.SaveToFile(ADestFile, writer);
876+ finally
877+ writer.Free;
878+ end;
879+ finally
880+ img.Free;
881+ end;
882+end;
883+```
884+
885+### Bar codes
886+
887+FCL-Image contains some units to create bar codes. Here is an example how to create a QRCode and save it as a graphics file:
888+
889+``` Pascal
890+program qrcode_as_imagefile;
891+uses
892+ fpqrcodegen, fpimgqrcode, fpWritePng;
893+const
894+ TEXT_STRING = 'This is a qrcode generated by fpc.';
895+ FILE_NAME = 'qrcode.png';
896+var
897+ qrcode: TImageQRCodeGenerator;
898+begin
899+ qrcode := TImageQRCodeGenerator.Create;
900+ try
901+ qrcode.PixelSize := 4;
902+ qrcode.Border := 8;
903+ qrcode.ErrorCorrectionLevel := EccHigh;
904+ qrcode.Generate(TEXT_STRING);
905+ qrcode.SaveToFile(FILE_NAME);
906+ finally
907+ qrcode.Free;
908+ end;
909+end.
910+```
911+
912+And the next example creates a "2-of-5-industrial" barcode:
913+
914+``` pascal
915+program project1;
916+uses
917+ Types, fpImage, fpBarCode, fpImgBarCode, fpWritePng;
918+const
919+ HEIGHT = 60;
920+ NUMERIC_TEXT = '0123456789';
921+ ENCODING = be2of5Industrial;
922+ UNIT_WIDTH = 2;
923+ WEIGHT = 4;
924+ FILE_NAME = 'barcode.png';
925+var
926+ barcode: TFPDrawBarcode;
927+ width: Integer;
928+begin
929+ barcode := TFPDrawBarcode.Create;
930+ try
931+ barcode.Encoding := ENCODING;
932+ barcode.UnitWidth := UNIT_WIDTH;
933+ barcode.Weight := WEIGHT;
934+ barcode.Text := NUMERIC_TEXT;
935+ width := barcode.CalcWidth;
936+ barcode.Rect := Rect(0, 0, width, HEIGHT);
937+ barcode.Image := TFPCompactImgGray8Bit.Create(barcode.Rect.Width, barcode.Rect.Height);
938+ try
939+ if barcode.Draw then
940+ begin
941+ barcode.Image.SaveToFile(FILE_NAME);
942+ WriteLn('Saved to file ', FILE_NAME);
943+ end else
944+ WriteLn('Error generating barcode.');
945+ finally
946+ barcode.Image.Free;
947+ end;
948+ finally
949+ barcode.Free;
950+ end;
951+end.
952+```
953+
954+### Getting image size without loading the image itself
955+
956+Answer by forum member **wp**.
957+
958+The basic image reader type, `TFPCustomImageReader`, is equipped with a class function `ImageSize: TPoint` which determines the image size in pixels without decoding the image data. In case of a jpeg image, the reader class is `TFPReaderJPEG` in unit `fpreadjpeg`; therefore, assuming that the image file is accessed via a stream, the image size can be obtained as a `TPoint` by a one-liner:
959+
960+``` pascal
961+ Size := TFPReaderJPEG.ImageSize(stream);
962+```
963+
964+If you have other image file formats you must pick the correct reader class from the fcl-image units. To help you, the basic fcl-image class, `TFPCustomImage`, has class methods `FindReaderFromStream(AStream)` which determines the required reader class from the file header or `FindReaderFromFileName(AFileName)` which determines the reader class from the extension of the filename.
965+
966+Putting these class methods together you can determine the image size for any image format supported by fcl-image by the following short function (do not forget to list the reader units in the uses clause for all file formats requested):
967+
968+``` pascal
969+uses
970+ [...] fpImage, fpReadJpeg, fpReadBMP, fpReadPNG, fpReadGIF, fpReadPCX, fpReadTIFF, fpReadTGA;
971+
972+function GetImageSize(const AFileName: String; out ASize: TPoint): Boolean;
973+var
974+ stream: TStream;
975+ readerClass: TFPCustomImageReaderClass;
976+begin
977+ Result := false;
978+ ASize := Point(-1, -1);
979+ stream := TFileStream.Create(AFileName, fmOpenRead);
980+ try
981+ readerClass := TFPCustomImage.FindReaderFromStream(stream);
982+ if readerClass <> nil then
983+ begin
984+ ASize := readerClass.ImageSize(stream);
985+ Result := true;
986+ end;
987+ finally
988+ stream.Free;
989+ end;
990+end;
991+```
992+
993+## See also
994+
995+- [[Package List|Packages List]]
996+- [[Developing with Graphics]]
997+- [Stretching a Canvas: Image support for Free Pascal](https://www.freepascal.org/~michael/articles/#canvas): In this extensive article by Michael Van Canneyt, the Free Pascal support for images and simple drawing support is presented.
998+
999+---
1000+*From the Free Pascal wiki, page "fcl-image", as it stood on 2024-03-08 after a change by Wp, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*
1001+Category: FCL
1002+Category: Graphics
1003+Category: Packages

Back to history