Getting started

Integration & migration

Image & video API

DAM user guide

API overview

Account

Python

Real-time image & video resizing, automatic optimization, and file uploading in Python application using ImageKit.io.


This quick start guide shows you how to integrate ImageKit into the Python application. The code samples covered here are hosted on GitHub.

SDK code is also hosted on Github along with the SDK documentation and examples.

This guide walks you through the following topics:

Setting up ImageKit Python SDK

We will create a new Python application for this tutorial and work with it.

First, we will install the imagekitio dependencies in our machine by applying the following things to our application.

Install dependencies

Copy
pip install imagekitio

Quick Examples

It loads the imagekitio dependency in our application. Before the SDK can be used, let's learn about and configure the requisite authentication parameters that need to be provided to the SDK.

Initialize SDK

In the main file of project, add your public and private API keys, as well as the URL Endpoint parameters for authentication, (You can find these keys in the Developer section of your ImageKit Dashboard)

Copy
#  Put essential values of keys [UrlEndpoint, PrivateKey, PublicKey]
from imagekitio import ImageKit
imagekit = ImageKit(
    private_key='your private_key',
    public_key='your public_key',
    url_endpoint = 'your url_endpoint'
)

The imagekitio client is configured with user-specific credentials.

Uploading images in python app

There are different ways to upload the file in imagekitio. Let's upload the remote file to imagekitio using the following code:

Example

Copy
url = "https://file-examples.com/wp-content/uploads/2017/10/file_example_JPG_100kB.jpg"
upload = imagekit.upload_file(
        file=url,
        file_name="test-url.jpg",
        options=UploadFileRequestOptions(
            response_fields=["is_private_file", "tags"],
            tags=["tag1", "tag2"]
        )
    )

The output should be like this:

Copy
# Final Result
print(upload)
<imagekitio.models.results.UploadFileResult.UploadFileResult object at 0x7f9f0ceb0dd8>

# Raw Response
print("raw", upload.response_metadata.raw)
upload remote file =>
{
    'fileId': '6311960051c0c0bdd51cff53',
    'name': 'test-url_9lQZRkh8J.jpg',
    'size': 1222,
    'versionInfo': {
        'id': '6311960051c0c0bdd51cff53',
        'name': 'Version 1'
    },
    'filePath': '/test-url_9lQZRkh8J.jpg',
    'url': 'https://ik.imagekit.io/your_imagekit_id/test-url_9lQZRkh8J.jpg',
    'fileType': 'non-image',
    'tags': ['tag1', 'tag2'],
    'AITags': None,
    'isPrivateFile': False
}

Congratulation, the file was uploaded successfully.

Generating URL for rendering images in python app

Here, declare a variable to store the image URL generated by the SDK. Like this:

Example

Copy

image_url = imagekit.url({
            "path": "/default-image.jpg"
        }
    )

Now, image_url has the URL https://ik.imagekit.io/<your_imagekit_id>/default-image.jpg stored in it. This fetches the image from the URL stored in image_url.

Open the URL in the browser. It should now display this default image in its full size:

Common image manipulation in Python App

Let’s now learn how to manipulate images using image transformations.

Height and width manipulation

To resize an image or video along with its height or width, we need to pass the transformation option in imageKit.url() method.

Let's resize the default image to 200px height and width:

Example

Copy
image_url = imagekit.url(
        {
            "path": "/default-image.jpg",
            "transformation": [{"height": "200", "width": "200", "raw": "ar-4-3,q-40"}],
        }
    )

Transformation URL:

Copy
https://ik.imagekit.io/fl0osl7rq9/tr:h-200,w-200,raw-ar-4-3,q-40/default-image.jpg

Refresh your browser with a new URL to get the resized image.

The imageKit.url() method accepts the following parameters.

OptionDescription
urlEndpointOptional. The base URL is to be appended before the path of the image. If not specified, the URL Endpoint specified at the time of SDK initialization is used. For example, https://ik.imagekit.io/your_imagekit_id/endpoint/
pathConditional. This is the path on which the image exists. For example, /path/to/image.jpg. Either the path or src parameter needs to be specified for URL generation.
srcConditional. This is the complete URL of an image already mapped to ImageKit. For example, https://ik.imagekit.io/your_imagekit_id/endpoint/path/to/image.jpg. Either the path or src parameter needs to be specified for URL generation.
transformationOptional. An array of objects specifying the transformation to be applied in the URL. The transformation name and the value should be specified as a key-value pair in the object. Different steps of a chained transformation can be specified as different objects of the array. The complete List of supported transformations in the SDK and some examples of using them are given later. If you use a transformation name that is not specified in the SDK, it gets applied as it is in the URL.
transformationPositionOptional. The default value is path, which places the transformation string as a path parameter in the URL. It can also be specified as query, which adds the transformation string as the query parameter tr in the URL. The transformation string is always added as a query parameter if you use the src parameter to create the URL.
queryParametersOptional. These are the other query parameters that you want to add to the final URL. These can be any query parameters and are not necessarily related to ImageKit. Especially useful if you want to add some versioning parameters to your URLs.
signedOptional. Boolean. The default value is false. If set to true, the SDK generates a signed image URL adding the image signature to the image URL.
expireSecondsOptional. Integer. It is used along with the signed parameter. It specifies the time in seconds from now when the signed URL will expire. If specified, the URL contains the expiry timestamp in the URL, and the image signature is modified accordingly.

Applying Chained Transformations, Common Image Manipulations & Signed URL

This section covers the basics:

The Python SDK gives a name to each transformation parameter e.g. height for h and width for w parameter. It makes your code more readable. See the Full List of supported transformations.

πŸ‘‰ If the property does not match any of the available options, it is added as it is.

Copy
[
    'effectGray' => 'e-grayscale'
]
# and
[
    'e-grayscale' => ''
]
# works the same

πŸ‘‰ Note that you can also use the h and w parameters instead of height and width.

For more examples, check the Demo Application.

Chained Transformations

Chained transformations provide a simple way to control the sequence in which transformations are applied.

Chained Transformations as a query parameter

Let's try it out by resizing an image, then rotating it:

Example

Copy
image_url = imagekit.url(
        {
            "path": "/default-image.jpg",
            "transformation": [{"height": "200", "width": "200"}],
            "transformation_position": "query",
        }
    )

Transformation URL:

Copy
https://ik.imagekit.io/fl0osl7rq9/default-image.jpg?tr=h-200%2Cw-200

Output Image:

Now, rotate the image by 90 degrees.

Example

Copy
image_url = imagekit.url(
        {
            "path": "/default-image.jpg",
            "transformation": [{"height": "300", "width": "200"}, {"rt": "90"}],
        }
    )

Chained Transformation URL:

Copy
https://ik.imagekit.io/fl0osl7rq9/tr:h-300,w-200:rt-90/default-image.jpg

Output Image:

Let's flip the order of transformation and see what happens.

Example

Copy
image_url = imagekit.url(
        {
            "path": "/default-image.jpg",
            "transformation": [{"rt": "90"}, {"height": "300", "width": "200"}],
        }
    )

Chained Transformation URL:

Copy
https://ik.imagekit.io/fl0osl7rq9/tr:rt-90:h-300,w-200/default-image.jpg

Output Image:

Image enhancement and color manipulation

Some transformations like Contrast stretch, Sharpen and Unsharp mask can be added to the URL with or without any other value. To use such transforms without specifying a value, specify the value as "-" in the transformation object. Otherwise, specify the value that you want to be added to this transformation.

Example

Copy
image_url = imagekit.url(
        {
            "path": "/default-image.jpg",
            "transformation": [
                {
                    "format": "jpg",
                    "progressive": "true",
                    "effect_sharpen": "-",
                    "effect_contrast": "1",
                }
            ],
        }
    )

Transformation URL:

Copy
https://ik.imagekit.io/fl0osl7rq9/tr:f-jpg,pr-true,e-sharpen,e-contrast-1/default-image.jpg

Output Image:

Resizing images

Let's resize the image to a width of 200 and a height of 200. Check detailed instructions on Resize, Crop, and Other Common Transformations.

Example

Copy
image_url = imagekit.url(
        {
            "path": "/default-image.jpg",
            "transformation": [{"height": "200", "width": "200"}],
        }
    )

Transformation URL:

Copy
https://ik.imagekit.io/fl0osl7rq9/tr:h-200,w-200/default-image.jpg

Output Image:

Quality manipulation

You can use the Quality Parameter to change quality like this.

Example

Copy
image_url = imagekit.url(
        {
            "path": "/default-image.jpg",
            "transformation": [{"quality": "40"}],
        }
    )

Transformation URL:

Copy
https://ik.imagekit.io/fl0osl7rq9/tr:q-40/default-image.jpg

Output Image:

Adding overlays

ImageKit.io enables you to apply overlays to images and videos using the raw parameter with the concept of layers. The raw parameter facilitates incorporating transformations directly in the URL. A layer is a distinct type of transformation that allows you to define an asset to serve as an overlay, along with its positioning and additional transformations.

Text as overlays

You can add any text string over a base video or image using a text layer (l-text).

For example:

Copy
image_url = imagekit.url({
    "path": "/default-image",
    "url_endpoint": "https://ik.imagekit.io/your_imagekit_id/endpoint/",
    "transformation": [{
        "height": "300",
        "width": "400",
        "raw": "l-text,i-Imagekit,fs-50,l-end"
    }],
})

Sample Result URL

Copy
https://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400,l-text,i-Imagekit,fs-50,l-end/default-image.jpg

Output Image:

Image as overlays

You can add an image over a base video or image using an image layer (l-image).

For example:

Copy
image_url = imagekit.url({
    "path": "/default-image",
    "url_endpoint": "https://ik.imagekit.io/your_imagekit_id/endpoint/",
    "transformation": [{
        "height": "300",
        "width": "400",
        "raw": "l-image,i-default-image.jpg,w-100,b-10_CDDC39,l-end"
    }],
})

Sample Result URL

Copy
https://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400,l-image,i-default-image.jpg,w-100,b-10_CDDC39,l-end/default-image.jpg

Output Image:

Solid color blocks as overlays

You can add solid color blocks over a base video or image using an image layer (l-image).

For example:

Copy
image_url = imagekit.url({
    "path": "/default-image.jpg",
    "url_endpoint": "https://ik.imagekit.io/your_imagekit_id/endpoint/",
    "transformation": [{
        "height": "300",
        "width": "400",
        "raw": "l-image,i-ik_canvas,bg-FF0000,w-300,h-100,l-end"
    }],
})

Sample Result URL

Copy
https://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400,l-image,i-ik_canvas,bg-FF0000,w-300,h-100,l-end/default-image.jpg

Output Image:

List of supported transformations

See the complete list of image and video transformations supported in ImageKit. The SDK gives a name to each transformation parameter e.g. height for h and width for w parameter. It makes your code more readable. If the property does not match any of the following supported options, it is added as it is.

If you want to generate transformations in your application and add them to the URL as it is, use the raw parameter.

Supported Transformation NameTranslates to parameter
heighth
widthw
aspect_ratioar
qualityq
cropc
crop_modecm
xx
yy
focusfo
formatf
radiusr
backgroundbg
borderb
rotationrt
blurbl
namedn
progressivepr
losslesslo
trimt
metadatamd
color_profilecp
default_imagedi
dprdpr
effect_sharpene-sharpen
effect_usme-usm
effect_contraste-contrast
effect_graye-grayscale
effect_shadowe-shadow
effect_gradiente-gradient
originalorig
rawreplaced by the parameter value

Server-side File Upload

The SDK provides a simple interface using the imagekit.upload_file() method to upload files to the ImageKit Media Library. Check all the supported parameters and details.

Example

Copy
result = imagekit.upload_file(
        file=open("sample.jpg", "rb"),
        file_name="test-file.jpg",
    )

Response

Copy
# Final Result
print(upload)
<imagekitio.models.results.UploadFileResult.UploadFileResult object at 0x7f9f0ceb0dd8>

# Raw Response
{
    'fileId': '631197af51c0c0bdd51f77da',
    'name': 'test-file_X4nk4kIuC.jpg',
    'size': 59,
    'versionInfo': {
        'id': '631197af51c0c0bdd51f77da',
        'name': 'Version 1'
    },
    'filePath': '/test-file_X4nk4kIuC.jpg',
    'url': 'https://ik.imagekit.io/zv3rkhsym/test-file_X4nk4kIuC.jpg',
    'fileType': 'non-image',
    'AITags': None
}

Optional Parameters

Please refer to Server Side File Upload - Request Structure for a detailed explanation of mandatory and optional parameters.

Example

Copy
result = imagekit.upload_file(
        file=open("sample.jpg", "rb"),
        file_name="testing-file.jpg",
        options=UploadFileRequestOptions(
            use_unique_file_name=False,
            tags=["tag-1", "tag-2"],
            folder="/testing-folder/",
            is_private_file=True,
            custom_coordinates="10,10,20,20",
            response_fields=["is_private_file", "tags"],
            extensions=[
                {"name": "remove-bg", "options": {"add_shadow": True, "bg_color": "pink"}},
                {"name": "google-auto-tagging", "minConfidence": 80, "maxTags": 10}
            ],
            webhook_url="url",
            overwrite_file=True,
            overwrite_ai_tags=False,
            overwrite_tags=False,
            overwrite_custom_metadata=True,
            custom_metadata={"test": 11}
            transformation = { 
                "pre": 'l-text,i-Imagekit,fs-50,l-end',
                "post": [{ "type": 'transformation', "value": 'w-100' }] 
            }
        ),
    )

Media management

The SDK provides easy-to-use methods for all APIs. Learn more from the SDK documentation.