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
- Upload images
- Rendering images
- Applying common image manipulations
- Server-side file uploading
- ImageKit Media API
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
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)
# 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.
publicKey
andprivateKey
parameters are required as these would be used for all ImageKit API, server-side upload, and generating tokens for client-side file upload. You can get these parameters from the developer section in your ImageKit dashboard - https://imagekit.io/dashboard/developer/api-keys.urlEndpoint
is also a required parameter. You can get the value of URL endpoint from your ImageKit dashboard - https://imagekit.io/dashboard/url-endpoints.
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
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:
# 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
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
image_url = imagekit.url( { "path": "/default-image.jpg", "transformation": [{"height": "200", "width": "200", "raw": "ar-4-3,q-40"}], } )
Transformation URL:
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.
Option | Description |
---|---|
urlEndpoint | Optional. 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/ |
path | Conditional. 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. |
src | Conditional. 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. |
transformation | Optional. 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. |
transformationPosition | Optional. 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. |
queryParameters | Optional. 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. |
signed | Optional. 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. |
expireSeconds | Optional. 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:
- Chained Transformations
- Image Enhancement & Color Manipulation
- Resizing images
- Quality manipulation
- Adding overlays
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.
[ '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
image_url = imagekit.url( { "path": "/default-image.jpg", "transformation": [{"height": "200", "width": "200"}], "transformation_position": "query", } )
Transformation URL:
https://ik.imagekit.io/fl0osl7rq9/default-image.jpg?tr=h-200%2Cw-200
Output Image:
Now, rotate the image by 90 degrees.
Example
image_url = imagekit.url( { "path": "/default-image.jpg", "transformation": [{"height": "300", "width": "200"}, {"rt": "90"}], } )
Chained Transformation URL:
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
image_url = imagekit.url( { "path": "/default-image.jpg", "transformation": [{"rt": "90"}, {"height": "300", "width": "200"}], } )
Chained Transformation URL:
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
image_url = imagekit.url( { "path": "/default-image.jpg", "transformation": [ { "format": "jpg", "progressive": "true", "effect_sharpen": "-", "effect_contrast": "1", } ], } )
Transformation URL:
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
image_url = imagekit.url( { "path": "/default-image.jpg", "transformation": [{"height": "200", "width": "200"}], } )
Transformation URL:
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
image_url = imagekit.url( { "path": "/default-image.jpg", "transformation": [{"quality": "40"}], } )
Transformation URL:
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:
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
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:
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
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:
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
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 Name | Translates to parameter |
---|---|
height | h |
width | w |
aspect_ratio | ar |
quality | q |
crop | c |
crop_mode | cm |
x | x |
y | y |
focus | fo |
format | f |
radius | r |
background | bg |
border | b |
rotation | rt |
blur | bl |
named | n |
progressive | pr |
lossless | lo |
trim | t |
metadata | md |
color_profile | cp |
default_image | di |
dpr | dpr |
effect_sharpen | e-sharpen |
effect_usm | e-usm |
effect_contrast | e-contrast |
effect_gray | e-grayscale |
effect_shadow | e-shadow |
effect_gradient | e-gradient |
original | orig |
raw | replaced 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
result = imagekit.upload_file( file=open("sample.jpg", "rb"), file_name="test-file.jpg", )
Response
# 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
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.