An image cropper component for Angular applications with comprehensive cropping functionality
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
The CropService handles the actual image cropping operations, performing canvas manipulations to extract the selected image portion with support for transformations and various output formats.
Injectable service for performing image cropping operations.
export class CropService {
/**
* Crop image to blob format
* @param input - Crop input parameters including image, cropper position, and options
* @param output - Output type 'blob'
* @returns Promise resolving to ImageCroppedEvent with blob data, or null if cropping fails
*/
crop(input: CropInput, output: 'blob'): Promise<ImageCroppedEvent> | null;
/**
* Crop image to base64 format
* @param input - Crop input parameters including image, cropper position, and options
* @param output - Output type 'base64'
* @returns ImageCroppedEvent with base64 data, or null if cropping fails
*/
crop(input: CropInput, output: 'base64'): ImageCroppedEvent | null;
/**
* Generic crop method supporting both output types
* @param input - Crop input parameters
* @param output - Output type ('base64' | 'blob')
* @returns Promise<ImageCroppedEvent> | ImageCroppedEvent | null depending on output type
*/
crop(input: CropInput, output: OutputType): Promise<ImageCroppedEvent> | ImageCroppedEvent | null;
/**
* Calculate resize ratio based on target dimensions and options
* @param width - Current width
* @param height - Current height
* @param options - Resize options including target dimensions and scale restrictions
* @returns Resize ratio to apply
*/
getResizeRatio(width: number, height: number, options?: {
resizeToWidth?: number;
resizeToHeight?: number;
onlyScaleDown?: boolean;
}): number;
/**
* Get image quality value from options
* @param options - Options containing imageQuality setting
* @returns Quality value between 0 and 1
*/
getQuality(options?: { imageQuality?: number }): number;
}Usage Examples:
import { CropService } from 'ngx-image-cropper';
// Using the crop service directly
const cropService = new CropService();
// Crop to base64
const cropInput: CropInput = {
loadedImage: loadedImage,
cropper: { x1: 10, y1: 10, x2: 200, y2: 150 },
maxSize: { width: 400, height: 300 },
transform: { scale: 1, rotate: 0 },
options: {
format: 'png',
imageQuality: 90,
backgroundColor: '#ffffff'
}
};
const base64Result = cropService.crop(cropInput, 'base64');
if (base64Result) {
console.log('Base64 result:', base64Result.base64);
}
// Crop to blob
const blobResult = await cropService.crop(cropInput, 'blob');
if (blobResult && blobResult.blob) {
// Upload or process the blob
const formData = new FormData();
formData.append('image', blobResult.blob, 'cropped.png');
}
// Calculate resize ratio
const resizeRatio = cropService.getResizeRatio(800, 600, {
resizeToWidth: 400,
resizeToHeight: 300,
onlyScaleDown: true
});
console.log('Resize ratio:', resizeRatio);
// Get quality value
const quality = cropService.getQuality({ imageQuality: 85 });
console.log('Quality:', quality); // 0.85Input parameters required for cropping operations.
interface CropInput {
/** Loaded image data with original and transformed versions */
loadedImage: LoadedImage;
/** Cropper position coordinates */
cropper: CropperPosition;
/** Maximum size constraints */
maxSize: Dimensions;
/** Image transformation settings */
transform?: ImageTransform;
/** Cropping options */
options?: {
backgroundColor?: string;
containWithinAspectRatio?: boolean;
maintainAspectRatio?: boolean;
aspectRatio?: number;
format?: OutputFormat;
canvasRotation?: number;
imageQuality?: number;
resizeToWidth?: number;
resizeToHeight?: number;
onlyScaleDown?: boolean;
};
}Options for controlling image resizing behavior.
interface ResizeOptions {
/** Target width for resizing */
resizeToWidth?: number;
/** Target height for resizing */
resizeToHeight?: number;
/** Only scale down, never scale up */
onlyScaleDown?: boolean;
}Type definitions for crop service outputs.
type OutputType = 'base64' | 'blob';
interface ImageCroppedEvent {
/** Base64 encoded image data (when output type is 'base64') */
base64?: string | null;
/** Blob containing image data (when output type is 'blob') */
blob?: Blob | null;
/** Object URL for the blob (when output type is 'blob') */
objectUrl?: string | null;
/** Width of the cropped image */
width: number;
/** Height of the cropped image */
height: number;
/** Position of the cropper within the display */
cropperPosition: CropperPosition;
/** Position of the crop within the actual image */
imagePosition: CropperPosition;
/** Offset image position (when containWithinAspectRatio is enabled) */
offsetImagePosition?: CropperPosition;
}// Custom cropping with specific transformations
const advancedCropInput: CropInput = {
loadedImage: myLoadedImage,
cropper: { x1: 50, y1: 50, x2: 300, y2: 200 },
maxSize: { width: 800, height: 600 },
transform: {
scale: 1.2,
rotate: 15,
flipH: false,
flipV: true,
translateH: 10,
translateV: -5,
translateUnit: 'px'
},
options: {
format: 'jpeg',
imageQuality: 95,
backgroundColor: '#f0f0f0',
resizeToWidth: 512,
resizeToHeight: 384,
onlyScaleDown: false,
maintainAspectRatio: true,
containWithinAspectRatio: true
}
};
// Perform cropping with transformations
const croppedResult = await cropService.crop(advancedCropInput, 'blob');
if (croppedResult) {
console.log(`Cropped to ${croppedResult.width}x${croppedResult.height}`);
console.log('Cropper position:', croppedResult.cropperPosition);
console.log('Image position:', croppedResult.imagePosition);
if (croppedResult.offsetImagePosition) {
console.log('Offset position:', croppedResult.offsetImagePosition);
}
}
// Utility methods
const resizeRatio = cropService.getResizeRatio(1920, 1080, {
resizeToWidth: 800,
onlyScaleDown: true
});
const qualityValue = cropService.getQuality({ imageQuality: 80 });