This is a routine I have used a lot in different graphics applications. It was designed to scale down DIBS quickly to thumbnail and preview which was later pushed to a database. But I have also used it in my thumbnail browser and in a few image viewers and a graphics library I wrote. Tried and tested by time.
It attempts to center the resulting rectangle within the bounds of “newwidth / newheight”.
Function JLReScale(aWidth,aHeight:Integer; NewWidth,NewHeight:Integer; var outRect:TRect):Boolean; var x,y: Integer; x1,y1: Real; wd,hd: Integer; Begin result:=False; if (aWidth>1) and (aHeight>1) then Begin If (NewWidth>1) and (NewHeight>1) then Begin x1:=(NewWidth/aWidth); y1:=(NewHeight/aHeight); if x1 > y1 then begin outRect.top:=0; outRect.bottom:=NewHeight; x:=trunc(aWidth*y1); outRect.left:=(NewWidth-x) shr 1; outRect.right:=outRect.left+x; end else begin outRect.left:=0; outRect.right:=NewWidth; y:=trunc(aHeight*x1); outRect.top:=(NewHeight-y) shr 1; outRect.bottom:=outRect.top+y; end; result:=True; end; end; end;