Delphi – Crop scale and center image with delphi

cropdelphiimagescale

Does anyone know a way of cropping, scaling and centering an image (jpg or bitmap) using Delphi?
I have an image with large resolution. I would like to be able to scale it to a lower resolution. The ratio of the target resolution may be different from the original image. I want to keep the original photo aspect ratio, therefore, I don't want to stretch to the new resolution, but crop and center it, to fit best and loose minimal data from the original image. Does anyone know how can it be done using Delphi?

Best Answer

I'm guessing that you want to resize to fill the target image edge to edge, and crop the part that goes out of bounds.

Here's pseudocode. The implementation will differ depending on what you're working with.

// Calculate aspect ratios
sourceAspectRatio := souceImage.Width / sourceImage.Height;
targetAspectRatio := targetImage.Width / targetImage.Height;

if (sourceAspectRatio > targetAspectRatio) then
begin
  // Target image is narrower, so crop left and right
  // Resize source image
  sourceImage.Height := targetImage.Height;
  // Crop source image
  ..
end
else
begin
  // Target image is wider, so crop top and bottom
  // Resize source image
  sourceImage.Width := targetImage.Width;
  // Crop source image
  ..
end;
Related Topic