The Angular ImageKit SDK is a wrapper built on top of the ImageKit JavaScript SDK. It seamlessly integrates ImageKit's URL generation, image and video optimization, responsive image handling, and file upload capabilities into Angular applications.
The SDK is lightweight and has first-class TypeScript support. It works with Angular 14+ (standalone components and directives). You can view the source code on Github.
Installation and Setup
Install the Angular SDK via npm or yarn:
npm install @imagekit/angular # or yarn add @imagekit/angular
The SDK supports both server-side rendering (SSR) and client-side rendering (CSR), so it can be added to any Angular project.
This Angular SDK exports IKImageDirective and IKVideoDirective directives. These directives can be applied to native <img> and <video> elements to add ImageKit's optimization and transformation capabilities. They automatically handle URL generation, lazy loading, responsive images, and transformations while preserving all native HTML attributes.
Modern Angular (14+) - Standalone Directives
For Angular 14 and above, you can import standalone directives directly:
import { Component } from '@angular/core';
import { IKImageDirective, provideImageKit } from '@imagekit/angular';
@Component({
selector: 'app-root',
standalone: true,
imports: [IKImageDirective],
template: `
<img
ikSrc="/profile.png"
[width]="500"
[height]="500"
alt="Picture of the author"
/>
`
})
export class AppComponent {}
Configure the SDK globally using provideImageKit() in your application config:
import { ApplicationConfig } from '@angular/core';
import { provideImageKit } from '@imagekit/angular';
export const appConfig: ApplicationConfig = {
providers: [
provideImageKit({
urlEndpoint: 'https://ik.imagekit.io/your_imagekit_id',
})
]
};
Besides IKImageDirective and IKVideoDirective, the SDK also provides utility functions and error classes that can be used independently of the components.
Utility functions
buildSrc– Generates URLs for images and videos based on your URL endpoint and transformation parameters.buildTransformationString– Converts array of transformation objects into a URL query string.upload– Facilitates file uploads to ImageKit with built-in support for common error handling, progress tracking, and abort functionality.getResponsiveImageAttributes– Generates responsive image attributes that can be used on raw HTML image elements. This SDK however handles this automatically for you when using theIKImageDirectivecomponent with[responsive]="true".
Refer to linked documentation for detailed usage of these utility functions.
Error classes for upload error handling
ImageKitInvalidRequestError- For invalid requests.ImageKitAbortError- For aborted uploads.ImageKitUploadNetworkError- For network errors during upload.ImageKitServerError- For server-side errors.
Image Directive
The IKImageDirective is applied to native HTML <img> elements using the ikSrc attribute. It enhances the image element with ImageKit's URL generation, transformations, lazy-loading, and responsive image capabilities.
Important: The directive selector is img[ikSrc], meaning you must use ikSrc instead of the standard src attribute.
It preserves all HTML img attributes and additionally accepts the following ImageKit-specific inputs:
| Parameter | Description and Example |
|---|---|
urlEndpoint | The base URL endpoint from your ImageKit dashboard. To avoid passing this input in every component, you can configure it globally using Example: |
ikSrc | A relative or absolute path to the image. This replaces the standard
Examples: |
width | The width of the image in pixels (in numbers). This is used to calculate the srcSet attribute and is only utilized when sizes is not provided. The prop is set on the Example: |
transformation | An array of transformation objects. Each object can include properties like Example: See all supported transformation options and how to handle unsupported transformations. |
| queryParameters | An object with additional query parameters to append to the URL. Example: [queryParameters]="{ v: 2 }" |
| responsive | A boolean that determines if responsive image functionality is enabled. By default, this is true, meaning that a srcset attribute is automatically generated for responsive images. Set it to false to disable this behavior and only apply explicitly defined transformations. |
deviceBreakpoints | It allows you to specify a list of device width breakpoints. Defaults to |
imageBreakpoints | It allows you to specify a list of image width breakpoints. It is concatenated with Defaults to |
| transformationPosition | Specifies whether the transformation string is included in the URL path or as a query parameter. Defaults to "query".Example: transformationPosition="query" or transformationPosition="path" |
| loading | Controls lazy loading behavior. Set to "lazy" (default) to defer loading until the image is near the viewport, or "eager" to load immediately. Example: loading="lazy" |
Video Directive
The IKVideoDirective is applied to native HTML <video> elements using the ikSrc attribute. It enhances the video element with ImageKit's URL generation and transformation capabilities.
Important: The directive selector is video[ikSrc], meaning you must use ikSrc instead of the standard src attribute.
It preserves all HTML video attributes and additionally accepts the following ImageKit-specific inputs - urlEndpoint, transformation, transformationPosition, and queryParameters. For the definition of these inputs, refer to the Image directive section.
import { Component } from '@angular/core';
import { IKVideoDirective } from '@imagekit/angular';
@Component({
selector: 'app-video-example',
standalone: true,
imports: [IKVideoDirective],
template: `
<video
ikSrc="/video.mp4"
[controls]="true"
[width]="500"
[height]="500"
></video>
`
})
export class VideoExampleComponent {}
Height and Width Transformations
With ImageKit, you can resize images on the fly using the width and height properties. The SDK automatically generates the appropriate URL with the specified dimensions.
import { Component } from '@angular/core';
import { IKImageDirective, Transformations } from '@imagekit/angular';
@Component({
selector: 'app-resize-example',
standalone: true,
imports: [IKImageDirective],
template: `
<img
ikSrc="/profile.png"
[width]="500"
[height]="500"
alt="Picture of the author"
[transformation]="transformation"
/>
`
})
export class ResizeExampleComponent {
transformation: Transformations = [{ width: 500, height: 500 }];
}
Responsive Images
The IKImageDirective includes built-in support for responsive images, enabled by default. It automatically generates appropriate srcSet attributes based on device and image breakpoints, ensuring optimal image delivery across screen sizes.
Under the hood, it leverages the getResponsiveImageAttributes utility from the core JavaScript SDK to generate these attributes.
If you want to turn off responsive images, you can set responsive to false. This will disable the automatic generation of srcset attributes.
Note: If you have enabled the "Restrict unnamed transformations" setting (see Basic Security), hardcoded width/crop transformations may be added by default causing request failures. Setting responsive to false prevents these additional transformations from being applied.
Lazy Loading Images
The IKImageDirective supports lazy loading by default. You can control this behavior using the loading attribute.
By default, loading is set to lazy, which defers loading the image until it is near the viewport.
If set to eager, the image loads immediately.
import { Component } from '@angular/core';
import { IKImageDirective } from '@imagekit/angular';
@Component({
selector: 'app-lazy-load-example',
standalone: true,
imports: [IKImageDirective],
template: `
<img
ikSrc="/profile.png"
[width]="500"
[height]="500"
alt="Picture of the author"
loading="lazy"
/>
`
})
export class LazyLoadExampleComponent {}
Lazy Loading with Placeholder
To display a placeholder while an image is loading, you can generate a placeholder image URL using ImageKit's buildSrc utility function and apply it as a background image using styles. You can use Angular's event binding to manage the placeholder visibility.
import { Component } from '@angular/core';
import { IKImageDirective, buildSrc } from '@imagekit/angular';
import { NgStyle } from '@angular/common';
@Component({
selector: 'app-placeholder-example',
standalone: true,
imports: [IKImageDirective, NgStyle],
template: `
<img
ikSrc="/default-image.jpg"
alt="Angular logo"
[width]="400"
[height]="400"
loading="eager"
[ngStyle]="imageStyle"
(load)="onImageLoad()"
/>
`
})
export class PlaceholderExampleComponent {
showPlaceholder = true;
get imageStyle() {
if (!this.showPlaceholder) return {};
return {
backgroundImage: `url(${buildSrc({
urlEndpoint: 'https://ik.imagekit.io/your_imagekit_id',
src: '/default-image.jpg',
transformation: [
{ quality: 10, blur: 90 }
]
})})`,
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat'
};
}
onImageLoad() {
this.showPlaceholder = false;
}
}
Lazy Loading Videos
To lazy load a video using IKVideoDirective, you can set the preload attribute to none and specify a poster image by extracting a thumbnail from the video.
The buildSrc utility function is used to generate the thumbnail URL. It accepts the same parameters as the IKVideoDirective and returns a URL with the specified transformations.
Refer to the create thumbnail documentation for detailed instructions on generating a thumbnail from a video using ImageKit.
import { Component } from '@angular/core';
import { IKVideoDirective, buildSrc } from '@imagekit/angular';
@Component({
selector: 'app-video-lazy-load',
standalone: true,
imports: [IKVideoDirective],
template: `
<video
ikSrc="/video.mp4"
[controls]="true"
preload="none"
[poster]="posterUrl"
></video>
`
})
export class VideoLazyLoadComponent {
posterUrl = buildSrc({
urlEndpoint: 'https://ik.imagekit.io/your_imagekit_id',
src: '/video.mp4/ik-thumbnail.jpg'
});
}
Chained Transformations
You can chain multiple transformations together by passing an array of transformation objects. Each object can specify different properties, such as width, height, cropping, overlays, and effects. See chained transformations for more details.
import { Component } from '@angular/core';
import { IKImageDirective, Transformations } from '@imagekit/angular';
@Component({
selector: 'app-chained-transform',
standalone: true,
imports: [IKImageDirective],
template: `
<img
ikSrc="/profile.png"
[width]="500"
[height]="500"
alt="Picture of the author"
[transformation]="transformations"
/>
`
})
export class ChainedTransformComponent {
transformations: Transformations = [
{ width: 400, height: 300 },
{ rotation: 90 }
];
}
Adding Overlays
You can add overlays to images and videos. The overlay can be a text, image, video, or subtitle.
Besides the overlay type, you can also specify the position, size, and other properties of the overlay. Check the overlay options for more details.
Image Overlay
import { Component } from '@angular/core';
import { IKImageDirective, Transformations } from '@imagekit/angular';
@Component({
selector: 'app-image-overlay',
standalone: true,
imports: [IKImageDirective],
template: `
<img
ikSrc="/background.jpg"
alt="Background with image overlay"
[width]="600"
[height]="400"
[transformation]="transformations"
/>
`
})
export class ImageOverlayComponent {
transformations: Transformations = [
{ overlay: { type: 'image', input: 'logo.png' } }
];
}
You can independently transform the overlay image by passing a transformation array inside the overlay object. The transformation will be applied to the overlay image only.
import { Component } from '@angular/core';
import { IKImageDirective, Transformations } from '@imagekit/angular';
@Component({
selector: 'app-image-overlay-transform',
standalone: true,
imports: [IKImageDirective],
template: `
<img
ikSrc="/background.jpg"
alt="Background with transformed image overlay"
[width]="600"
[height]="400"
[transformation]="transformations"
/>
`
})
export class ImageOverlayTransformComponent {
transformations: Transformations = [
{
overlay: {
type: 'image',
input: 'logo.png',
transformation: [{ width: 100, height: 100 }]
}
}
];
}
Image overlays support a wide range of transformations. Check reference for the complete list of transformations supported on image overlays.
Solid Color Overlay
You can add a solid color overlay to images and videos.
import { Component } from '@angular/core';
import { IKImageDirective, Transformations } from '@imagekit/angular';
@Component({
selector: 'app-color-overlay',
standalone: true,
imports: [IKImageDirective],
template: `
<img
ikSrc="/background.jpg"
alt="Background with solid color overlay"
[width]="600"
[height]="400"
[transformation]="transformations"
/>
`
})
export class SolidColorComponent {
transformations: Transformations = [
{
overlay: {
type: 'solidColor',
color: 'FF0000'
}
}
];
}
You can also specify the width, height, and other properties of the solid color overlay. For example:
import { Component } from '@angular/core';
import { IKImageDirective, Transformations } from '@imagekit/angular';
@Component({
selector: 'app-color-overlay-sized',
standalone: true,
imports: [IKImageDirective],
template: `
<img
ikSrc="/background.jpg"
alt="Background with 100x100 solid color overlay"
[width]="600"
[height]="400"
[transformation]="transformations"
/>
`
})
export class ColorOverlaySizedComponent {
transformations: Transformations = [
{
overlay: {
type: 'solidColor',
color: 'FF0000',
transformation: [
{ width: 100, height: 100 }
]
}
}
];
}
For more options related to styling the solid color overlay, check the solid color overlay transformations section.
Text Overlay
You can add text overlays to images and videos.
import { Component } from '@angular/core';
import { IKImageDirective, Transformations } from '@imagekit/angular';
@Component({
selector: 'app-text-overlay',
standalone: true,
imports: [IKImageDirective],
template: `
<img
ikSrc="/background.jpg"
alt="Background with text overlay"
[width]="600"
[height]="400"
[transformation]="transformations"
/>
`
})
export class TextOverlayComponent {
transformations: Transformations = [
{
overlay: {
type: 'text',
text: 'Hello, ImageKit!'
}
}
];
}
You can also specify the font size, color, and other properties of the text overlay. For example:
import { Component } from '@angular/core';
import { IKImageDirective, Transformations } from '@imagekit/angular';
@Component({
selector: 'app-text-overlay-styled',
standalone: true,
imports: [IKImageDirective],
template: `
<img
ikSrc="/background.jpg"
alt="Background with styled text overlay"
[width]="600"
[height]="400"
[transformation]="transformations"
/>
`
})
export class TextOverlayStyledComponent {
transformations: Transformations = [
{
overlay: {
type: 'text',
text: 'Hello, ImageKit!',
transformation: [
{ fontSize: 20, fontColor: 'FF0000' }
]
}
}
];
}
Check the text overlay transformations section for more options related to styling the text.
Video Overlay
You can add video overlays on videos only.
import { Component } from '@angular/core';
import { IKVideoDirective, Transformations } from '@imagekit/angular';
@Component({
selector: 'app-video-overlay',
standalone: true,
imports: [IKVideoDirective],
template: `
<video
ikSrc="/background.mp4"
[controls]="true"
[transformation]="transformations"
></video>
`
})
export class VideoOverlayComponent {
transformations: Transformations = [
{
overlay: {
type: 'video',
input: 'overlay.mp4'
}
}
];
}
Additionally, you can specify the start and duration for the overlay video. For example:
import { Component } from '@angular/core';
import { IKVideoDirective, Transformations } from '@imagekit/angular';
@Component({
selector: 'app-video-overlay-timed',
standalone: true,
imports: [IKVideoDirective],
template: `
<video
ikSrc="/background.mp4"
[controls]="true"
[transformation]="transformations"
></video>
`
})
export class VideoOverlayTimedComponent {
transformations: Transformations = [
{
overlay: {
type: 'video',
input: 'overlay.mp4',
timing: { start: 5, duration: 10 }
}
}
];
}
You can also independently transform the overlay video. For example, to resize the overlay video:
import { Component } from '@angular/core';
import { IKVideoDirective, Transformations } from '@imagekit/angular';
@Component({
selector: 'app-video-overlay-transform',
standalone: true,
imports: [IKVideoDirective],
template: `
<video
ikSrc="/background.mp4"
[controls]="true"
[transformation]="transformations"
></video>
`
})
export class VideoOverlayTransformComponent {
transformations: Transformations = [
{
overlay: {
type: 'video',
input: 'overlay.mp4',
transformation: [
{ width: 100, height: 100 }
]
}
}
];
}
All supported video transformations can also be applied to overlay videos.
If you're overlaying an image on a base video, refer to this list for all the transformations supported on image overlays.
Subtitle Overlay
You can add subtitle overlays on videos.
import { Component } from '@angular/core';
import { IKVideoDirective, Transformations } from '@imagekit/angular';
@Component({
selector: 'app-subtitle-overlay',
standalone: true,
imports: [IKVideoDirective],
template: `
<video
ikSrc="/background.mp4"
[controls]="true"
[transformation]="transformations"
></video>
`
})
export class SubtitleOverlayComponent {
transformations: Transformations = [
{
overlay: {
type: 'subtitle',
input: 'subtitle.srt'
}
}
];
}
The subtitle overlay can be styled with various properties such as font size, color, and outline. See the Subtitle Overlay Transformations section for all styling options.
Background Removal Using AI
import { Component } from '@angular/core';
import { IKImageDirective, Transformations } from '@imagekit/angular';
@Component({
selector: 'app-bg-removal',
standalone: true,
imports: [IKImageDirective],
template: `
<img
ikSrc="/photo.jpg"
alt="Photo with background removal"
[width]="500"
[height]="500"
[transformation]="transformations"
/>
`
})
export class BgRemovalComponent {
transformations: Transformations = [
{ aiRemoveBackground: true }
];
}
ImageKit supports multiple AI-powered transformations, like upscaling, generative fill, and more. More examples:
import { Component } from '@angular/core';
import { IKImageDirective, Transformations } from '@imagekit/angular';
@Component({
selector: 'app-ai-drop-shadow',
standalone: true,
imports: [IKImageDirective],
template: `
<img
ikSrc="/photo.jpg"
alt="Photo with AI drop shadow"
[width]="500"
[height]="500"
[transformation]="transformations"
/>
`
})
export class AiDropShadowComponent {
transformations: Transformations = [
{ aiDropShadow: true }
];
}
Upscaling example:
import { Component } from '@angular/core';
import { IKImageDirective, Transformations } from '@imagekit/angular';
@Component({
selector: 'app-ai-upscale',
standalone: true,
imports: [IKImageDirective],
template: `
<img
ikSrc="/photo.jpg"
alt="Photo with AI upscaling"
[width]="500"
[height]="500"
[transformation]="transformations"
/>
`
})
export class AiUpscaleComponent {
transformations: Transformations = [
{ aiUpscale: true }
];
}
Arithmetic Expressions
You can use arithmetic expressions to dynamically compute transformation values. For example, to set the width to half of the original image width:
import { Component } from '@angular/core';
import { IKImageDirective, Transformations } from '@imagekit/angular';
@Component({
selector: 'app-arithmetic',
standalone: true,
imports: [IKImageDirective],
template: `
<img
ikSrc="/photo.jpg"
alt="Photo with arithmetic width"
[width]="300"
[height]="200"
[transformation]="transformations"
/>
`
})
export class ArithmeticComponent {
transformations: Transformations = [
{ width: 'iw_div_2' }
];
}
Check out the Arithmetic Expressions reference for more examples and details.
Uploading Files
The Angular SDK exports a utility function upload(), which enables you to upload files to ImageKit. The function wraps the core JavaScript SDK's upload() function, which leverages the Upload V1 API.
The SDK automatically converts certain parameters into JSON strings, as required by the API. If a parameter is not explicitly supported by the SDK, it is included in the request as-is. For a complete list of parameters and expected formats, refer to the API documentation.
upload() Parameters
The upload() function accepts a JSON object with the following parameters:
| Option | Description and Example |
|---|---|
| file (Required) | The file content to be uploaded. Accepts binary data, a base64-encoded string, or a URL. Typically used with a File or Blob in the browser. Example: file: fileInput.files[0] |
| fileName (Required) | The name to assign to the uploaded file. Supports alphanumeric characters, dot, underscore, and dash. Any other character is replaced with _. Example: fileName: "myImage.jpg" |
| signature (Required) | The HMAC-SHA1 digest of the concatenation of "token + expire". The signing key is your ImageKit private API key. Must be computed on the server side. Example: signature: "generated_signature" |
token | A unique value to identify and prevent replays. Typically a UUID (e.g., version 4). Example: Check the generating authentication parameters section for more details on how to generate this value. |
expire | A Unix timestamp in seconds, less than 1 hour in the future. Example: Check the generating authentication parameters section for more details on how to generate this value. |
| onProgress | A callback function to track the upload progress. It receives an event object with loaded and total properties. Example: onProgress: (event) => console.log(event.loaded, event.total) This is useful for showing upload progress to the user. |
| abortSignal | An optional AbortSignal object to abort the upload request. If the signal is already aborted, the upload will fail immediately. You can create an AbortController instance and pass its signal to the upload() function. |
| useUniqueFileName | Boolean flag to automatically generate a unique filename if set to true. Defaults to true. If false, the image is uploaded with the provided filename, replacing any existing file with the same name. Example: useUniqueFileName: true |
| folder | The folder path where the file will be stored, e.g., "/images/folder/". If the path doesn't exist, it is created on-the-fly. Example: folder: "/images/uploads" |
| isPrivateFile | Boolean to mark the file as private, restricting access to the original file URL. A private file requires signed URLs or named transformations for access. Defaults to false. Example: isPrivateFile: false |
| tags | Optionally set tags on the uploaded file. Can be a comma-separated string or an array of tags. Example: tags: "summer,holiday" or tags: ["summer","holiday"] |
| customCoordinates | A string in "x,y,width,height" format that defines the region of interest in an image (top-left coords and area size). Example: customCoordinates: "10,10,100,100" |
| responseFields | A comma-separated or array-based set of fields to return in the upload response. Example: responseFields: "tags,customCoordinates" |
| extensions | An array of extension objects to apply to the image, e.g., background removal, auto-tagging, etc. Example: extensions: [{ name: "auto-tagging" }] |
| webhookUrl | A webhook URL to receive the final status of any pending extensions once they've completed processing. Example: webhookUrl: "https://example.com/webhook" |
| overwriteFile | Defaults to true. If false, and "useUniqueFileName" is also false, the API immediately fails if a file with the same name/folder already exists. Example: overwriteFile: true |
| overwriteAITags | Defaults to true. If true, and an existing file is found at the same location, its AITags are removed. Set to false to keep existing AITags. Example: overwriteAITags: true |
| overwriteTags | Defaults to true. If no tags are specified in the request, existing tags are removed from overwritten files. Setting to false has no effect if the request includes tags. Example: overwriteTags: true |
| overwriteCustomMetadata | Defaults to true. If no customMetadata is specified in the request, existing customMetadata is removed from overwritten files. Setting to false has no effect if the request specifies customMetadata. Example: overwriteCustomMetadata: true |
| customMetadata | A stringified JSON or an object containing custom metadata fields to store with the file. Custom metadata fields must be pre-defined in your ImageKit configuration. Example: customMetadata: {author: "John Doe"} |
| transformation | Defines pre and post transformations to be applied to the file during upload. The SDK enforces certain validation rules for pre/post transformations. Example: transformation: { pre: "w-200,h-200", post: [...] } |
| xhr | An optional XMLHttpRequest instance for the upload. The SDK merges it with its own logic to handle progress events, etc. Example: xhr: new XMLHttpRequest() |
| checks | A string specifying the checks to be performed server-side before uploading to the media library, e.g., size or mime type checks. Example: checks: "file.size' < '1MB'" |
Upload Example and Error Handling
The upload() function expects the following mandatory parameters:
fileandfileName– The file to be uploaded and the name you want to assign to it. Thefilevalue can be aFileobject, a base64-encoded string, or a URL.- Authentication parameters –
token,signature&expire
Authentication is essential for secure file uploads from the browser. You should never expose your private API key in client-side code. Instead, generate these one-time authentication parameters on the server side and pass them to the client.
To simplify the process, all of our backend SDKs include utility functions for generating authentication parameters.
Note: If you're using HttpClient in your components to fetch authentication parameters, make sure to provide it in your application. For standalone components, add provideHttpClient() to your application config providers.
Upload Flow Overview
Here's how the upload process using the SDK works:
Client Request for Auth Parameters
The client component calls an API route to fetch the authentication parameters.
You can implement your own application logic within this route to authenticate the user.
After that, use one of our backend SDKs to generate the required auth parameters and return them to the client.File Upload
Once the client has the auth parameters, it can call theupload()function with the necessary data.
Generating Authentication Parameters
The following example demonstrates how to create an API route that generates authentication parameters using the ImageKit backend SDKs.
You can find your private key and public key in the ImageKit dashboard.
const express = require('express');
const ImageKit = require('@imagekit/nodejs'); // Node.js SDK
const app = express();
const client = new ImageKit({
privateKey: process.env.IMAGEKIT_PRIVATE_KEY
});
// allow cross-origin requests
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/auth', function (req, res) {
// Your application logic to authenticate the user
// For example, you can check if the user is logged in or has the necessary permissions
// If the user is not authenticated, you can return an error response
const { token, expire, signature } = client.helper.getAuthenticationParameters();
res.send({ token, expire, signature, publicKey: process.env.IMAGEKIT_PUBLIC_KEY });
});
app.listen(3000, function () {
console.log('Live at Port 3000');
});
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"github.com/imagekit-developer/imagekit-go/v2"
"github.com/imagekit-developer/imagekit-go/v2/option"
)
func main() {
client := imagekit.NewClient(
option.WithPrivateKey(os.Getenv("IMAGEKIT_PRIVATE_KEY")),
)
http.HandleFunc("/auth", func(w http.ResponseWriter, r *http.Request) {
// Enable CORS
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
// Your application logic to authenticate the user
// For example, you can check if the user is logged in or has the necessary permissions
// If the user is not authenticated, you can return an error response
authParams := client.Helper.GetAuthenticationParameters("", 0)
response := map[string]interface{}{
"token": authParams["token"],
"expire": authParams["expire"],
"signature": authParams["signature"],
"publicKey": os.Getenv("IMAGEKIT_PUBLIC_KEY"),
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
})
log.Println("Live at Port 3000")
log.Fatal(http.ListenAndServe(":3000", nil))
}
import os
from flask import Flask, jsonify
from imagekitio import ImageKit
app = Flask(__name__)
imagekit = ImageKit(
private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY")
)
# Enable CORS
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
return response
@app.route('/auth')
def get_auth():
# Your application logic to authenticate the user
# For example, you can check if the user is logged in or has the necessary permissions
# If the user is not authenticated, you can return an error response
auth_params = imagekit.helper.get_authentication_parameters()
return jsonify({
'token': auth_params['token'],
'expire': auth_params['expire'],
'signature': auth_params['signature'],
'publicKey': os.environ.get('IMAGEKIT_PUBLIC_KEY')
})
if __name__ == '__main__':
app.run(port=3000)
require 'sinatra'
require 'imagekitio'
require 'json'
# Enable CORS
before do
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'
end
client = Imagekitio::Client.new(private_key: ENV['IMAGEKIT_PRIVATE_KEY'])
get '/auth' do
content_type :json
# Your application logic to authenticate the user
# For example, you can check if the user is logged in or has the necessary permissions
# If the user is not authenticated, you can return an error response
auth_params = client.helper.get_authentication_parameters
{
token: auth_params[:token],
expire: auth_params[:expire],
signature: auth_params[:signature],
publicKey: ENV['IMAGEKIT_PUBLIC_KEY']
}.to_json
end
# Start the server
set :port, 3000
Now your client-side code can call this API route to retrieve the upload parameters.
The example below demonstrates how to use the upload() function in a component to upload a file, including error handling for various upload scenarios.
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import {
upload,
ImageKitAbortError,
ImageKitInvalidRequestError,
ImageKitUploadNetworkError,
ImageKitServerError
} from '@imagekit/angular';
interface AuthResponse {
signature: string;
expire: number;
token: string;
publicKey: string;
}
@Component({
selector: 'app-upload-example',
standalone: true,
imports: [CommonModule],
template: `
<div>
<input
type="file"
(change)="onFileSelect($event)"
#fileInput
/>
<button
type="button"
(click)="handleUpload()"
[disabled]="!selectedFile"
>
Upload file
</button>
<br />
<div *ngIf="progress > 0">
<progress [value]="progress" max="100"></progress>
<span>{{ progress.toFixed(0) }}%</span>
</div>
<div *ngIf="uploadStatus">
{{ uploadStatus }}
</div>
</div>
`
})
export class UploadExampleComponent {
private http = inject(HttpClient);
selectedFile: File | null = null;
progress = 0;
uploadStatus = '';
private abortController = new AbortController();
onFileSelect(event: Event) {
const target = event.target as HTMLInputElement;
if (target.files && target.files.length > 0) {
this.selectedFile = target.files[0];
this.progress = 0;
this.uploadStatus = '';
}
}
async handleUpload() {
const file = this.selectedFile;
if (!file) {
alert('Please select a file to upload');
return;
}
try {
// Fetch authentication parameters from your backend
const authParams = await this.http.get<AuthResponse>('/auth').toPromise();
if (!authParams) {
throw new Error('Failed to get authentication parameters');
}
// Upload the file
const response = await upload({
file: file,
fileName: file.name,
signature: authParams.signature,
expire: authParams.expire,
token: authParams.token,
publicKey: authParams.publicKey,
onProgress: (event) => {
this.progress = (event.loaded / event.total) * 100;
},
abortSignal: this.abortController.signal
});
this.uploadStatus = 'Upload successful!';
console.log('Upload response:', response);
} catch (error) {
if (error instanceof ImageKitAbortError) {
this.uploadStatus = 'Upload aborted';
console.error('Upload aborted:', error.reason);
} else if (error instanceof ImageKitInvalidRequestError) {
this.uploadStatus = 'Invalid request';
console.error('Invalid request:', error.message);
} else if (error instanceof ImageKitUploadNetworkError) {
this.uploadStatus = 'Network error';
console.error('Network error:', error.message);
} else if (error instanceof ImageKitServerError) {
this.uploadStatus = 'Server error';
console.error('Server error:', error.message);
} else {
this.uploadStatus = 'Upload failed';
console.error('Upload error:', error);
}
}
}
// Optional: Method to abort the upload
abortUpload() {
this.abortController.abort();
}
}
Supported Transformations
The SDK assigns a name to each transformation parameter (e.g., height maps to h, width maps to w). If the property does not match any of the following supported options, it is added as is in the URL.
If you want to generate transformations without any modifications, use the raw parameter. For example, SDK doesn't provide a nice way to write conditional transformations, so you can use the raw parameter to add them as is.
Check transformation documentation for complete reference on all transformations supported by ImageKit.
| Transformation Name | URL Parameter |
|---|---|
| width | w |
| height | h |
| aspectRatio | ar |
| quality | q |
| aiRemoveBackground | e-bgremove (ImageKit powered) |
| aiRemoveBackgroundExternal | e-removedotbg (Using third party) |
| aiUpscale | e-upscale |
| aiRetouch | e-retouch |
| aiVariation | e-genvar |
| aiDropShadow | e-dropshadow |
| aiChangeBackground | e-changebg |
| crop | c |
| cropMode | cm |
| x | x |
| y | y |
| xCenter | xc |
| yCenter | yc |
| focus | fo |
| format | f |
| radius | r |
| background | bg |
| border | b |
| rotation | rt |
| blur | bl |
| named | n |
| dpr | dpr |
| progressive | pr |
| lossless | lo |
| trim | t |
| metadata | md |
| colorProfile | cp |
| defaultImage | di |
| original | orig |
| videoCodec | vc |
| audioCodec | ac |
| grayscale | e-grayscale |
| contrastStretch | e-contrast |
| shadow | e-shadow |
| sharpen | e-sharpen |
| unsharpMask | e-usm |
| gradient | e-gradient |
| flip | fl |
| opacity | o |
| zoom | z |
| page | pg |
| startOffset | so |
| endOffset | eo |
| duration | du |
| streamingResolutions | sr |
| overlay | Generates the correct layer syntax for image, video, text, subtitle, and solid color overlays. |
| raw | The string provided in raw will be added in the URL as is. |
Handling Unsupported Transformations
If you specify a transformation parameter that is not explicitly supported by the SDK, it is added "as-is" in the generated URL. This provides flexibility for using new or custom transformations without waiting for an SDK update. However add @ts-ignore to avoid TypeScript errors for unsupported transformations, or add transformation as a string in the raw parameter.
For example:
import { Component } from '@angular/core';
import { IKImageDirective, Transformations } from '@imagekit/angular';
@Component({
selector: 'app-unsupported-transform',
standalone: true,
imports: [IKImageDirective],
template: `
<img
ikSrc="/photo.jpg"
alt="Photo with unsupported transformation"
[transformation]="transformations"
/>
`
})
export class UnsupportedTransformComponent {
// @ts-ignore - unsupported transformation
transformations: Transformations = [
{ unsupportedTransformation: "value" }
];
}
// Output URL: https://ik.imagekit.io/your_imagekit_id/photo.jpg?tr=unsupportedTransformation-value
Overlay Reference
This SDK provides overlay as a transformation parameter. The overlay can be a text, image, video, subtitle, or solid color.
Overlays in ImageKit are applied using layers, allowing you to stack multiple overlays on top of each other. Each overlay can be styled and positioned independently. For more details, refer to the layer documentation.
The SDK automatically generates the correct layer syntax for image, video, text, subtitle, and solid color overlays. You can also specify the overlay position, size, and other properties.
The table below outlines the available overlay configuration options:
| Option | Description and Example |
|---|---|
| type (Required) | Specifies the type of overlay. Supported values: text, image, video, subtitle, solidColor. Example: type: "text" |
| text (Required for text overlays) | The text content to display. Example: text: "ImageKit" |
| input (Required for image, video, or subtitle overlays) | Relative path to the overlay asset. Example: input: "logo.png" or input: "overlay-video.mp4" |
| color (Required for solidColor overlays) | RGB/RGBA hex code or color name for the overlay color. Example: color: "FF0000" |
| encoding | Accepted values: auto, plain, base64. Check this for more details. Example: encoding: "auto" |
| transformation | An array of transformation objects to style the overlay independently of the base asset. Each overlay type has its own set of supported transformations.
|
| position | Sets the overlay's position relative to the base asset. Accepts an object with x, y, or focus. Example: position: { x: 10, y: 20 } or position: { focus: "center" } |
| timing | (For video base) Specifies when the overlay appears using start, duration, and end (in seconds); if both duration and end are set, duration is ignored. Example: timing: { start: 5, duration: 10 } |
Encoding Options
Overlay encoding options define how the overlay input is converted for URL construction. When set to auto, the SDK automatically determines whether to use plain text or Base64 encoding based on the input content.
For text overlays:
- If
autois used, the SDK checks the text overlay input: if it is URL-safe, it uses the formati-{input}(plain text); otherwise, it applies Base64 encoding with the formatie-{base64_encoded_input}. - You can force a specific method by setting encoding to
plain(always usei-{input}) orbase64(always useie-{base64}). - Note: In all cases, the text is percent-encoded to ensure URL safety.
For image, video, and subtitle overlays:
- The input path is processed by removing any leading/trailing slashes and replacing inner slashes with
@@whenplainis used. - Similarly, if
autois used, the SDK determines whether to apply plain text or Base64 encoding based on the characters present. - For explicit behavior, use
plainorbase64to enforce the desired encoding.
Use auto for most cases to let the SDK optimize encoding, and use plain or base64 when a specific encoding method is required.
Solid Color Overlay Transformations
| Option | Description | Example |
|---|---|---|
| width | Specifies the width of the solid color overlay block (in pixels or as an arithmetic expression). | width: 100 |
| height | Specifies the height of the solid color overlay block (in pixels or as an arithmetic expression). | height: 50 |
| radius | Specifies the corner radius of the solid color overlay block or shape. Can be a number or "max" for circular/oval shapes. | radius: "max" |
| alpha | Specifies the transparency level of the solid color overlay. Supports integers from 1 (most transparent) to 9 (least transparent). | alpha: 5 |
| background | Specifies the background color of the solid color overlay. Accepts an RGB hex code, an RGBA code, or a standard color name. | background: "red" |
| gradient | Only works if base asset is an image. Creates a linear gradient with two colors. Pass true for a default gradient, or provide a string for a custom gradient. Learn more | gradient: true |
Text Overlay Transformations
| Option | Description | Example |
|---|---|---|
| width | Specifies the maximum width (in pixels) of the overlaid text. The text wraps automatically, and arithmetic expressions are supported (e.g., bw_mul_0.2 or bh_div_2). | width: 400 |
| fontSize | Specifies the font size of the overlaid text. Accepts a numeric value or an arithmetic expression. | fontSize: 50 |
| fontFamily | Specifies the font family of the overlaid text. Choose from the supported fonts or provide a custom font. | fontFamily: "Arial" |
| fontColor | Specifies the font color of the overlaid text. Accepts an RGB hex code, an RGBA code, or a standard color name. | fontColor: "FF0000" |
| innerAlignment | Specifies the inner alignment of the text when it doesn't occupy the full width. Supported values: left, right, center. | innerAlignment: "center" |
| padding | Specifies the padding around the text overlay. Can be a single integer or multiple values separated by underscores; arithmetic expressions are accepted. | padding: 10 |
| alpha | Specifies the transparency level of the text overlay. Accepts an integer between 1 and 9. | alpha: 5 |
| typography | Specifies the typography style of the text. Supported values: b for bold, i for italics, and b_i for bold with italics. | typography: "b" |
| background | Specifies the background color of the text overlay. Accepts an RGB hex code, an RGBA code, or a color name. | background: "red" |
| radius | Specifies the corner radius of the text overlay. Accepts a numeric value or max for circular/oval shape. | radius: "max" |
| rotation | Specifies the rotation angle of the text overlay. Accepts a numeric value for clockwise rotation or a string prefixed with N for counterclockwise rotation. | rotation: 90 |
| flip | Specifies the flip option for the text overlay. Supported values: h, v, h_v, v_h. | flip: "h" |
| lineHeight | Specifies the line height for multi-line text. Accepts a numeric value or an arithmetic expression. | lineHeight: 20 |
Subtitle Overlay Transformations
| Option | Description | Example |
|---|---|---|
| background | Specifies the subtitle background color using a standard color name, RGB color code, or RGBA color code. | background: "blue" |
| fontSize | Sets the font size of subtitle text. | fontSize: 16 |
| fontFamily | Sets the font family of subtitle text. | fontFamily: "Arial" |
| color | Specifies the font color of subtitle text using standard color name, RGB, or RGBA color code. | color: "FF0000" |
| typography | Sets the typography style of subtitle text. Supported values: b, i, b_i. | typography: "b" |
| fontOutline | Specifies the font outline for subtitles. Requires an outline width and color separated by an underscore. | fontOutline: "2_blue" |
| fontShadow | Specifies the font shadow for subtitles. Requires shadow color and indent separated by an underscore. | fontShadow: "blue_2" |