Imagekit 6.0.0

dotnet add package Imagekit --version 6.0.0
                    
NuGet\Install-Package Imagekit -Version 6.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Imagekit" Version="6.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Imagekit" Version="6.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Imagekit" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Imagekit --version 6.0.0
                    
#r "nuget: Imagekit, 6.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Imagekit@6.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Imagekit&version=6.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Imagekit&version=6.0.0
                    
Install as a Cake Tool

ImageKit.io C# SDK

The ImageKit C# SDK is a comprehensive library designed to simplify the integration of ImageKit into your server-side applications. It provides powerful tools for working with the ImageKit REST API, including building and transforming URLs, generating signed URLs for secure content delivery, and handling file uploads.

For additional details, refer to the ImageKit REST API documentation.

Table of Contents

Installation

Install the package from NuGet:

dotnet add package Imagekit

Requirements

This library requires .NET Standard 2.0 or later.

Usage

using System;
using Imagekit;
using Imagekit.Models.Files;

ImageKitClient client = new()
{
    PrivateKey = "private_key_xxx",
};

FileUploadParams parameters = new()
{
    File = new System.IO.FileStream("/path/to/your/image.jpg", System.IO.FileMode.Open),
    FileName = "uploaded-image.jpg",
};

var response = await client.Files.Upload(parameters);

Console.WriteLine(response);

Client configuration

Configure the client using environment variables:

using Imagekit;

// Configured using the IMAGEKIT_PRIVATE_KEY, IMAGEKIT_WEBHOOK_SECRET and IMAGE_KIT_BASE_URL environment variables
ImageKitClient client = new();

Or manually:

using Imagekit;

ImageKitClient client = new()
{
    PrivateKey = "My Private Key",
};

Or using a combination of the two approaches.

See this table for the available options:

Property Environment variable Required Default value
PrivateKey IMAGEKIT_PRIVATE_KEY true -
WebhookSecret IMAGEKIT_WEBHOOK_SECRET false -
BaseUrl IMAGE_KIT_BASE_URL true "https://api.imagekit.io"

Modifying configuration

To temporarily use a modified client configuration, while reusing the same connection and thread pools, call WithOptions on any client or service:

using System;

var response = await client
    .WithOptions(options =>
        options with
        {
            BaseUrl = "https://example.com",
            Timeout = TimeSpan.FromSeconds(42),
        }
    )
    .Files.Upload(parameters);

Console.WriteLine(response);

Using a with expression makes it easy to construct the modified options.

The WithOptions method does not affect the original client or service.

Requests and responses

To send a request to the Image Kit API, build an instance of some Params class and pass it to the corresponding client method. When the response is received, it will be deserialized into an instance of a C# class.

For example, client.Files.Upload should be called with an instance of FileUploadParams, and it will return an instance of Task<FileUploadResponse>.

Raw responses

The SDK defines methods that deserialize responses into instances of C# classes. However, these methods don't provide access to the response headers, status code, or the raw response body.

To access this data, prefix any HTTP method call on a client or service with WithRawResponse:

var response = await client.WithRawResponse.Files.Upload(parameters);
var statusCode = response.StatusCode;
var headers = response.Headers;

The raw HttpResponseMessage can also be accessed through the RawMessage property.

For non-streaming responses, you can deserialize the response into an instance of a C# class if needed:

using System;
using Imagekit.Models.Files;

var response = await client.WithRawResponse.Files.Upload(parameters);
FileUploadResponse deserialized = await response.Deserialize();
Console.WriteLine(deserialized);

URL generation

The ImageKit SDK provides a powerful Helper.BuildUrl() method for generating optimized image and video URLs with transformations. Here are examples ranging from simple URLs to complex transformations with overlays and signed URLs.

Basic URL generation

Generate a simple URL without any transformations:

using Imagekit;
using Imagekit.Models;

ImageKitClient client = new()
{
    PrivateKey = "private_key_xxx",
};

string url = client.Helper.BuildUrl(new SrcOptions
{
    UrlEndpoint = "https://ik.imagekit.io/your_imagekit_id",
    Src = "/path/to/image.jpg",
});
Console.WriteLine(url);
// Result: https://ik.imagekit.io/your_imagekit_id/path/to/image.jpg

URL generation with transformations

Apply common transformations like resizing, cropping, and format conversion:

using Imagekit;
using Imagekit.Models;

string url = client.Helper.BuildUrl(new SrcOptions
{
    UrlEndpoint = "https://ik.imagekit.io/your_imagekit_id",
    Src = "/path/to/image.jpg",
    Transformation =
    [
        new Transformation
        {
            Width = 400,
            Height = 300,
            Crop = Crop.MaintainRatio,
            Quality = 80,
            Format = Format.Webp,
        },
    ],
});
Console.WriteLine(url);
// Result: https://ik.imagekit.io/your_imagekit_id/path/to/image.jpg?tr=w-400,h-300,q-80,c-maintain_ratio,f-webp

URL generation with image overlay

Add image overlays to your base image:

using Imagekit;
using Imagekit.Models;

string url = client.Helper.BuildUrl(new SrcOptions
{
    UrlEndpoint = "https://ik.imagekit.io/your_imagekit_id",
    Src = "/path/to/base-image.jpg",
    Transformation =
    [
        new Transformation
        {
            Width = 500,
            Height = 400,
            Overlay = new ImageOverlay("/path/to/overlay-logo.png")
            {
                Position = new OverlayPosition { X = "10", Y = "10" },
                Transformation = [new Transformation { Width = 100, Height = 50 }],
            },
        },
    ],
});
Console.WriteLine(url);
// Result: URL with image overlay positioned at x:10, y:10

URL generation with text overlay

Add customized text overlays:

using Imagekit;
using Imagekit.Models;

string url = client.Helper.BuildUrl(new SrcOptions
{
    UrlEndpoint = "https://ik.imagekit.io/your_imagekit_id",
    Src = "/path/to/base-image.jpg",
    Transformation =
    [
        new Transformation
        {
            Width = 600,
            Height = 400,
            Overlay = new TextOverlay("Sample Text Overlay")
            {
                Position = new OverlayPosition { X = "50", Y = "50", Focus = Focus.Center },
                Transformation =
                [
                    new TextOverlayTransformation
                    {
                        FontSize = 40,
                        FontFamily = "Arial",
                        FontColor = "FFFFFF",
                        Typography = "b", // bold
                    },
                ],
            },
        },
    ],
});
Console.WriteLine(url);
// Result: URL with bold white Arial text overlay at center position

URL generation with multiple overlays

Combine multiple overlays for complex compositions:

using Imagekit;
using Imagekit.Models;

string url = client.Helper.BuildUrl(new SrcOptions
{
    UrlEndpoint = "https://ik.imagekit.io/your_imagekit_id",
    Src = "/path/to/base-image.jpg",
    Transformation =
    [
        new Transformation
        {
            Width = 800,
            Height = 600,
            Overlay = new TextOverlay("Header Text")
            {
                Position = new OverlayPosition { X = "20", Y = "20" },
                Transformation =
                [
                    new TextOverlayTransformation { FontSize = 30, FontColor = "000000" },
                ],
            },
        },
        new Transformation
        {
            Overlay = new ImageOverlay("/watermark.png")
            {
                Position = new OverlayPosition { Focus = Focus.BottomRight },
                Transformation = [new Transformation { Width = 100, Opacity = 70 }],
            },
        },
    ],
});
Console.WriteLine(url);
// Result: URL with text overlay at top-left and semi-transparent watermark at bottom-right

Signed URLs for secure delivery

Generate signed URLs that expire after a specified time for secure content delivery:

using Imagekit;
using Imagekit.Models;

// Generate a signed URL that expires in 1 hour (3600 seconds)
string url = client.Helper.BuildUrl(new SrcOptions
{
    UrlEndpoint = "https://ik.imagekit.io/your_imagekit_id",
    Src = "/private/secure-image.jpg",
    Transformation = [new Transformation { Width = 400, Height = 300, Quality = 90 }],
    Signed = true,
    ExpiresIn = 3600, // URL expires in 1 hour
});
Console.WriteLine(url);
// Result: URL with signature parameters (?ik-t=timestamp&ik-s=signature)

// Generate a signed URL that doesn't expire
string permanentSignedUrl = client.Helper.BuildUrl(new SrcOptions
{
    UrlEndpoint = "https://ik.imagekit.io/your_imagekit_id",
    Src = "/private/secure-image.jpg",
    Signed = true,
    // No ExpiresIn means the URL won't expire
});
Console.WriteLine(permanentSignedUrl);
// Result: URL with signature parameter (?ik-s=signature)

Using Raw transformations for undocumented features

ImageKit frequently adds new transformation parameters that might not yet be documented in the SDK. You can use the Raw parameter to access these features or create custom transformation strings:

using Imagekit;
using Imagekit.Models;

string url = client.Helper.BuildUrl(new SrcOptions
{
    UrlEndpoint = "https://ik.imagekit.io/your_imagekit_id",
    Src = "/path/to/image.jpg",
    Transformation =
    [
        new Transformation { Width = 400, Height = 300 },
        new Transformation { Raw = "something-new" },
    ],
});
Console.WriteLine(url);
// Result: https://ik.imagekit.io/your_imagekit_id/path/to/image.jpg?tr=w-400,h-300:something-new

Authentication parameters for client-side uploads

Generate authentication parameters for secure client-side file uploads:

using Imagekit;

ImageKitClient client = new()
{
    PrivateKey = "private_key_xxx",
};

// Generate authentication parameters for client-side uploads
var authParams = client.Helper.GetAuthenticationParameters();
Console.WriteLine(authParams);
// Result: AuthenticationParameters { Token = "<uuid-token>", Expire = <timestamp>, Signature = "<hmac-signature>" }

// Generate with custom token and expiry (seconds from now)
var customAuthParams = client.Helper.GetAuthenticationParameters("my-custom-token", 1800);
Console.WriteLine(customAuthParams);
// Result: AuthenticationParameters { Token = "my-custom-token", Expire = 1800, Signature = "<hmac-signature>" }

These authentication parameters can be used in client-side upload forms to securely upload files without exposing your private API key.

Webhook verification

For detailed information about webhook setup, signature verification, and handling different webhook events, refer to the ImageKit webhook documentation.

Error handling

The SDK throws custom unchecked exception types:

  • ImageKitApiException: Base class for API errors. See this table for which exception subclass is thrown for each HTTP status code:
Status Exception
400 ImageKitBadRequestException
401 ImageKitUnauthorizedException
403 ImageKitForbiddenException
404 ImageKitNotFoundException
422 ImageKitUnprocessableEntityException
429 ImageKitRateLimitException
5xx ImageKit5xxException
others ImageKitUnexpectedStatusCodeException

Additionally, all 4xx errors inherit from ImageKit4xxException.

  • ImageKitIOException: I/O networking errors.

  • ImageKitInvalidDataException: Failure to interpret successfully parsed data. For example, when accessing a property that's supposed to be required, but the API unexpectedly omitted it from the response.

  • ImageKitException: Base class for all exceptions.

Network options

Retries

The SDK automatically retries 2 times by default, with a short exponential backoff between requests.

Only the following error types are retried:

  • Connection errors (for example, due to a network connectivity problem)
  • 408 Request Timeout
  • 409 Conflict
  • 429 Rate Limit
  • 5xx Internal

The API may also explicitly instruct the SDK to retry or not retry a request.

To set a custom number of retries, configure the client using the MaxRetries method:

using Imagekit;

ImageKitClient client = new() { MaxRetries = 3 };

Or configure a single method call using WithOptions:

using System;

var response = await client
    .WithOptions(options =>
        options with { MaxRetries = 3 }
    )
    .Files.Upload(parameters);

Console.WriteLine(response);

Timeouts

Requests time out after 1 minute by default.

To set a custom timeout, configure the client using the Timeout option:

using System;
using Imagekit;

ImageKitClient client = new() { Timeout = TimeSpan.FromSeconds(42) };

Or configure a single method call using WithOptions:

using System;

var response = await client
    .WithOptions(options =>
        options with { Timeout = TimeSpan.FromSeconds(42) }
    )
    .Files.Upload(parameters);

Console.WriteLine(response);

Proxies

To route requests through a proxy, configure your client with a custom HttpClient:

using System.Net;
using System.Net.Http;
using Imagekit;

var httpClient = new HttpClient
(
    new HttpClientHandler
    {
        Proxy = new WebProxy("https://example.com:8080")
    }
);

ImageKitClient client = new() { HttpClient = httpClient };

Undocumented API functionality

The SDK is typed for convenient usage of the documented API. However, it also supports working with undocumented or not yet supported parts of the API.

Parameters

To set undocumented parameters, a constructor exists that accepts dictionaries for additional header, query, and body values. If the method type doesn't support request bodies (e.g. GET requests), the constructor will only accept a header and query dictionary.

using System.Collections.Generic;
using System.Text.Json;
using Imagekit.Core;
using Imagekit.Models.Files;

FileUploadParams parameters = new
(
    rawHeaderData: new Dictionary<string, JsonElement>()
    {
        { "Custom-Header", JsonSerializer.SerializeToElement(42) }
    },

    rawQueryData: new Dictionary<string, JsonElement>()
    {
        { "custom_query_param", JsonSerializer.SerializeToElement(42) }
    },

    rawBodyData: new Dictionary<string, MultipartJsonElement>()
    {
        { "custom_body_param", JsonSerializer.SerializeToElement(42) }
    }
)
{
    // Documented properties can still be added here.
    // In case of conflict, these parameters take precedence over the custom parameters.
    Expire = 0
};

The raw parameters can also be accessed through the RawHeaderData, RawQueryData, and RawBodyData (if available) properties.

This can also be used to set a documented parameter to an undocumented or not yet supported value, as long as the parameter is optional. If the parameter is required, omitting its init property will result in a compile-time error. To work around this, the FromRawUnchecked method can be used:

using System.Collections.Generic;
using System.Text.Json;
using Imagekit.Models.Files;

var parameters = FileUploadParams.FromRawUnchecked
(

    rawHeaderData: new Dictionary<string, JsonElement>(),
    rawQueryData: new Dictionary<string, JsonElement>(),
    rawBodyData: new Dictionary<string, JsonElement>
    {
        {
            "file",
            JsonSerializer.SerializeToElement("custom value")
        }
    }
);

Nested Parameters

Undocumented properties, or undocumented values of documented properties, on nested parameters can be set similarly, using a dictionary in the constructor of the nested parameter.

using System.Collections.Generic;
using System.Text.Json;
using Imagekit.Models.Files;

FileUploadParams parameters = new()
{
    Transformation = new
    (
        new Dictionary<string, JsonElement>
        {
            { "custom_nested_param", JsonSerializer.SerializeToElement(42) }
        }
    )
};

Required properties on the nested parameter can also be changed or omitted using the FromRawUnchecked method:

using System.Collections.Generic;
using System.Text.Json;
using Imagekit.Models.Files;

FileUploadParams parameters = new()
{
    Transformation = Transformation.FromRawUnchecked
    (
        new Dictionary<string, JsonElement>
        {
            { "required_property", JsonSerializer.SerializeToElement("custom value") }
        }
    )
};

Response properties

To access undocumented response properties, the RawData property can be used:

using System.Text.Json;

var response = await client.Files.Upload(parameters);
if (response.RawData.TryGetValue("my_custom_key", out JsonElement value))
{
    // Do something with `value`
}

RawData is a IReadonlyDictionary<string, JsonElement>. It holds the full data received from the API server.

Response validation

In rare cases, the API may return a response that doesn't match the expected type. For example, the SDK may expect a property to contain a string, but the API could return something else.

By default, the SDK will not throw an exception in this case. It will throw ImageKitInvalidDataException only if you directly access the property.

If you would prefer to check that the response is completely well-typed upfront, then either call Validate:

var response = await client.Files.Upload(parameters);
response.Validate();

Or configure the client using the ResponseValidation option:

using Imagekit;

ImageKitClient client = new() { ResponseValidation = true };

Or configure a single method call using WithOptions:

using System;

var response = await client
    .WithOptions(options =>
        options with { ResponseValidation = true }
    )
    .Files.Upload(parameters);

Console.WriteLine(response);

Semantic versioning

This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:

  1. Changes to library internals which are technically public but not intended or documented for external use. (Please open a GitHub issue to let us know if you are relying on such internals.)
  2. Changes that we do not expect to impact the vast majority of users in practice.

We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.

We are keen for your feedback; please open an issue with questions, bugs, or suggestions.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on Imagekit:

Package Downloads
AlphaReds.Core.Common

Common class for AlphaReds project

IglooSoftware.Sdk.ImageKit

Igloo SDK for using ImageKit

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
6.0.0 70 5/18/2026
5.0.0 67,077 9/10/2024
4.0.2 13,821 5/13/2024
4.0.1 53,465 1/17/2023
4.0.0 11,061 10/26/2022
3.1.6 77,069 7/21/2021
3.1.5 1,929 6/11/2021
3.1.4 1,188 4/12/2021
3.1.3 1,971 11/4/2020
3.1.0 781 9/2/2020
3.0.4 1,035 8/19/2020
3.0.3 8,169 9/20/2019
2.1.0 865 7/4/2019
2.0.0 808 7/2/2019
1.5.0 1,055 12/13/2018
1.4.0 1,489 12/13/2018
Loading failed