Since ImageEn does not have a Trim feature for TIEBitmap, I have written a Trim ClassHelper for TIEBitmap:
unit PAIEImageTrimming;
interface
uses
ImageEnProc, ImageEnView, iexBitmaps, Vcl.Graphics, Winapi.Windows, hyieutils, hyiedefs;
type
TIEBitmapHelper = class helper for TIEBitmap
function Trim: TIEBitmap;
private
function FindMostCommonEdgeColor: TRGB;
function IsRowUniform(Y: Integer; Color: TRGB): Boolean;
function IsColumnUniform(X: Integer; Color: TRGB): Boolean;
function FindTrimRect: TRect;
end;
implementation
uses
System.Classes, System.SysUtils;
function TIEBitmapHelper.FindMostCommonEdgeColor: TRGB;
var
TopLeftPixel, BottomRightPixel: TRGB;
begin
TopLeftPixel := Self.Pixels[0, 0];
BottomRightPixel := Self.Pixels[Self.Width - 1, Self.Height - 1];
// Assuming the top left pixel as the most common color for simplicity
Result := TopLeftPixel;
end;
function TIEBitmapHelper.IsRowUniform(Y: Integer; Color: TRGB): Boolean;
var
X: Integer;
CurrentColor: TRGB;
begin
for X := 0 to Self.Width - 1 do
begin
CurrentColor := Self.Pixels[X, Y];
if not CompareMem(@CurrentColor, @Color, SizeOf(TRGB)) then
Exit(False);
end;
Result := True;
end;
function TIEBitmapHelper.IsColumnUniform(X: Integer; Color: TRGB): Boolean;
var
Y: Integer;
CurrentColor: TRGB;
begin
for Y := 0 to Self.Height - 1 do
begin
CurrentColor := Self.Pixels[X, Y];
if not CompareMem(@CurrentColor, @Color, SizeOf(TRGB)) then
Exit(False);
end;
Result := True;
end;
function TIEBitmapHelper.FindTrimRect: TRect;
var
x, y: Integer;
MostCommonEdgeColor: TRGB;
begin
MostCommonEdgeColor := FindMostCommonEdgeColor;
Result := System.Classes.Rect(0, 0, Self.Width, Self.Height);
// Find top edge
y := 0;
while (y < Self.Height) and IsRowUniform(y, MostCommonEdgeColor) do
Inc(y);
Result.Top := y;
// Find bottom edge
y := Self.Height - 1;
while (y >= Result.Top) and IsRowUniform(y, MostCommonEdgeColor) do
Dec(y);
Result.Bottom := y + 1;
// Find left edge
x := 0;
while (x < Self.Width) and IsColumnUniform(x, MostCommonEdgeColor) do
Inc(x);
Result.Left := x;
// Find right edge
x := Self.Width - 1;
while (x >= Result.Left) and IsColumnUniform(x, MostCommonEdgeColor) do
Dec(x);
Result.Right := x + 1;
end;
function TIEBitmapHelper.Trim: TIEBitmap;
var
TrimRect: TRect;
begin
TrimRect := FindTrimRect;
Result := TIEBitmap.Create;
try
Result.Assign(Self);
Result.Crop(TrimRect.Left, TrimRect.Top, TrimRect.Right - TrimRect.Left, TrimRect.Bottom - TrimRect.Top);
except
Result.Free;
raise;
end;
end;
end.
Now you can trim a TIEBitmap by simply writing: bmp := bmp.Trim;
If you want, I can donate it to ImageEn.
Please feel free to fix any errors or optimize anything you want.