Doing Clipping Manually

Recently I was doing a PHP script that combines some images and needed to clip some of them to a specific rectangle. PHP doesn’t have a function to do that explicitly, and due to some technical restraints I couldn’t compose the required image in another buffer (which would let me to clip it implicitly).

After some research I solved my problem (probably inventing the wheel again ;)), so I present the solution here in hope it will be useful. The example is in Delphi but it’s simple enough and could be easily ported to other languages (the code for IntersectRect() can be found in the downloadable source code).

To clip an image we need a clipping rectangle (ClipRect). What I do is find the intersection of this rectangle and a target rectangle – the location that would be occupied by the image if it wasn’t clipped. Knowing the intersection I can calculate the source rectangle – the portion of image that should actually be shown – and copy it to the intersection rectangle.

TargetRect.Left:=100; //example, should be target x coordinate
TargetRect.Top:=100; //y
TargetRect.Bottom:=TargetRect.Top+imgSource.Height;
TargetRect.Right:=TargetRect.Left+imgSource.Width;

if IntersectRect(ClippedRect,ClipRect,TargetRect) then begin
   //If the target rectangle and clipping rectangle intersect,
   //use the intersection to find out from what part of
   //image should we copy the data
   SourceRect.Left:=ClippedRect.Left-TargetRect.Left;
   SourceRect.Top:=ClippedRect.Top-TargetRect.Top;
   SourceRect.Right:=SourceRect.Left + ClippedRect.Right – ClippedRect.Left;
   SourceRect.Bottom:=SourceRect.Top + ClippedRect.Bottom – ClippedRect.Top;
   //show only the neccessary part of the source image
   Canvas.CopyRect(ClippedRect,imgSource.Canvas,SourceRect);
end;

Download
Clipping Example : wsclipping.rar (40 Kb)
Required : Delphi 7 (probably works with older versions, too)

Related posts :

Leave a Reply