Understanding TBitmap.Scanline in Delphi & C++ Builder - delphi

Delphi & C++ Builder have a TBitmap class with a Scanline property which returns the memory of pixels of the bitmap. This seems to be different when I look in a hex editor of the BMP file.
I'm trying to port a C++ Builder app to Java, and would like to understand the algorithm in Scanline. If I have the file, how do I generate the memory array like Scanline does? What is the exact spec behind Scanline?
Clarifcation: The BMP is a Windows 24bit DIB. I don't provide any other info in the code; C++ Builder seems to load it into some type of memory structure, but it's not byte-for-byte. Would like to know what the spec of that structture is.

A bitmap file starts with a BITMAPFILEHEADER, the bfOffBits member specifies the starting address of image data. This is a DWORD at Dh (11-14th bytes). Delphi VCL has the structure defined as TBitmapFileHeader in 'windows.pas'.
The last row of the ScanLine points to this image data (bottom-up). The VCL has this value in bmBits member of the dsBm(a BITMAP) member or the DIBSECTION of the image. When a scan line is requested, the VCL calculates an offset depending on the requested row, number of pixels in a row (width of the image) and how many bits make up a pixel, and returns a pointer to an address adding this offset to bmBits. It's really byte-by-byte image data.
The below Delphi sample code reads a 24bit bitmap to a file stream and compares each read pixel with the pixel data of the Bitmap.ScanLine counterpart:
procedure TForm1.Button1Click(Sender: TObject);
var
BmpFile: string;
Bmp: TBitmap;
fs: TFileStream;
FileHeader: TBitmapFileHeader;
InfoHeader: TBitmapInfoHeader;
iHeight, iWidth, Padding: Longint;
ScanLine: Pointer;
RGBFile, RGBBitmap: TRGBTriple;
begin
BmpFile := ExtractFilePath(Application.ExeName) + 'Attention_128_24.bmp';
// laod bitmap to TBitmap
Bmp := TBitmap.Create;
Bmp.LoadFromFile(BmpFile);
Assert(Bmp.PixelFormat = pf24bit);
// read bitmap file with stream
fs := TFileStream.Create(BmpFile, fmOpenRead or fmShareDenyWrite);
// need to get the start of pixel array
fs.Read(FileHeader, SizeOf(FileHeader));
// need to get width and height of bitmap
fs.Read(InfoHeader, SizeOf(InfoHeader));
// just a general demo - no top-down image allowed
Assert(InfoHeader.biHeight > 0);
// size of each row is a multiple of the size of a DWORD
Padding := SizeOf(DWORD) -
(InfoHeader.biWidth * 3) mod SizeOf(DWORD); // pf24bit -> 3 bytes
// start of pixel array
fs.Seek(FileHeader.bfOffBits, soFromBeginning);
// compare reading from file stream with the value from scanline
for iHeight := InfoHeader.biHeight - 1 downto 0 do begin
// get the scanline, bottom first
ScanLine := Bmp.ScanLine[iHeight];
for iWidth := 0 to InfoHeader.biWidth - 1 do begin
// read RGB from file stream
fs.Read(RGBFile, SizeOf(RGBFile));
// read RGB from scan line
RGBBitmap := TRGBTriple(Pointer(
Longint(ScanLine) + (iWidth * SizeOf(TRGBTriple)))^);
// assert the two values are the same
Assert((RGBBitmap.rgbtBlue = RGBFile.rgbtBlue) and
(RGBBitmap.rgbtGreen = RGBFile.rgbtGreen) and
(RGBBitmap.rgbtRed = RGBFile.rgbtRed));
end;
// skip row padding
fs.Seek(Padding, soCurrent);
end;
end;
A picture about finding the starting of pixel data of a bitmap file in a hex-editor:

Related

How to use correctly TBitmap object to save a file with transparency?

Below is my sample code:
var lBitmap: TBitmap;
begin
lBitmap := TBitmap.Create;
lBitmap.PixelFormat := TPixelFormat.pf32bit;
lBitmap.Transparent := TRUE; // !
lBitmap.LoadFromFile( 'd:\temp\bmp32b_300dpi_transparent_400x250.bmp' );
// Bitmap RGB+Alpha created with GIMP
// modifications on pixels
Canvas.Draw(100, 0, lBitmap);
// Up to this point it is correct, the drawing is painted with transparency
lBitmap.SaveToFile( 'd:\tmp\after.bmp' ); // after this -> I have lost transparency
lBitmap.Free;
end;
How to use correctly TBitmap object to save a file with transparency?
It seems to me like TBitmap doesn't support saving bitmaps with alpha channels. And maybe we shouldn't blame the VCL for this, because BMPs with alpha transparency are uncommon. Many applications don't support transparent BMPs.
This being said, I "reverse-engineered" a BMP with alpha channel created in GIMP and wrote the following Delphi routine to produce the very same bitmap:
procedure SaveTransparentBitmap(ABitmap: TBitmap; const AFileName: string);
var
FS: TFileStream;
BFH: TBitmapFileHeader;
BIH: TBitmapV5Header;
y: Integer;
sl: PUInt64;
begin
// ABitmap MUST have the GIMP BGRA format.
FS := TFileStream.Create(AFileName, fmOpenWrite);
try
// Bitmap file header
FillChar(BFH, SizeOf(BFH), 0);
BFH.bfType := $4D42; // BM
BFH.bfSize := 4 * ABitmap.Width * ABitmap.Height + SizeOf(BFH) + SizeOf(BIH);
BFH.bfOffBits := SizeOf(BFH) + SizeOf(BIH);
FS.Write(BFH, SizeOf(BFH));
// Bitmap info header
FillChar(BIH, SizeOf(BIH), 0);
BIH.bV5Size := SizeOf(BIH);
BIH.bV5Width := ABitmap.Width;
BIH.bV5Height := ABitmap.Height;
BIH.bV5Planes := 1;
BIH.bV5BitCount := 32;
BIH.bV5Compression := BI_BITFIELDS;
BIH.bV5SizeImage := 4 * ABitmap.Width * ABitmap.Height;
BIH.bV5XPelsPerMeter := 11811;
BIH.bV5YPelsPerMeter := 11811;
BIH.bV5ClrUsed := 0;
BIH.bV5ClrImportant := 0;
BIH.bV5RedMask := $00FF0000;
BIH.bV5GreenMask := $0000FF00;
BIH.bV5BlueMask := $000000FF;
BIH.bV5AlphaMask := $FF000000;
BIH.bV5CSType := $73524742; // BGRs
BIH.bV5Intent := LCS_GM_GRAPHICS;
FS.Write(BIH, SizeOf(BIH));
// Pixels
for y := ABitmap.Height - 1 downto 0 do
begin
sl := ABitmap.ScanLine[y];
FS.Write(sl^, 4 * ABitmap.Width);
end;
finally
FS.Free;
end;
end;
This write a BITMAPFILEHEADER followed by a BITMAPV5HEADER and the pixel data in BGRA format.
I omit all kinds of error checking. For instance, I don't verify that ABitmap actually has the required format.
Test:
procedure TForm1.FormCreate(Sender: TObject);
var
bm: TBitmap;
begin
bm := TBitmap.Create;
try
bm.LoadFromFile('C:\Users\Andreas Rejbrand\Desktop\Test.bmp');
SaveTransparentBitmap(bm, 'C:\Users\Andreas Rejbrand\Desktop\Test2.bmp');
finally
bm.Free;
end;
end;
After this, Test.bmp and Test2.bmp are binary equal.
Saving 32-bit bitmaps with alpha channels needs a workaround as #Andreas Rejbrand has pointed out. There also seems to be some more confusion about the BMP file format, what the TBitmap.Transparent property does, and how you draw bitmaps transparently with the VCL.
32-bit bitmaps are the only bitmaps that carry information about transparency in the files. They have that information in the alpha channel and nowhere else. In the alpha channel, every pixel has its own 0-255 alpha value in the RGBA structure. This is often referred to as partial transparency.
When you draw/display 32-bit bitmaps, you have to pay attention to the TBitmap.AlphaFormat property. It defaults to afIgnore, which means that the bitmap is drawn without transparency. Use afPremultiplied or afDefined to draw with transparency. The latter is probably what you want.
The TBitmap.Transparent property is specific to the VCL TBitmap, and there is nothing in the BMP file format that corresponds to it. It's just a simple way to display bitmaps transparently, where a color defines which pixels should be fully transparent. The application must be familiar with the bitmaps to be able to use this method. It's also important to be aware of how the TBitmap.TransparentMode property works. It defaults to tmAuto, which sets the color of the bottom-leftmost pixel of the bitmap as TBitmap.TransparentColor. When TransparentMode is set to tmFixed, the TBitmap.TransparentColor you have specified is used. This method can also be used on 32-bit bitmaps.
Note that when you draw with the standard VCL TCanvas drawing routines on a 32-bit bitmap with transparency in the alpha channel, the transparency will be lost where you have drawn.
It seems that in your sample code, you have ignored AlphaFormat and TransparentMode. You should also decide if you want to use the transparency in the alpha channel or the TBitmap.Transparent method. But we have no bitmap in order to check if that is the real problem.

TImage width with double value instead integer

How can I set TImage size as double value? Example Image1.width := 50.1; or what component accept it, because TImage only accept integer values.
I'm working with download files, and one image should be the number of elements to download, so Image1.width max value is 340, i need to divide this value by the amount of files who will be downloaded, and increase this value on image1.width when every download be finished, but TImage only accept Integer value.
I already did it using "Round" but it is not what I need.
As answered, you cannot set the image's size to any floating point value.
However, using coordinate spaces and transformations functions, you can set an arbitrary transformation between a logical coordinate system and the viewing device. This can be used to increase the logical extent of the image's canvas size with each download and yet keep the image on the screen with an entirely different size.
The below example demonstrates the concept by drawing 4 rows and 4 columns of a 256x256 image on a 105x105 bitmap canvas of a TPicture of a TImage. Basically it achieves to draw a single 256x256 image on a 26.25x26.25 px. surface.
uses
pngimage;
procedure TForm1.Button1Click(Sender: TObject);
const
Col = 4;
Row = 4;
var
Png: TPngImage;
ImgCanvas: TCanvas;
ExtX, ExtY: Integer;
MapMode: Integer;
Size: TSize;
i, j: Integer;
begin
Png := TPngImage.Create;
try
Png.LoadFromFile('...\Attention.png');
Png.Draw(Canvas, Rect(0, 0, Png.Width, Png.Height)); // original picture
Image1.Picture.Bitmap.Canvas.Brush.Color := Color;
Image1.Picture.Bitmap.SetSize(Image1.Width, Image1.Height);
ImgCanvas := Image1.Picture.Bitmap.Canvas;
SetStretchBltMode(ImgCanvas.Handle, HALFTONE);
MapMode := SetMapMode(ImgCanvas.Handle, MM_ISOTROPIC);
if MapMode <> 0 then
try
ExtX := Png.Width * Col;
ExtY := Png.Height * Row;
if not GetWindowExtEx(ImgCanvas.Handle, Size) then
RaiseLastOSError;
if not SetWindowExtEx(ImgCanvas.Handle, Size.cx * ExtX div Image1.Width,
Size.cy * ExtY div Image1.Height, nil) then
RaiseLastOSError;
if not SetViewportExtEx(ImgCanvas.Handle, Size.cx, Size.cy, nil) then
RaiseLastOSError;
i := 0;
j := 0;
while j < ExtY do begin
while i < ExtX do begin
Png.Draw(ImgCanvas, Rect(i, j, i + Png.Width, j + Png.Height));
Inc(i, Png.Width);
end;
i := 0;
Inc(j, Png.Height);
end;
finally
SetMapMode(ImgCanvas.Handle, MapMode);
end
else
RaiseLastOSError;
finally
Png.Free;
end;
end;
Probably worth noting that GDI may not be the best graphics system when scaling is involved. For quick reference, here's what the above yields:
Assuming you're using the VCL framework, all controls across Delphi are Integer based. You simply cannot assign a float value, not without first converting it to an integer.
The Firemonkey framework on the other hand is widely based on float values.

Saving transparent (alpha channel) PNG from TImageList

I have a TImageList which contains transparent icons (32bit, with alpha channel). What I want to do is to save individual icons based on image index as PNG file(s), while preserving alpha channel transparency. Using RAD Studio 2010 so it has TPngImage support, no need for third party libraries. Images are loaded into TImageList from PNG "sprite" image using the method here - Add a png image to a imagelist in runtime using Delphi XE - so the transparency is preserved upon loading. Now I need to save them out individually, in other words, extract individual images from sprite images which is already loaded into TImageList.
My code so far:
int imageindex = 123;
boost::scoped_ptr<TPngImage> png(new TPngImage);
boost::scoped_ptr<Graphics::TBitmap> bmp(new Graphics::TBitmap);
MyImageList->GetBitmap(imageindex, bmp.get()); // Using GetBitmap to copy TImageList image into separate TBitmap
png->Assign(bmp.get()); // Assign that bitmap to TPngImage
png->SaveToFile("C:\\filename.png");
The above works but it saves with the white background (transparency is not preserved after saving). I am probably missing a simple step but can't figure it out.
Delphi code is also welcome, shouldn't be hard to translate.
Yes, you can obtain PNG-image from TImageList where it was added. Code below allows you to do this!
Firstly, add PngImage to your uses clause.
procedure LoadPNGFromImageList(AImageList: TCustomImageList; AIndex: Integer; var ADestPNG: TPngImage);
const
PixelsQuad = MaxInt div SizeOf(TRGBQuad) - 1;
type
TRGBAArray = Array [0..PixelsQuad - 1] of TRGBQuad;
PRGBAArray = ^TRGBAArray;
var
ContentBmp: TBitmap;
RowInOut: PRGBAArray;
RowAlpha: PByteArray;
X: Integer;
Y: Integer;
begin
if not Assigned(AImageList) or (AIndex < 0) or
(AIndex > AImageList.Count - 1) or not Assigned(ADestPNG)
then
Exit;
ContentBmp := TBitmap.Create;
try
ContentBmp.SetSize(ADestPNG.Width, ADestPNG.Height);
ContentBmp.PixelFormat := pf32bit;
// Allocate zero alpha-channel
for Y:=0 to ContentBmp.Height - 1 do
begin
RowInOut := ContentBmp.ScanLine[Y];
for X:=0 to ContentBmp.Width - 1 do
RowInOut[X].rgbReserved := 0;
end;
ContentBmp.AlphaFormat := afDefined;
// Copy image
AImageList.Draw(ContentBmp.Canvas, 0, 0, AIndex, true);
// Now ContentBmp has premultiplied alpha value, but it will
// make bitmap too dark after converting it to PNG. Setting
// AlphaFormat property to afIgnored helps to unpremultiply
// alpha value of each pixel in bitmap.
ContentBmp.AlphaFormat := afIgnored;
// Copy graphical data and alpha-channel values
ADestPNG.Assign(ContentBmp);
ADestPNG.CreateAlpha;
for Y:=0 to ContentBmp.Height - 1 do
begin
RowInOut := ContentBmp.ScanLine[Y];
RowAlpha := ADestPNG.AlphaScanline[Y];
for X:=0 to ContentBmp.Width - 1 do
RowAlpha[X] := RowInOut[X].rgbReserved;
end;
finally
ContentBmp.Free;
end;
end;
Look at the picture. It is depicts what will happen if we set or not set such line of code:
ContentBmp.AlphaFormat := afIgnored;
Figure 1 is a result of setting afIgnored and the second one figure is a result of not setting afIgnored, allowing to use previously set afDefined.
Original image is an image named Figure 1
Using of code above in application:
procedure TForm1.aButton1Click(Sender: TObject);
var
DestPNG: TPngImage;
begin
DestPNG := TPNGImage.Create;
try
// Initialize PNG
DestPNG.CreateBlank(COLOR_RGBALPHA, 8, 60, 60);
// Obtain PNG from image list
LoadPNGFromImageList(ImageList1, 0, DestPNG);
// Output PNG onto Canvas
DestPNG.Draw(Canvas, Rect(0, 0, 60, 60));
DestPNG.SaveToFile('C:\MyPNGIcon.png');
finally
DestPNG.Free;
end;
end;

Why does loading of a PNG image format icon cause the "Out of system resources" exception?

I have a specific icon file, which is composed from PNG compressed images and when I try to load it and add to a TImageList, the Out of system resources exception is raised.
The icon file is here: https://www.dropbox.com/s/toll6jhlwv3cpq0/icon.ico?m
Here is the code, which works with common type of icons, but fails with PNG image icons:
procedure TForm1.Button1Click(Sender: TObject);
var
Icon: TIcon;
begin
try
Icon := TIcon.Create;
Icon.LoadFromFile('icon.ico');
ImageList1.AddIcon(Icon);
Caption := IntToStr(ImageList1.Count);
finally
Icon.Free;
end;
end;
Why does the PNG image icon format fail to load with Out of system resources exception ? How to add this kind of icon to an image list ?
Problem source:
The fact, that the icon is a multi-size icon file doesn't matter in this case. The icon's bitmap info header is internally read in a different way than should be. Your icon is the PNG format file icon and those have no bitmap info header structure. The reason, why you are getting Out of system resources exception, is because the internally used procedures expects from icon to have a TBitmapInfoHeader structure and then tries to create a temporary bitmap based on this header information. For your icon it was read like this:
If you take a look closer on the header values, you calculate that the system would try to create a bitmap which would be in size 169478669 * 218103808 pixels at 21060 B per pixel, what would need to have at least 778.5 EB (exabytes) of free memory :-)
Workaround:
That's of course impossible (at this time :-) and happens just because the PNG file format icons doesn't have this bitmap header, but instead contains directly a PNG image on that position. What you can do to workaround this is to check, if there's the PNG signature on the first 8 bytes of the image data, which actually checks if there's a PNG image and if so, treat it as a PNG image, otherwise try to add the icon in a common way through the TIcon object.
In the following code, the ImageListAddIconEx function iterates all the icons in the icon file and when there's one which matches the image list dimensions it is processed. The processing first checks those 8 bytes if there's a PNG image on data offset position and if so, it adds this PNG image to the image list. If not, then the icon is added in a common way through the TIcon object. This function returns index of the added icon in the image list if succeed, -1 otherwise:
uses
PNGImage;
type
TIconDirEntry = packed record
bWidth: Byte; // image width, in pixels
bHeight: Byte; // image height, in pixels
bColorCount: Byte; // number of colors in the image (0 if >= 8bpp)
bReserved: Byte; // reserved (must be 0)
wPlanes: Word; // color planes
wBitCount: Word; // bits per pixel
dwBytesInRes: DWORD; // image data size
dwImageOffset: DWORD; // image data offset
end;
TIconDir = packed record
idReserved: Word; // reserved (must be 0)
idType: Word; // resource type (1 for icons)
idCount: Word; // image count
idEntries: array[0..255] of TIconDirEntry;
end;
PIconDir = ^TIconDir;
function ImageListAddIconEx(AImageList: TCustomImageList;
AIconStream: TMemoryStream): Integer;
var
I: Integer;
Data: PByte;
Icon: TIcon;
IconHeader: PIconDir;
Bitmap: TBitmap;
PNGImage: TPNGImage;
PNGStream: TMemoryStream;
const
PNGSignature: array[0..7] of Byte = ($89, $50, $4E, $47, $0D, $0A, $1A, $0A);
begin
// initialize result to -1
Result := -1;
// point to the icon header
IconHeader := AIconStream.Memory;
// iterate all the icons in the icon file
for I := 0 to IconHeader.idCount - 1 do
begin
// if the icon dimensions matches to the image list, then...
if (IconHeader.idEntries[I].bWidth = AImageList.Width) and
(IconHeader.idEntries[I].bHeight = AImageList.Height) then
begin
// point to the stream beginning
Data := AIconStream.Memory;
// point with the Data pointer to the current icon image data
Inc(Data, IconHeader.idEntries[I].dwImageOffset);
// check if the first 8 bytes are PNG image signature; if so, then...
if CompareMem(Data, #PNGSignature[0], 8) then
begin
Bitmap := TBitmap.Create;
try
PNGImage := TPNGImage.Create;
try
PNGStream := TMemoryStream.Create;
try
// set the icon stream position to the current icon data offset
AIconStream.Position := IconHeader.idEntries[I].dwImageOffset;
// copy the whole PNG image from icon data to a temporary stream
PNGStream.CopyFrom(AIconStream,
IconHeader.idEntries[I].dwBytesInRes);
// reset the temporary stream position to the beginning
PNGStream.Position := 0;
// load the temporary stream data to a temporary TPNGImage object
PNGImage.LoadFromStream(PNGStream);
finally
PNGStream.Free;
end;
// assign temporary TPNGImage object to a temporary TBitmap object
Bitmap.Assign(PNGImage);
finally
PNGImage.Free;
end;
// to properly add the bitmap to the image list set the AlphaFormat
// to afIgnored, see e.g. http://stackoverflow.com/a/4618630/960757
// if you don't have TBitmap.AlphaFormat property available, simply
// comment out the following line
Bitmap.AlphaFormat := afIgnored;
// and finally add the temporary TBitmap object to the image list
Result := AImageList.Add(Bitmap, nil);
finally
Bitmap.Free;
end;
end
// the icon is not PNG type icon, so load it to a TIcon object
else
begin
// reset the position of the input stream
AIconStream.Position := 0;
// load the icon and add it to the image list in a common way
Icon := TIcon.Create;
try
Icon.LoadFromStream(AIconStream);
Result := AImageList.AddIcon(Icon);
finally
Icon.Free;
end;
end;
// break the loop to exit the function
Break;
end;
end;
end;
And the usage:
procedure TForm1.Button1Click(Sender: TObject);
var
Index: Integer;
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
try
Stream.LoadFromFile('d:\Icon.ico');
Index := ImageListAddIconEx(ImageList1, Stream);
if (Index <> -1) then
ImageList1.Draw(Canvas, 8, 8, Index);
finally
Stream.Free;
end;
end;
Conclusion:
I'd say if Microsoft recommends the PNG icon format to use (supported since Windows Vista), it would be fine to update the ReadIcon procedure in Graphics.pas to take this into account.
Something to read:
The evolution of the ICO file format, part 4: PNG images

Fast way of swapping Red/Blue bytes using ScanLine

Currently, I loop the Canvas.Pixels[] property and read each pixel on a canvas to swap Red/Blue bytes around (for specific reasons). However, it takes an average of 2 seconds per picture, and I have over 8,000 pictures I need to convert (overnight). I understand I can use a method of ScanLine to accomplish this much faster, but I know nothing about ScanLine - it's a much lower level of coding than I'm comfortable with. What's the fastest way to accomplish this? I'm willing to wait some time for this to run through, but it would still be nice if I could chop that time in half or more.
Right now, this is the procedure I use:
procedure SwapBytes(var Bmp: TBitmap);
var
X, Y: Integer;
R, G, B: Byte;
C: TColor;
begin
for Y := 0 to Bmp.Height - 1 do begin
for X := 0 to Bmp.Width - 1 do begin
C:= Bmp.Canvas.Pixels[X,Y];
R:= GetRValue(C);
G:= GetGValue(C);
B:= GetBValue(C);
Bmp.Canvas.Pixels[X,Y]:= RGB(B, G, R)
end;
end;
end;
Added Note: An initial conversion of over 8,000 images is the first step of why I need this. However, I also will be using the same thing in our software to automatically convert any image on the spot, as needed. So a third-party converter won't work, because I cannot distribute this to our clients.
I would try something like follows. This version is only for 24-bit bitmaps:
procedure SwapRedBluePixels(ABitmap: TBitmap);
var
X: Integer;
Y: Integer;
Red: Byte;
Pixel: PRGBTriple;
begin
// check for the bit depth, it must be 24-bit if you use PRGBTriple pointer
// for line scan; if it wouldn't the iterated line pointers would point to
// another place in the memory
if ABitmap.PixelFormat <> pf24bit then
begin
ShowMessage('Your bitmap has color depth different from 24-bit');
Exit;
end;
// iterate through the image vertically
for Y := 0 to (ABitmap.Height - 1) do
begin
// access the line of pixels and get the pointer to the first pixel of
// that line
Pixel := ABitmap.ScanLine[Y];
// iterate through the scanned line pixels horizontally
for X := 0 to (ABitmap.Width - 1) do
begin
// store the pixel's red channel value
Red := Pixel.rgbtRed;
// modify the pixel's red channel value
Pixel.rgbtRed := Pixel.rgbtBlue;
// modify the pixel's blue channel value
Pixel.rgbtBlue := Red;
// increment to get the next pixel pointer of the scanned line
Inc(Pixel);
end;
end;
end;
Update 2:
This version is for 24-bit and 32-bit bitmaps:
procedure SwapRedBluePixels(ABitmap: TBitmap);
var
X: Integer;
Y: Integer;
Red: Byte;
Size: Integer;
Pixels: PByteArray;
begin
// check the color depth and set the size of the pixel arrangement
case ABitmap.PixelFormat of
pf24bit: Size := SizeOf(TRGBTriple);
pf32bit: Size := SizeOf(TRGBQuad);
else
// if the image is not 24-bit or 32-bit go away
begin
ShowMessage('Your bitmap has unsupported color depth!');
Exit;
end;
end;
// iterate through the image vertically
for Y := 0 to (ABitmap.Height - 1) do
begin
// access the line of pixels and get the pointer to the first pixel of
// that line
Pixels := ABitmap.ScanLine[Y];
// iterate through the scanned line pixels horizontally
// for 24-bit images the pixels are stored like
// B -> G -> R -> B -> G -> R etc.
// for 32-bit images the pixels are stored like
// B -> G -> R -> A -> B -> G -> R -> A etc.
// so we can simply use e.g. byte array and iterate through
// it, if we have 24-bit image, we have to read each element,
// if 32-bit we have to skip the alpha (reserved) channel
for X := 0 to (ABitmap.Width - 1) do
begin
// store the pixel's red channel value
Red := Pixels^[(X * Size) + 2];
// modify the pixel's red channel value
Pixels^[(X * Size) + 2] := Pixels^[(X * Size)];
// modify the pixel's blue channel value
Pixels^[(X * Size)] := Red;
end;
end;
end;

Resources