CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-ngx-image-cropper

An image cropper component for Angular applications with comprehensive cropping functionality

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

utility-functions.mddocs/

Utility Functions

Standalone utility functions for common image manipulation tasks including base64 conversion and canvas resizing operations.

Capabilities

Base64 to File Conversion

Convert base64 encoded image data to a Blob object for file operations.

/**
 * Convert base64 image string to Blob object
 * @param base64Image - Base64 encoded image string with data URL prefix
 * @returns Blob object containing the decoded image data
 */
function base64ToFile(base64Image: string): Blob;

Usage Examples:

import { base64ToFile } from 'ngx-image-cropper';

// Convert base64 to blob for upload
const base64String = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==';
const blob = base64ToFile(base64String);

console.log('Blob type:', blob.type); // 'image/png'
console.log('Blob size:', blob.size); // Size in bytes

// Use in FormData for upload
const formData = new FormData();
formData.append('image', blob, 'image.png');

// Upload to server
fetch('/upload', {
  method: 'POST',
  body: formData
});

// Create object URL for display
const objectUrl = URL.createObjectURL(blob);
const img = document.createElement('img');
img.src = objectUrl;
document.body.appendChild(img);

// Clean up object URL when done
URL.revokeObjectURL(objectUrl);

Canvas Resizing

Resize canvas content using Hermite filter algorithm for high-quality image scaling.

/**
 * Resize canvas using Hermite filter algorithm
 * @param canvas - HTMLCanvasElement to resize
 * @param width - Target width in pixels
 * @param height - Target height in pixels
 */
function resizeCanvas(canvas: HTMLCanvasElement, width: number, height: number): void;

Usage Examples:

import { resizeCanvas } from 'ngx-image-cropper';

// Resize existing canvas content
const canvas = document.getElementById('myCanvas') as HTMLCanvasElement;
const ctx = canvas.getContext('2d');

// Draw some content on the canvas
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, 100, 100);

console.log('Original size:', canvas.width, 'x', canvas.height);

// Resize the canvas content
resizeCanvas(canvas, 200, 150);

console.log('New size:', canvas.width, 'x', canvas.height); // 200 x 150

// The original content is now scaled to fit the new dimensions

Advanced Usage Examples

// Convert cropped image result to blob for storage
function saveCroppedImage(croppedEvent: ImageCroppedEvent) {
  if (croppedEvent.base64) {
    // Convert base64 result to blob
    const blob = base64ToFile(croppedEvent.base64);
    
    // Save to local storage as blob URL
    const blobUrl = URL.createObjectURL(blob);
    localStorage.setItem('croppedImage', blobUrl);
    
    // Or download as file
    const link = document.createElement('a');
    link.href = blobUrl;
    link.download = 'cropped-image.png';
    link.click();
    
    // Clean up
    URL.revokeObjectURL(blobUrl);
  }
}

// Resize canvas with quality control
function resizeCanvasWithQuality(
  sourceCanvas: HTMLCanvasElement, 
  targetWidth: number, 
  targetHeight: number,
  quality: 'fast' | 'high' = 'high'
) {
  if (quality === 'high') {
    // Use Hermite filter for high quality
    resizeCanvas(sourceCanvas, targetWidth, targetHeight);
  } else {
    // Simple resize for speed
    const ctx = sourceCanvas.getContext('2d');
    if (ctx) {
      const imageData = ctx.getImageData(0, 0, sourceCanvas.width, sourceCanvas.height);
      sourceCanvas.width = targetWidth;
      sourceCanvas.height = targetHeight;
      ctx.putImageData(imageData, 0, 0);
    }
  }
}

// Batch convert multiple base64 images
async function convertBase64Batch(base64Images: string[]): Promise<Blob[]> {
  return base64Images.map(base64 => base64ToFile(base64));
}

// Create thumbnail from large canvas
function createThumbnail(
  sourceCanvas: HTMLCanvasElement, 
  maxDimension: number = 150
): HTMLCanvasElement {
  const ratio = Math.min(
    maxDimension / sourceCanvas.width,
    maxDimension / sourceCanvas.height
  );
  
  const thumbnailWidth = Math.round(sourceCanvas.width * ratio);
  const thumbnailHeight = Math.round(sourceCanvas.height * ratio);
  
  // Create new canvas for thumbnail
  const thumbnailCanvas = document.createElement('canvas');
  const ctx = thumbnailCanvas.getContext('2d');
  
  if (ctx) {
    // Copy original canvas content
    thumbnailCanvas.width = sourceCanvas.width;
    thumbnailCanvas.height = sourceCanvas.height;
    ctx.drawImage(sourceCanvas, 0, 0);
    
    // Resize to thumbnail size
    resizeCanvas(thumbnailCanvas, thumbnailWidth, thumbnailHeight);
  }
  
  return thumbnailCanvas;
}

// Convert canvas to different formats
function canvasToMultipleFormats(canvas: HTMLCanvasElement) {
  return {
    // Convert to base64 in different formats
    png: canvas.toDataURL('image/png'),
    jpeg: canvas.toDataURL('image/jpeg', 0.9),
    webp: canvas.toDataURL('image/webp', 0.8),
    
    // Convert to blobs using utility function
    pngBlob: base64ToFile(canvas.toDataURL('image/png')),
    jpegBlob: base64ToFile(canvas.toDataURL('image/jpeg', 0.9)),
    webpBlob: base64ToFile(canvas.toDataURL('image/webp', 0.8))
  };
}

Implementation Details

Base64 to File Algorithm

The base64ToFile function performs the following operations:

  1. Parse Data URL: Extracts the MIME type and base64 data from the data URL string
  2. Decode Base64: Converts the base64 string to binary data using atob()
  3. Create Array Buffer: Builds an ArrayBuffer from the binary data
  4. Generate Blob: Creates a Blob with the correct MIME type

Canvas Resize Algorithm

The resizeCanvas function uses the Hermite filter algorithm:

  1. Calculate Ratios: Determines scaling ratios for width and height
  2. Hermite Filtering: Applies mathematical filtering for smooth scaling
  3. Pixel Processing: Processes each pixel with weighted contributions from source pixels
  4. Quality Preservation: Maintains image quality during scaling operations

Error Handling

// Safe base64 conversion with error handling
function safeBase64ToFile(base64Image: string): Blob | null {
  try {
    return base64ToFile(base64Image);
  } catch (error) {
    console.error('Failed to convert base64 to file:', error);
    return null;
  }
}

// Safe canvas resize with validation
function safeResizeCanvas(
  canvas: HTMLCanvasElement, 
  width: number, 
  height: number
): boolean {
  try {
    if (width <= 0 || height <= 0) {
      console.error('Invalid dimensions for canvas resize');
      return false;
    }
    
    if (!canvas.getContext('2d')) {
      console.error('Canvas context not available');
      return false;
    }
    
    resizeCanvas(canvas, width, height);
    return true;
  } catch (error) {
    console.error('Failed to resize canvas:', error);
    return false;
  }
}

docs

crop-service.md

image-cropper-component.md

index.md

load-image-service.md

utility-functions.md

tile.json