Thursday, September 10, 2009

How to scale bitmap in percent

Need to scale a bitmap to 50%? how about 128%?
Here's a function which scales a bitmap to desired percent
function BitmapScale(theBitmap: TBitmap; iPercent: Integer): Boolean;
var
  TmpBmp: TBitmap;
  ARect: TRect;
  h, w: Real;
  hi, wi: Integer;
begin
  Result := False;
  try
    TmpBmp := TBitmap.Create;
    try
      h := theBitmap.Height * (iPercent / 100);
      w := theBitmap.Width * (iPercent / 100);
      hi := StrToInt(FormatFloat('#', h)) + theBitmap.Height;
      wi := StrToInt(FormatFloat('#', w)) + theBitmap.Width;
      TmpBmp.Width := wi;
      TmpBmp.Height := hi;
      ARect := Rect(0, 0, wi, hi);
      TmpBmp.Canvas.StretchDraw(ARect, theBitmap);
      theBitmap.Assign(TmpBmp);
    finally
      TmpBmp.Free;
    end;
    Result := True;
  except
    Result := False;
  end;
end;


Usage
BitmapScale(YourBitmapVar, 70);

1 comment:

  1. StretchDraw produces the worst result I've seen. Isn't there a better alternative?

    ReplyDelete

Blogroll(General programming and Delphi feeds)