Skip to content

MEStackCodes/Delphi.FMX.UImageCropper

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

TUImageCropper

A modern, mobile-oriented image cropper for Delphi FireMonkey (FMX) featuring auto-zoom, dynamic centered cropbox, and rendering powered by Skia4Delphi.

This is the modern standard for mobile devices because it enables precise crops, lockable aspect ratios, and clear visual feedback for all image areas, especially near the boundaries.


✨ Key Advantages

  • Fluid Touch Gestures: Seamless control of the image (pan, zoom, and double tap). It also allows you to easily plug in custom visual controls for crop ratio, rotation, and mirroring.
  • Precise Visual Feedback: The user always sees a well-defined crop area, while the dimming mask surrounding it clearly indicates which parts of the image will be discarded.
  • Flexible Cropping Grid: The cropbox can be dynamically resized from both the corners and the edges.
  • Lockable Aspect Ratios: Easily lock specific proportions (e.g., 1:1, 4:3, 16:9) or let the user resize it freely.
  • Smart Boundary Snapping: The image is anchored to the cropbox. When a user selects an area close to the edges, the viewport smoothly disengages from the screen boundaries and centers itself within the cropbox for optimal visibility and precision.

Auto-Zoom Feature



Manual Pinch-to-Zoom and Pan Feature


⚙️ Technical Features

  • Cross-Platform FMX: Written in FMX (FireMonkey) and integrated with Skia4Delphi.
  • Flexible Integration: Use it directly as source code within your project or install it into the Delphi Component Palette.
  • Wide Format Support: Supports all image formats handled by the FMX Codec Manager (primarily JPG, PNG, BMP).
  • Asynchronous Operations: Asynchronous image loading and cropping tasks prevent main UI thread blocks, keeping your application highly responsive.
  • Resource Efficient: Saves memory by processing a lightweight sample/preview image in memory, while the original high-resolution file is safely managed in a cache file.
  • Highly Customizable: Easily adapt its behavior, colors, and functionality through its built-in properties and events.

🚀 Getting Started

Prerequisites

  • Delphi 12/13 (FMX framework)
  • Skia4Delphi installed and enabled in your project.

Basic Usage

Follow these steps to integrate and use the TUImageCropper component in your FMX application:

  1. Create and initialize the component at runtime with Default Settings:

     uses
        FMX.UICropperTypes,
        FMX.UImageCropper;
        
     private 
        FImageCropper: TUImageCropper;
        ...
    begin
        FImageCropper := TUImageCropper.Create(Self);
        FImageCropper.Parent := CropperContainer; // Assign the visual container
        FImageCropper.Align := TAlignLayout.Client;
    end;
  2. Assign event handlers (Some are optional but recommended):

        FImageCropper.OnImageLoad := OnImageLoadHandler;
        FImageCropper.OnImageLoaded := OnImageLoadedHandler;
        FImageCropper.OnCropImage:= OnCropImageHandler;
        FImageCropper.OnImageCropped:= OnImageCroppedHandler;
        FImageCropper.OnImageError := OnImageErrorHandler;
        FImageCropper.OnCropCancel:= OnCropCancelHandler;
  3. Load an image from a TBitmap asynchronously:

        FImageCropper.LoadImageFromBitmapAsync(Bitmap);

Notes:

  • You can load images from file using LoadImageFromFileAsync('path/to/file.jpg').
  • Use the event handlers to manage loading states, errors, and crop results.
  • Preview the image before cropping with ShowCropPreview and CancelCropPreview.
  • The maximum size limit for a TBitmap in FMX is 8000x8000 (approximately 64MP).

Example: Cropping an Image and Retrieving the Cropped File

This example demonstrates how to start the cropping operation, handle the crop completion event, and retrieve the cropped file path.

procedure TForm1.StartCropping;
begin
	// Start the asynchronous cropping operation
	FImageCropper.CropImageAsync;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
	// Assign the event handler for when the image has been cropped
	FImageCropper.OnImageCropped := OnImageCroppedHandler;
end;

procedure TForm1.OnImageCroppedHandler(Sender: TObject);
var
	CroppedFileName: string;
begin
	// Try to get the cropped image file name
	if FImageCropper.TryGetCroppedImage(CroppedFileName) then
	begin
		ShowMessage('Cropped image saved at: ' + CroppedFileName);
		// You can now use the cropped file as needed
	end
	else
		ShowMessage('No cropped image available.');
end;

Notes:

  • To get the cropped image, use the TryGetCroppedImage method after cropping.
  • Use the event handlers to manage loading states, errors, and crop results.

Example: Profile Image Crop with Minimum and Maximum Size

This example shows how to configure a profile image crop with a square aspect ratio, minimum required image dimensions, and a maximum output size.

Suppose a profile picture is required with a minimum size of 256x256 and a maximum of 1024x1024. The adjustments are made accordingly.

procedure TForm1.SetupProfileImageCrop;
begin
  // Require the source image to be at least 450x450 pixels
  FImageCropper.ImageSettings.MinReqWidth := 450;
  FImageCropper.ImageSettings.MinReqHeight := 450;

  // Ensure the final cropped image is at least 256x256 pixels
  FImageCropper.MinPixelsWidth := 256;
  FImageCropper.MinPixelsHeight := 256;

  // Use a square crop box for profile images
  FImageCropper.CropBoxSettings.AspectRatio := TUICropRatio.Square;

end;

procedure TForm1.CropProfileImage;
begin
  // Crop the image and limit the result to a maximum of 1024x1024 pixels
  FImageCropper.CropImageAsync(1024, 1024);
end;

How it works:

  • ImageSettings.MinReqWidth and ImageSettings.MinReqHeight force a minimum source image size.
  • CropBoxSettings.AspectRatio := TUICropRatio.Square keeps the crop box square for profile avatars.
  • MinPixelsWidth and MinPixelsHeight guarantee the cropped result is not smaller than 256x256.
  • CropImageAsync(1024, 1024) resizes the final cropped image to a maximum of 1024x1024.

Example: Customizing Crop Box Colors and Borders

This example shows how to change the crop box border color and handle color using the CropBoxSettings property of TUImageCropper.

procedure TForm1.CustomizeCropBox;
begin
	// Set the crop box border color
	FImageCropper.CropBoxSettings.Color := TAlphaColorRec.Red;

	// Set the crop box handle color (corners)
	FImageCropper.CropBoxSettings.HandleColor := TAlphaColorRec.Blue;

	// Set the crop box border thickness
	FImageCropper.CropBoxSettings.Thickness := 3.0;

	// Set the crop box opacity
	FImageCropper.CropBoxSettings.Opacity := 0.8;
end;

How it works:

  • Use the CropBoxSettings.Color property to change the border color of the crop box.
  • Use the CropBoxSettings.HandleColor property to change the color of the corner handles.
  • Adjust Thickness and Opacity for further customization of the crop box appearance.

Methods

This table lists the main public methods of the TUImageCropper component.

Method Description
CancelCrop Cancels the current cropping operation and resets the viewport.
CancelCropPreview Cancels the crop preview and returns to the main image view.
ClearViewport It's the same as CancelCrop, but this method doesn't trigger the OnCropCancel event.
CropImageAsync Starts the asynchronous cropping operation.
CropImageAsync(const AWidth, AHeight: integer) Starts the asynchronous cropping operation and force the output image to be resampled when the image crop is larger than the specified dimensions.
ShowCropPreview Displays a preview of the cropped area.
LoadImageFromBitmapAsync(const ABitmap: TBitmap) Loads an image from a TBitmap asynchronously.
LoadImageFromFileAsync(AFileName: string) Loads an image from a file asynchronously.
MirrorImage Mirrors (flips horizontally) the current image.
RotateImage90DegreesRight Rotates the image 90 degrees to the right (clockwise).
RotateImage90DegreesLeft Rotates the image 90 degrees to the left (counterclockwise).
TryGetCroppedImage(out FileName: string): Boolean Retrieves the filename of the cropped image if available. Returns true if successful.
TryGetSourceImage(out FileName: string): Boolean Retrieves the filename of the source image if available. Returns true if successful.

Properties

This table describes the public and published properties of the TUImageCropper class, which configures the main Image Cropper component.

Property Type Description
IsImageZoomed Boolean (read-only) Returns true if the image is currently zoomed in beyond its minimum scale.
IsTouchZooming Boolean (read-only) Returns true if a touch zoom gesture is currently active.
IsImageRotated Boolean (read-only) Returns true if the image has been rotated.
IsMirroredImage Boolean (read-only) Returns true if the image is currently mirrored horizontally.
ImageScale Single The current scale (zoom level) of the image.
ImageOffsetX Single The current horizontal offset of the image.
ImageOffsetY Single The current vertical offset of the image.
CropBoxCenterX Single The X coordinate of the crop box center.
CropBoxCenterY Single The Y coordinate of the crop box center.
CropBoxWidth Single The width of the crop box.
CropBoxHeight Single The height of the crop box.
ImageSample ISkImage (read-only) The current image sample being displayed.
BackgroundColor TAlphaColor The background color of the cropper viewport.
CropBoxSettings TUICropBoxSettings Crop box configuration (appearance, behavior, constraints).
EnableBackground Boolean Enables or disables the background color.
EnableAutoZoom Boolean Enables or disables auto-zoom when resizing the crop box.
EnableElasticBounce Boolean Enables or disables elastic bounce effect when panning the image out of bounds.
EnableDoubleTap Boolean Enables or disables double-tap gesture for zooming.
EnableMouseWheel Boolean Enables or disables zooming with the mouse wheel.
EnablePinchZoom Boolean Enables or disables pinch-to-zoom gesture.
EnableTouchPan Boolean Enables or disables touch panning of the image.
ImageSettings TUICropperImageSettings Image loading and saving settings.
OverlaySettings TUICropperOverlaySettings Overlay layer settings (appearance, effects).
OnCropCancel TNotifyEvent Event triggered when cropping is canceled.
OnCropImage TNotifyEvent Event triggered when cropping is initiated.
OnImageCropped TNotifyEvent Event triggered when the image has been cropped.
OnImageError TUIImageErrorEvent Event triggered when an image loading or cropping error occurs.
OnImageLoad TNotifyEvent Event triggered when image loading starts.
OnImageLoaded TNotifyEvent Event triggered when image loading is complete.

Notes:

  • Properties with type TUICropBoxSettings, TUICropperImageSettings, and TUICropperOverlaySettings refer to their respective configuration objects.
  • Event properties allow you to handle user actions and errors in your application logic.
  • Read-only properties provide runtime state information about the cropper and the image.

TUICropBoxSettings API Reference

This table describes the properties of the TUICropBoxSettings class, which configures the CropBox behavior and appearance for an Image Cropper component.

Property Type Description
AspectRatio TUICropRatio The aspect ratio of the crop box.
AbsoluteOpacity Single The absolute opacity of the crop box (0.0 to 1.0).
AutoZoomThreshold Single The auto-zoom trigger threshold, as a percentage of the viewport (e.g., 0.8 = 80%).
Color TAlphaColor The color of the crop box border.
CenteringTransitionDelay Single Delay in milliseconds before the crop box recenters after resizing.
EnableEffects Boolean Enables or disables crop box effects (e.g., fadeIn, transitions).
EnableResizing Boolean Enables or disables manual resizing of the crop box.
GuidesThickness Single Thickness of the guide lines (thirds grid) inside the crop box.
GuideLinesOpacity Single Opacity of the guide lines (thirds grid).
GuideLinesFadeInDelay Single Fade-in animation delay for the guide lines.
GuideLinesFadeOutDelay Single Fade-out animation delay for the guide lines.
FadeInDelay Single Fade-in animation delay for the crop box.
FadeOutDelay Single Fade-out animation delay for the crop box.
HandleColor TAlphaColor Color of the crop box handles (corners).
HotHandleColor TAlphaColor Color of the handle when touched (active).
HotHandleThickness Single Thickness of the handle when touched (active).
HotEdgeThickness Single Thickness of the crop box edge when touched.
HandleGap Single Gap between the handle and the crop box edge.
HandleLength Single Length of the crop box handles (corners).
HandleOpacity Single Opacity of the crop box handles.
HandleThickness Single Thickness of the crop box handles.
HandleTolerance Single Touch area (in px) around the handle for easier interaction.
MinHeight Integer Minimum height in px (screen only).
MinPixelsHeight Integer Minimum crop size(Height) in px of the original image.
MinPixelsWidth Integer Minimum crop size(Width) in px of the original image.
MinWidth Integer Minimum width in px (screen only).
SafeAreaMargin Single Margin (in px) between the crop box and the viewport.
Opacity Single Opacity of the crop box border.
ShowGuideLines Boolean Whether to show the guide lines (thirds grid) inside the crop box.
Thickness Single Thickness of the crop box border.
TargetSizePercent Single Target size factor (percentage) for the crop box within the viewport after auto-zoom and centering.
Visible Boolean Whether the crop box is visible.

TUICropperOverlaySettings API Reference

This table describes the properties of the TUICropperOverlaySettings class, which configures the overlay layer for an Image Cropper component.

Property Type Description
Color TAlphaColor The color of the overlay mask that dims the area outside the crop box.
EnableEffects Boolean Enables or disables overlay effects (such as fade animations).
EnableOverlay Boolean Enables or disables the overlay layer.
MaxOpacity Single Maximum opacity value for overlay animation interpolators (when overlay darkens dynamically on crop box touch).
MinOpacity Single Minimum opacity value for overlay animation interpolators (when overlay lightens dynamically on crop box touch).
FadeInDelay Single Fade-in animation delay for the overlay appearance.
FadeOutDelay Single Fade-out animation delay for the overlay disappearance.
Opacity Single The base opacity of the overlay mask (0.0 to 1.0).

TUICropperImageSettings API Reference

This table describes the properties of the TUICropperImageSettings class, which configures the image settings for an Image Cropper component.

Property Type Description
MaxAllowHeight Integer Maximum allowed image height (in pixels) for loading into the cropper.
MaxAllowWidth Integer Maximum allowed image width (in pixels) for loading into the cropper.
MegaPixelsLimit Integer Maximum allowed image megapixels for loading into the cropper.
MinReqHeight Integer Minimum required image height (in pixels) to be accepted by the cropper.
MinReqWidth Integer Minimum required image width (in pixels) to be accepted by the cropper.
SaveCompressQuality Integer Compression quality (0-100) for saving the cropped image. Higher values mean better quality and larger file size.
SaveCompressFormat String File format for saving the cropped image (e.g., 'jpg', 'png').

Share

If you liked and found this repository useful for your projects, star it. Thank you for your support! ⭐

About

A modern, mobile-oriented image cropper for Delphi FireMonkey (FMX) featuring auto-zoom, dynamic centered cropbox, and rendering powered by Skia4Delphi.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages