### Install Cropper.Blazor Package
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/NuGet_README.md
This command adds the Cropper.Blazor package to your Blazor project. Ensure you have a compatible .NET version installed.
```bash
dotnet add package Cropper.Blazor
```
--------------------------------
### Get Image and Canvas Data (C#)
Source: https://context7.com/cropperblazor/cropper.blazor/llms.txt
Provides examples of retrieving detailed image information (position, size, natural dimensions, aspect ratio, rotation, scale) using GetImageDataAsync and canvas (image wrapper) data (position, size, natural dimensions) using GetCanvasDataAsync in Cropper.Blazor. It also shows how to get container dimensions with GetContainerDataAsync.
```csharp
private CropperComponent? cropperComponent;
private async Task GetImageInfo() {
// Get image data
ImageData imageData = await cropperComponent!.GetImageDataAsync();
Console.WriteLine($"Image Position: Left={imageData.Left}, Top={imageData.Top}");
Console.WriteLine($"Image Size: {imageData.Width}x{imageData.Height}");
Console.WriteLine($"Natural Size: {imageData.NaturalWidth}x{imageData.NaturalHeight}");
Console.WriteLine($"Aspect Ratio: {imageData.AspectRatio}");
Console.WriteLine($"Rotation: {imageData.Rotate} degrees");
Console.WriteLine($"Scale: X={imageData.ScaleX}, Y={imageData.ScaleY}");
}
private async Task GetCanvasInfo() {
// Get canvas (image wrapper) data
CanvasData canvasData = await cropperComponent!.GetCanvasDataAsync();
Console.WriteLine($"Canvas Position: Left={canvasData.Left}, Top={canvasData.Top}");
Console.WriteLine($"Canvas Size: {canvasData.Width}x{canvasData.Height}");
Console.WriteLine($"Natural Canvas Size: {canvasData.NaturalWidth}x{canvasData.NaturalHeight}");
}
private async Task GetContainerInfo() {
// Get container data
ContainerData containerData = await cropperComponent!.GetContainerDataAsync();
Console.WriteLine($"Container Size: {containerData.Width}x{containerData.Height}");
}
```
--------------------------------
### Blazor Resource Loading with Brotli Decompression
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/src/Cropper.Blazor/Client/wwwroot/index.html
Configures Blazor to load resources, prioritizing Brotli-compressed files for faster downloads. It includes logic to decompress these files using BrotliDecode and sets the appropriate content type, especially for WebAssembly binaries. This is particularly useful for static hosting environments that may not support Brotli natively.
```javascript
Blazor.start({ loadBootResource: function (type, name, defaultUri, integrity) { // For framework resources, use the precompressed .br files for faster downloads // This is needed only because GitHub pages doesn't natively support Brotli (or even gzip for .dll files) if (type !== 'dotnetjs' && location.hostname !== 'localhost') { return (async function () { const response = await fetch(defaultUri + '.br', { cache: 'no-cache' }); if (!response.ok) { alert(`Failed to fetch ${name}: ${response.statusText}`); throw new Error(response.statusText); } const originalResponseBuffer = await response.arrayBuffer(); const originalResponseArray = new Int8Array(originalResponseBuffer); const decompressedResponseArray = BrotliDecode(originalResponseArray); const contentType = type === 'dotnetwasm' ? 'application/wasm' : 'application/octet-stream'; return new Response(decompressedResponseArray, { headers: { 'content-type': contentType } }); })(); } } });
```
--------------------------------
### Using Open Iconic Icon Font Standalone
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/examples/Cropper.Blazor.Server.Net7/wwwroot/css/open-iconic/README.md
This example shows how to link the default Open Iconic stylesheet for standalone use. The subsequent HTML snippet illustrates displaying an icon using the 'oi' class and the 'data-glyph' attribute for specifying the icon.
```html
```
```html
```
--------------------------------
### Add HTML/CSS References for Cropper.Blazor
Source: https://context7.com/cropperblazor/cropper.blazor/llms.txt
Includes the necessary CSS and JavaScript references for Cropper.Blazor in your main HTML file. This setup is required for both Blazor WebAssembly/MAUI and Blazor Server applications.
```html
```
--------------------------------
### Load Raw Assets using FileSystem API
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/examples/Cropper.Blazor.MAUI.Net6/Resources/Raw/AboutAssets.txt
This C# code demonstrates how to load raw assets that have been deployed with your .NET MAUI application. It uses `FileSystem.OpenAppPackageFileAsync` to get a stream to the asset and `StreamReader` to read its contents. Ensure the file name matches the `LogicalName` specified in the .csproj.
```csharp
async Task LoadMauiAsset()
{
using var stream = await FileSystem.OpenAppPackageFileAsync("AboutAssets.txt");
using var reader = new StreamReader(stream);
var contents = reader.ReadToEnd();
}
```
--------------------------------
### Using Open Iconic SVG Sprite
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/examples/Cropper.Blazor.Server.Net9/wwwroot/css/open-iconic/README.md
Illustrates the usage of Open Iconic's SVG sprite for efficient icon display. This method allows loading all icons with a single request. It includes examples for styling icon size and color.
```html
```
```css
.icon {
width: 16px;
height: 16px;
}
```
```css
.icon-account-login {
fill: #f00;
}
```
--------------------------------
### Retrieve and Set Crop Box Data (C#)
Source: https://context7.com/cropperblazor/cropper.blazor/llms.txt
Illustrates how to get the current crop box data (position and size) using GetCropBoxDataAsync and how to set new crop box dimensions and position using SetCropBoxData in Cropper.Blazor. The SetCropBoxData method accepts an options object to define the new properties.
```csharp
private CropperComponent? cropperComponent;
private async Task GetAndModifyCropBox() {
// Get current crop box data
CropBoxData cropBoxData = await cropperComponent!.GetCropBoxDataAsync();
Console.WriteLine($"Crop Box Position: Left={cropBoxData.Left}, Top={cropBoxData.Top}");
Console.WriteLine($"Crop Box Size: {cropBoxData.Width}x{cropBoxData.Height}");
// Center the crop box horizontally
var newCropBoxData = new SetCropBoxDataOptions() {
Left = 100, // New left position
Top = 50, // New top position
Width = 300, // New width
Height = 200 // New height
};
cropperComponent!.SetCropBoxData(newCropBoxData);
}
private void SetCropBoxToFullWidth() {
// Set crop box to span full width
cropperComponent!.SetCropBoxData(new SetCropBoxDataOptions() {
Left = 0,
Width = 500
});
}
```
--------------------------------
### Set Crop Area and Transformations in Blazor
Source: https://context7.com/cropperblazor/cropper.blazor/llms.txt
This C# code demonstrates how to use the `SetData` method of the Cropper.Blazor component to change the cropped area's position, size, rotation, and scale. It includes examples for applying specific crop dimensions and applying transformations like flipping and rotation.
```csharp
@code {
private CropperComponent? cropperComponent;
private void ApplyCropData()
{
// Set specific crop area position and dimensions
var newCropData = new SetDataOptions()
{
X = 100, // Left offset from original image
Y = 50, // Top offset from original image
Width = 400, // Crop area width
Height = 300, // Crop area height
Rotate = 0, // No rotation
ScaleX = 1, // No horizontal flip
ScaleY = 1 // No vertical flip
};
cropperComponent!.SetData(newCropData);
}
private void FlipAndRotate()
{
// Apply transformations: flip horizontally and rotate 45 degrees
var transformData = new SetDataOptions()
{
Rotate = 45, // Rotate 45 degrees clockwise
ScaleX = -1, // Flip horizontally
ScaleY = 1 // Keep vertical orientation
};
cropperComponent!.SetData(transformData);
}
}
```
--------------------------------
### Using Open Iconic SVG Sprite
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/examples/Cropper.Blazor.Server.Net8/wwwroot/css/open-iconic/README.md
Illustrates the usage of Open Iconic's SVG sprite for displaying icons. This approach allows for a single request to load all icons, similar to icon fonts but with SVG benefits. It includes examples for applying general and specific classes for styling.
```html
```
```css
.icon {
width: 16px;
height: 16px;
}
.icon-account-login {
fill: #f00;
}
```
--------------------------------
### Integrating Open Iconic with Bootstrap
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/examples/Cropper.Blazor.Server.Net7/wwwroot/css/open-iconic/README.md
This snippet shows how to link the Open Iconic Bootstrap stylesheet for seamless integration. The subsequent HTML example demonstrates using the provided classes to display an icon within a span element, including title and aria-hidden attributes.
```html
```
```html
```
--------------------------------
### Using Open Iconic SVG Sprite
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/examples/Cropper.Blazor.Server.Net7/wwwroot/css/open-iconic/README.md
This example shows how to utilize Open Iconic's SVG sprite for efficient icon display. It suggests adding a general class to the SVG and specific classes to the 'use' tag for styling. The 'xlink:href' attribute points to the SVG sprite and the icon ID.
```html
```
--------------------------------
### Get Cropped Canvas Asynchronously in Background (C#)
Source: https://context7.com/cropperblazor/cropper.blazor/llms.txt
Retrieves the cropped canvas asynchronously in the background using a callback function to handle the result. This method is useful for long-running cropping operations without blocking the UI thread. It takes options for cropping and a callback delegate that receives the cropped canvas and a cancellation token.
```csharp
private CropperComponent? cropperComponent;
private string? croppedImageUrl;
private async Task GetCroppedCanvasWithCallback()
{
var options = new GetCroppedCanvasOptions()
{
MaxWidth = 2048,
MaxHeight = 2048,
ImageSmoothingEnabled = true,
ImageSmoothingQuality = "medium"
};
// Start background processing with callback
CroppedCanvasReceiver receiver = await cropperComponent!
.GetCroppedCanvasInBackgroundAsync(
options,
onReceive: async (croppedCanvas, cancellationToken) =>
{
// This callback is invoked when cropping is complete
string dataUrl = croppedCanvas.ToDataURL("image/png", 1.0f);
await InvokeAsync(() =>
{
croppedImageUrl = dataUrl;
StateHasChanged();
});
}
);
// Optionally wait for completion
// await receiver.WaitForCompletionAsync();
}
```
--------------------------------
### Configure Cropper.Blazor Options
Source: https://context7.com/cropperblazor/cropper.blazor/llms.txt
Demonstrates how to configure Cropper.Blazor using the Options class. This includes setting aspect ratios, view modes, drag modes, and various visual constraints. The Options class allows for fine-grained control over the cropping experience.
```csharp
using Cropper.Blazor.Models;
// Basic cropping options with fixed aspect ratio
var portraitOptions = new Options()
{
AspectRatio = 3m / 4m, // Portrait aspect ratio
ViewMode = ViewMode.Vm1, // Restrict crop box to canvas size
AutoCrop = true, // Enable automatic cropping on init
AutoCropArea = 0.8m // 80% of image area
};
// Free-form cropping with all features enabled
var advancedOptions = new Options()
{
AspectRatio = null, // Free aspect ratio (no restriction)
InitialAspectRatio = 1m, // Start with square selection
ViewMode = ViewMode.Vm0, // No restrictions
DragMode = "crop", // Default drag creates crop box
Movable = true, // Allow image movement
Rotatable = true, // Allow rotation
Scalable = true, // Allow scaling
Zoomable = true, // Allow zooming
ZoomOnTouch = true, // Enable pinch zoom on touch devices
ZoomOnWheel = true, // Enable mouse wheel zoom
WheelZoomRatio = 0.1m, // 10% zoom per wheel tick
CropBoxMovable = true, // Allow crop box dragging
CropBoxResizable = true, // Allow crop box resizing
ToggleDragModeOnDblclick = true, // Double-click toggles drag mode
Guides = true, // Show dashed guide lines
Center = true, // Show center indicator
Highlight = true, // Highlight crop area
Background = true, // Show grid background
Modal = true, // Show dark modal overlay
CheckCrossOrigin = true, // Handle cross-origin images
CheckOrientation = true, // Check EXIF orientation
Responsive = true, // Re-render on window resize
Restore = true, // Restore crop area after resize
MinContainerWidth = 200, // Minimum container width
MinContainerHeight = 100, // Minimum container height
MinCanvasWidth = 0, // Minimum canvas width
MinCanvasHeight = 0, // Minimum canvas height
MinCropBoxWidth = 50, // Minimum crop box width
MinCropBoxHeight = 50 // Minimum crop box height
};
// Options with preview element selector
var previewOptions = new Options()
{
AspectRatio = 1m, // Square aspect ratio
Preview = ".preview-container", // CSS selector for preview elements
ViewMode = ViewMode.Vm2 // Fit canvas within container
};
```
--------------------------------
### Add Cropper.Blazor Service Registration in Program.cs
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/README.md
Register the Cropper.Blazor services in your `Program.cs` file using `AddCropper()`. This makes the cropper functionality available throughout your application.
```csharp
using Cropper.Blazor.Extensions;
builder.Services.AddCropper();
```
--------------------------------
### Configure Cropper.Blazor JS Interop Path in Program.cs
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/README.md
Optionally, you can override the default path to the `cropperJSInterop.min.js` module if it's located elsewhere. This is done by providing `CropperJsInteropOptions` during service registration.
```csharp
builder.Services.AddCropper(new CropperJsInteropOptions()
{
DefaultInternalPathToCropperModule = "/_content/Cropper.Blazor/cropperJsInterop.min.js"
})
```
```csharp
builder.Services.AddCropper(new CropperJsInteropOptions()
{
IsActiveGlobalPath = true,
GlobalPathToCropperModule = "/_content/Cropper.Blazor/cropperJsInterop.min.js"
})
```
--------------------------------
### Manage Cropper Lifecycle with Cropper.Blazor
Source: https://context7.com/cropperblazor/cropper.blazor/llms.txt
Provides methods to manage the lifecycle and state of the cropper instance, including enabling/disabling interactions, resetting to initial states, clearing the crop box, manually showing the crop box, and destroying the instance to clean up resources.
```csharp
@code {
private CropperComponent? cropperComponent;
private void EnableCropper()
{
// Unfreeze the cropper to allow interactions
cropperComponent!.Enable();
}
private void DisableCropper()
{
// Freeze the cropper to prevent any interactions
cropperComponent!.Disable();
}
private void ResetCropper()
{
// Reset image and crop box to initial states
cropperComponent!.Reset();
}
private void ClearCropBox()
{
// Clear/hide the crop box
cropperComponent!.Clear();
}
private void ShowCropBox()
{
// Show the crop box manually (useful after Clear)
cropperComponent!.Crop();
}
private void DestroyCropper()
{
// Destroy the cropper instance and cleanup resources
cropperComponent!.Destroy();
}
}
```
--------------------------------
### Register Cropper.Blazor Services in Program.cs
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/NuGet_README.md
This C# code demonstrates how to add the Cropper.Blazor services to your application's dependency injection container. This is a mandatory step for using the component.
```csharp
using Cropper.Blazor.Extensions;
// ...
builder.Services.AddCropper();
```
--------------------------------
### Dynamically Set Crop Box Aspect Ratio (C#)
Source: https://context7.com/cropperblazor/cropper.blazor/llms.txt
Shows how to dynamically change the aspect ratio of the crop box during runtime using the SetAspectRatio method in Cropper.Blazor. This method accepts a decimal value representing the desired width-to-height ratio.
```csharp
private CropperComponent? cropperComponent;
private void SetSquareAspectRatio() {
// 1:1 square aspect ratio
cropperComponent!.SetAspectRatio(1m);
}
private void Set16By9AspectRatio() {
// 16:9 widescreen aspect ratio
cropperComponent!.SetAspectRatio(16m / 9m);
}
private void Set4By3AspectRatio() {
// 4:3 standard aspect ratio
cropperComponent!.SetAspectRatio(4m / 3m);
}
private void SetPortraitAspectRatio() {
// 3:4 portrait aspect ratio
cropperComponent!.SetAspectRatio(3m / 4m);
}
private void SetCustomAspectRatio(decimal width, decimal height) {
// Custom aspect ratio based on dimensions
cropperComponent!.SetAspectRatio(width / height);
}
```
--------------------------------
### Configure Cropper.Blazor JavaScript Module Path
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/NuGet_README.md
These C# snippets show how to customize the path to the Cropper.Blazor JavaScript interop module. This is useful if the default path needs to be overridden.
```csharp
builder.Services.AddCropper(new Cropper.Blazor.CropperJsInteropOptions()
{
DefaultInternalPathToCropperModule = "/_content/Cropper.Blazor/cropperJsInterop.min.js"
})
```
```csharp
builder.Services.AddCropper(new Cropper.Blazor.CropperJsInteropOptions()
{
IsActiveGlobalPath = true,
GlobalPathToCropperModule = "/_content/Cropper.Blazor/cropperJsInterop.min.js"
})
```
--------------------------------
### Get Cropped Canvas Data Asynchronously in Blazor
Source: https://context7.com/cropperblazor/cropper.blazor/llms.txt
This C# code shows how to retrieve cropped canvas data asynchronously using `GetCroppedCanvasDataInBackgroundAsync` in Cropper.Blazor. It allows specifying output dimensions, quality, and handling potential image processing errors. The cropped image is returned as a stream, which can then be converted to a byte array or data URL.
```csharp
@using Cropper.Blazor.Components
@using Cropper.Blazor.Models
@using Cropper.Blazor.Exceptions
@code {
private CropperComponent? cropperComponent;
private async Task GetCroppedImage()
{
var options = new GetCroppedCanvasOptions()
{
Width = 800, // Output width
Height = 600, // Output height
MinWidth = 100, // Minimum output width
MinHeight = 100, // Minimum output height
MaxWidth = 4096, // Maximum output width
MaxHeight = 4096, // Maximum output height
FillColor = "transparent", // Background fill color
ImageSmoothingEnabled = true, // Enable anti-aliasing
ImageSmoothingQuality = "high", // Quality: low, medium, high
Rounded = false // Use precise values
};
try
{
// Get cropped image data in background with chunked transfer
ImageReceiver imageReceiver = await cropperComponent!
.GetCroppedCanvasDataInBackgroundAsync(
options,
type: "image/png",
number: 1.0f, // Quality (0-1)
maximumReceiveChunkSize: 32768 // 32KB chunks
);
// Retrieve the image as a stream
using MemoryStream imageStream = await imageReceiver.GetImageChunkStreamAsync();
byte[] imageBytes = imageStream.ToArray();
// Convert to data URL for display
string dataUrl = $"data:image/png;base64,{Convert.ToBase64String(imageBytes)}";
Console.WriteLine($"Cropped image size: {imageBytes.Length} bytes");
}
catch (ImageProcessingException ex)
{
Console.WriteLine($"Error processing image: {ex.Message}");
}
}
private async Task GetJpegWithCompression()
{
var options = new GetCroppedCanvasOptions()
{
MaxWidth = 1920,
MaxHeight = 1080
};
// Get JPEG with 80% quality
ImageReceiver receiver = await cropperComponent!
.GetCroppedCanvasDataInBackgroundAsync(
options,
type: "image/jpeg",
number: 0.8f // 80% quality for smaller file size
);
using var stream = await receiver.GetImageChunkStreamAsync();
// Process stream...
}
}
```
--------------------------------
### Retrieve Cropper.Blazor Crop Data with GetDataAsync
Source: https://context7.com/cropperblazor/cropper.blazor/llms.txt
Demonstrates how to asynchronously retrieve the final cropped area's position and size data using the GetDataAsync method. This method can return either rounded or precise values for the crop coordinates and dimensions.
```csharp
@code {
private CropperComponent? cropperComponent;
private async Task GetCropData()
{
// Get crop data with rounded values
CropperData roundedData = await cropperComponent!.GetDataAsync(rounded: true);
Console.WriteLine($"Rounded - X: {roundedData.X}, Y: {roundedData.Y}");
Console.WriteLine($"Size: {roundedData.Width}x{roundedData.Height}");
Console.WriteLine($"Rotation: {roundedData.Rotate}");
Console.WriteLine($"Scale: X={roundedData.ScaleX}, Y={roundedData.ScaleY}");
// Get precise crop data without rounding
CropperData preciseData = await cropperComponent!.GetDataAsync(rounded: false);
Console.WriteLine($"Precise - X: {preciseData.X}, Y: {preciseData.Y}");
}
}
```
--------------------------------
### Handle Image Uploads with IUrlImageInterop in Cropper.Blazor
Source: https://context7.com/cropperblazor/cropper.blazor/llms.txt
Demonstrates using the `IUrlImageInterop` service to handle image uploads. It converts uploaded files into blob URLs using `GetImageUsingStreamingAsync`, revokes previous URLs to manage memory, and then uses `ReplaceAsync` to update the cropper with the new image.
```csharp
@using Cropper.Blazor.Services
@using Microsoft.AspNetCore.Components.Forms
@inject IUrlImageInterop UrlImageInterop
@code {
private CropperComponent? cropperComponent;
private string? currentImageUrl;
private async Task HandleFileUpload(InputFileChangeEventArgs e)
{
var imageFile = e.File;
if (imageFile != null)
{
// Revoke previous blob URL to free memory
if (!string.IsNullOrEmpty(currentImageUrl))
{
await UrlImageInterop.RevokeObjectUrlAsync(currentImageUrl);
}
// Create blob URL from uploaded file stream
currentImageUrl = await UrlImageInterop.GetImageUsingStreamingAsync(
imageFile,
maxAllowedSize: imageFile.Size // Allow full file size
);
// Replace cropper image with new upload
await cropperComponent!.ReplaceAsync(currentImageUrl, hasSameSize: false);
}
}
public async ValueTask DisposeAsync()
{
// Clean up blob URL on component disposal
if (!string.IsNullOrEmpty(currentImageUrl))
{
await UrlImageInterop.RevokeObjectUrlAsync(currentImageUrl);
}
}
}
```
--------------------------------
### Include Raw Assets with MauiAsset Build Action
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/examples/Cropper.Blazor.MAUI.Net6/Resources/Raw/AboutAssets.txt
This snippet shows how to configure your .csproj file to include raw assets in your .NET MAUI application. The `MauiAsset` build action ensures these files are deployed with your application package. The `LogicalName` property controls the path and name of the asset within the deployed package.
```xml
```
--------------------------------
### Add Cropper.Blazor CSS to index.html or _Host.cshtml
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/NuGet_README.md
Include the Cropper.Blazor CSS file in the head section of your main HTML file to apply styling for the cropper component. This is required for both Blazor WebAssembly/MAUI and Blazor Server/MVC applications.
```html
```
--------------------------------
### Integrating Open Iconic with Foundation
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/examples/Cropper.Blazor.Server.Net7/wwwroot/css/open-iconic/README.md
This code demonstrates linking the Open Iconic Foundation stylesheet. The following HTML snippet shows how to implement an icon using the Foundation-specific classes within a span tag, complete with accessibility attributes.
```html
```
```html
```
--------------------------------
### Add Cropper.Blazor JavaScript to index.html or _Host.cshtml
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/NuGet_README.md
Add the Cropper.Blazor JavaScript file to the body section of your main HTML file. This enables the JavaScript functionality required for the cropper component to work.
```html
```
--------------------------------
### Register Cropper Services in Program.cs
Source: https://context7.com/cropperblazor/cropper.blazor/llms.txt
Registers Cropper.Blazor services in your application's Program.cs file to enable dependency injection. This includes options for default or custom module paths and SignalR configuration for Blazor Server to handle large images.
```csharp
using Cropper.Blazor.Extensions;
var builder = WebApplication.CreateBuilder(args);
// Add cropper services with default options
builder.Services.AddCropper();
// Or with custom module path options
builder.Services.AddCropper(new CropperJsInteropOptions()
{
DefaultInternalPathToCropperModule = "/_content/Cropper.Blazor/cropperJsInterop.min.js"
});
// For Blazor Server, configure SignalR for large images
builder.Services.AddServerSideBlazor()
.AddHubOptions(options =>
{
options.MaximumReceiveMessageSize = 32 * 1024 * 100; // ~3.2MB
});
var app = builder.Build();
app.MapBlazorHub();
app.Run();
```
--------------------------------
### Import Cropper.Blazor Component
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/NuGet_README.md
This snippet shows how to import the necessary namespace for using Cropper.Blazor components in your Razor files.
```razor
@using Cropper.Blazor.Components
```
--------------------------------
### Handle Cropper Event Details
Source: https://context7.com/cropperblazor/cropper.blazor/llms.txt
This snippet demonstrates how to handle detailed cropping events, extracting width, height, rotation, and scale information. It formats the output for display or further processing.
```csharp
private void OnCrop(CroppedEventArgs e)
{
Console.WriteLine($"Width: {e.Detail.Width:F2}\n" +
$"Height: {e.Detail.Height:F2}\n" +
$"Rotate: {e.Detail.Rotate:F2}\n" +
$"ScaleX: {e.Detail.ScaleX}\n" +
$"ScaleY: {e.Detail.ScaleY}");
}
```
--------------------------------
### Displaying Open Iconic SVGs
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/examples/Cropper.Blazor.Server.Net7/wwwroot/css/open-iconic/README.md
This snippet demonstrates how to use Open Iconic's SVG files directly as images. Ensure the 'alt' attribute is used for accessibility. The path to the SVG file should be correctly specified.
```html
```
--------------------------------
### Configure Cropper.Blazor Service with Global Path Override
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/src/Cropper.Blazor/Client/Pages/ManualMarkdown/InstallServicesOverrideGlobalCode.html
This C# code snippet demonstrates how to configure the Cropper.Blazor service in a Blazor application. It shows how to use `AddCropper` with `CropperJsInteropOptions` to set `IsActiveGlobalPath` to true and specify a custom `GlobalPathToCropperModule`. This is useful when the default module path needs to be overridden.
```csharp
using Cropper.Blazor.Extensions;
// Override full global path to cropperJSInterop.min.js module
builder.Services.AddCropper(new CropperJsInteropOptions()
{
IsActiveGlobalPath = true,
GlobalPathToCropperModule = "{StartUrlWithPath}/\_content/Cropper.Blazor/cropperJsInterop.min.js"
});
```
--------------------------------
### Create Ellipse Image and Stream Chunks (JavaScript)
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/src/Cropper.Blazor/Client/Pages/Crop/Examples/BackgroundCropRoundImage_ScriptCode.html
This function takes a source canvas, a .NET reference for receiving image data, and a maximum chunk size. It draws the source image onto a new canvas, clips it to an ellipse, converts it to a PNG blob, and then streams this blob in chunks to the .NET receiver. It uses `setTimeout` to ensure asynchronous execution.
```javascript
window.getEllipseImageInBackground = (sourceCanvas, dotNetImageReceiverRef, maximumReceiveChunkSize) => {
setTimeout(() => {
const newCanvas = document.createElement('canvas')
const ctxCanvas = newCanvas.getContext('2d')
const widthCanvas = sourceCanvas.width
const heightCanvas = sourceCanvas.height
newCanvas.width = widthCanvas
newCanvas.height = heightCanvas
ctxCanvas.imageSmoothingEnabled = true
// Draw the source image
ctxCanvas.drawImage(sourceCanvas, 0, 0, widthCanvas, heightCanvas)
// Clip to ellipse
ctxCanvas.globalCompositeOperation = 'destination-in'
ctxCanvas.beginPath()
ctxCanvas.ellipse(
widthCanvas / 2,
heightCanvas / 2,
widthCanvas / 2,
heightCanvas / 2,
0,
0,
2 * Math.PI,
true
)
ctxCanvas.fill()
// Convert to blob and stream in chunks
newCanvas.toBlob(async (blob) => {
await window.cropper.readBlobInChunks(blob, dotNetImageReceiverRef, maximumReceiveChunkSize)
}, 'image/png', 1)
}, 0)
}
```
--------------------------------
### Configure Cropper.Blazor with Custom Module Path (C#)
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/src/Cropper.Blazor/Client/Pages/ManualMarkdown/InstallServicesOverrideInternalCode.html
This snippet shows how to configure Cropper.Blazor services by providing a custom path to the Cropper.js interop module. This is useful when the default path needs to be overridden. It utilizes the AddCropper extension method with CropperJsInteropOptions.
```csharp
using Cropper.Blazor.Extensions;
// Override internal path to cropperJSInterop.min.js module
builder.Services.AddCropper(new CropperJsInteropOptions()
{
DefaultInternalPathToCropperModule = "{YourPath}/\_content/Cropper.Blazor/cropperJsInterop.min.js"
});
```
--------------------------------
### Scale and Flip Image (C#)
Source: https://context7.com/cropperblazor/cropper.blazor/llms.txt
Applies scaling transformations to flip or resize the image horizontally and/or vertically. The `ScaleX` and `ScaleY` methods control individual axis scaling, while `Scale` can apply simultaneous scaling to both axes. This is used for effects like flipping the image.
```csharp
private CropperComponent? cropperComponent;
private decimal currentScaleX = 1m;
private decimal currentScaleY = 1m;
private void FlipHorizontal()
{
// Toggle horizontal flip
currentScaleX = currentScaleX == 1m ? -1m : 1m;
cropperComponent!.ScaleX(currentScaleX);
}
private void FlipVertical()
{
// Toggle vertical flip
currentScaleY = currentScaleY == 1m ? -1m : 1m;
cropperComponent!.ScaleY(currentScaleY);
}
private void FlipBoth()
{
// Flip both horizontally and vertically (180 degree rotation effect)
cropperComponent!.Scale(-1m, -1m);
}
private void ResetScale()
{
// Reset to original orientation
currentScaleX = 1m;
currentScaleY = 1m;
cropperComponent!.Scale(1m, 1m);
}
```
--------------------------------
### Configure Blazor Server-Side Hub Options
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/src/Cropper.Blazor/Client/Pages/ManualMarkdown/InstallServicesForBlazorServerManualCode.html
Configures the Blazor Server-side application to set the maximum receive message size for the Hub. This is useful for applications that might transfer large amounts of data, such as image data for Cropper.Blazor. It requires access to the WebApplication builder and its services.
```csharp
using Cropper.Blazor.Extensions;
builder.Services.AddServerSideBlazor()
.AddHubOptions(options =>
{
options.MaximumReceiveMessageSize = 32 * 1024 * 100;
});
app.MapBlazorHub();
```
--------------------------------
### Use CropperComponent in Razor File
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/NuGet_README.md
This Razor code demonstrates how to integrate the CropperComponent into your Blazor pages. It includes various attributes for customization and event handling, such as setting the image source, input attributes, and event callbacks.
```razor
```
--------------------------------
### Configure SignalR for Server-Side Blazor
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/NuGet_README.md
For server-side Blazor applications, this C# code configures SignalR, including increasing the maximum receive message size for hub messages and mapping the SignalR hub. This is crucial for handling potentially large image data.
```csharp
builder.Services.AddServerSideBlazor()
.AddHubOptions(options =>
{
options.MaximumReceiveMessageSize = 32 * 1024 * 100;
});
app.MapBlazorHub();
```
--------------------------------
### Generate Polygon Image from Canvas (JavaScript)
Source: https://github.com/cropperblazor/cropper.blazor/blob/dev/src/Cropper.Blazor/Client/Pages/Crop/Examples/CropPolygonImage_ScriptCode.html
This function takes a source canvas and a path array to create a new canvas with a polygon-shaped cropped image. It scales coordinates based on the source canvas dimensions and returns the cropped image as a PNG data URL. Dependencies include the browser's Canvas API.
```javascript
window.getPolygonImage = (sourceCanvas, path) => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const width = sourceCanvas.width,
height = sourceCanvas.height;
canvas.width = width;
canvas.height = height;
context.imageSmoothingEnabled = true;
context.beginPath();
context.moveTo(path[0] * width / 100, path[1] * height / 100);
context.fillStyle = "rgba(255, 255, 255, 0)";
for (let i = 2; i < path.length; i += 2) {
context.lineTo(path[i] * width / 100, path[i + 1] * height / 100);
}
context.closePath();
context.clip();
context.fill();
context.globalCompositeOperation = 'lighter';
context.drawImage(sourceCanvas, 0, 0, width, height);
return canvas.toDataURL("image/png", 1);
}
```
--------------------------------
### Render CropperComponent with Interactive Features in Blazor
Source: https://context7.com/cropperblazor/cropper.blazor/llms.txt
This Blazor Razor component demonstrates the usage of CropperComponent for rendering an interactive image cropper. It showcases various configuration options for aspect ratio, view mode, drag mode, and image manipulation (movable, rotatable, scalable, zoomable). It also includes event handlers for cropping actions, image loading, and error handling.
```razor
@page "/crop"
@using Cropper.Blazor.Components
@using Cropper.Blazor.Models
@using Cropper.Blazor.Events
@code {
private CropperComponent? cropperComponent;
private string imageSource = "https://example.com/sample-image.jpg";
private bool isImageError = false;
private Options cropperOptions = new Options()
{
AspectRatio = 16m / 9m,
ViewMode = ViewMode.Vm1,
DragMode = "crop",
AutoCrop = true,
AutoCropArea = 0.8m,
Movable = true,
Rotatable = true,
Scalable = true,
Zoomable = true,
ZoomOnWheel = true,
WheelZoomRatio = 0.1m,
CropBoxMovable = true,
CropBoxResizable = true,
Guides = true,
Center = true,
Highlight = true,
Background = true
};
private Dictionary inputAttributes = new()
{
{ "loading", "lazy" },
{ "alt", "Image to crop" }
};
private void OnCropperReady(JSEventData e)
=> Console.WriteLine("Cropper is ready");
private void OnCrop(JSEventData e)
=> Console.WriteLine($"Crop: X={e.Detail?.X}, Y={e.Detail?.Y}, Width={e.Detail?.Width}, Height={e.Detail?.Height}");
private void OnCropStart(JSEventData e)
=> Console.WriteLine($"Crop started: {e.Detail?.ActionEvent}");
private void OnCropEnd(JSEventData e)
=> Console.WriteLine($"Crop ended: {e.Detail?.ActionEvent}");
private void OnCropMove(JSEventData e)
=> Console.WriteLine($"Crop moving: {e.Detail?.ActionEvent}");
private void OnZoom(JSEventData e)
=> Console.WriteLine($"Zoom: OldRatio={e.Detail?.OldRatio}, NewRatio={e.Detail?.Ratio}");
private void OnImageLoaded()
=> Console.WriteLine("Image loaded successfully");
private void OnImageLoadError(ErrorEventArgs e)
{
isImageError = true;
StateHasChanged();
}
}
```
--------------------------------
### Move Canvas with Offsets or Absolute Position (C#)
Source: https://context7.com/cropperblazor/cropper.blazor/llms.txt
Demonstrates how to move the image canvas using relative offsets (Move) or to an absolute position (MoveTo) in Cropper.Blazor. The Move method takes X and Y offsets, while MoveTo sets the canvas to a specific coordinate.
```csharp
private CropperComponent? cropperComponent;
private void MoveLeft() {
// Move image 10 pixels to the left
cropperComponent!.Move(-10, 0);
}
private void MoveRight() {
// Move image 10 pixels to the right
cropperComponent!.Move(10, 0);
}
private void MoveUp() {
// Move image 10 pixels up
cropperComponent!.Move(0, -10);
}
private void MoveDown() {
// Move image 10 pixels down
cropperComponent!.Move(0, 10);
}
private void MoveDiagonal() {
// Move image diagonally (50px right, 30px down)
cropperComponent!.Move(50, 30);
}
private void MoveToCenter() {
// Move canvas to absolute position (0, 0) - top-left
cropperComponent!.MoveTo(0, 0);
}
private void MoveToPosition(decimal x, decimal y) {
// Move canvas to specific absolute position
cropperComponent!.MoveTo(x, y);
}
```