Getting started

Integration & migration

Image & video API

DAM user guide

API overview

Account

Java

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


This quick start guide shows you how to integrate ImageKit into the Java 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 Java SDK

We will create a new Java 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

  • Java 1.8 or later

Gradle users

Step 1. Add the JitPack repository to your build file

Copy
allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

Step 2. Add the dependency on project's build.gradle:

Copy
dependencies {
        implementation 'com.github.imagekit-developer:imagekit-java:2.0.0'
}

Maven users

Step 1. Add the JitPack repository to your build file

Copy
<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>

Step 2. Add the dependency in the POM file:

Copy
<dependency>
    <groupId>com.github.imagekit-developer</groupId>
    <artifactId>imagekit-java</artifactId>
    <version>2.0.0</version>
</dependency>

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 with config.properties

Open or create the config.properties file and add your public and private API keys, as well as the URL Endpoint, as follows no need to use quote('or ") in values: (You can find these keys in the Developer section of your ImageKit Dashboard)

Copy
//  Put essential values of keys [UrlEndpoint, PrivateKey, PublicKey]
UrlEndpoint=your_url_endpoint
PrivateKey=your_private_key
PublicKey=your_public_key

Initialize SDK via Create an ImageKit Instance

Copy
ImageKit imageKit = ImageKit.getInstance();
Configuration config = new Configuration(your_public_key, your_private_key, your_url_endpoint);
imageKit.setConfig(config);

The imagekitio client is configured with user-specific credentials.

Uploading images in java 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
FileCreateRequest fileCreateRequest =new FileCreateRequest("https://ik.imagekit.io/ikmedia/red_dress_woman.jpeg",  "women_in_red.jpg");
List<String> responseFields=new ArrayList<>();
responseFields.add("thumbnail");
responseFields.add("tags");
responseFields.add("customCoordinates");
fileCreateRequest.setResponseFields(responseFields);
List<String> tags=new ArrayList<>();
tags.add("Software");
tags.add("Developer");
tags.add("Engineer");
fileCreateRequest.setTags(tags);
Result result=ImageKit.getInstance().upload(fileCreateRequest);

The output should like this:

Copy
upload remote file => 
{:response=>
    Result{
        isSuccessful=true,
        message='null',
        help='null',
        fileId='62ac768c7db9372ad1f07f0b',
        name='sample-image11__Unm_54pI.jpg',
        url='https://ik.imagekit.io/zv3rkhsym/sample-image11__Unm_54pI.jpg',
        thumbnail='null',
        height=0,
        width=0,
        size=169092,
        filePath='/sample-image11__Unm_54pI.jpg',
        tags='[Software, Developer, Engineer]',
        isPrivateFile=false,
        customCoordinates='null',
        fileType='non-image',
        aiTags=null,
        versionInfo={"id":"62ac768c7db9372ad1f07f0b","name":"Version 1"},
        customMetadata=null,
        embeddedMetadata=null,
        extensionStatus=null,
        type='null',
        mime='null',
        hasAlpha=null,
        createdAt=null,
        updatedAt=null
    }
}

Congratulation file uploaded successfully.

Generating URL for rendering images in java app

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

Example

Copy
Map<String, Object> options=new HashMap();
options.put("path",baseFile.getFilePath());

String image_url=ImageKit.getInstance().getUrl(options);

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 on browser, it should now display this default image in its full size:

Common image manipulation in java 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.getInstance().getUrl() method.

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

Example

Copy
List<Map<String, String>> transformation=new ArrayList<Map<String, String>>();
Map<String, String> scale=new HashMap<>();
scale.put("height","200");
scale.put("width","200");
scale.put("raw", "ar-4-3,q-40");
transformation.add(scale);
Map<String, Object> options=new HashMap();
options.put("path", "/default-image.jpg");
options.put("transformation", transformation);

String image_url=ImageKit.getInstance().getUrl(options);

Transformation URL:

Copy
https://ik.imagekit.io/zv3rkhsym/tr:w-200,h-200,ar-4-3,q-40/default-image.jpg?ik-sdk-version=java-1.0.3

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

The ageKit.getInstance().getUrl 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 Java 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
List<Map<String, String>> transformation=new ArrayList<Map<String, String>>();
Map<String, String> scale=new HashMap<>();
scale.put("height","200");
scale.put("width","200");
transformation.add(scale);
Map<String, Object> options=new HashMap();
options.put("path", "/default-image.jpg");
options.put("transformation", transformation);
options.put("transformationPosition", "query");

String image_url=ImageKit.getInstance().getUrl(options);

Transformation URL:

Copy
https://ik.imagekit.io/zv3rkhsym/default-image.jpg?ik-sdk-version=java-1.0.3&tr:w-200,h-200

Output Image:

Now, rotate the image by 90 degrees.

Example

Copy
List<Map<String, String>> transformation=new ArrayList<Map<String, String>>();
Map<String, String> scale=new HashMap<>();
scale.put("height","300");
scale.put("width","200");
transformation.add(scale);
Map<String, String> rotate=new HashMap<>();
rotate.put("rt","90");
transformation.add(rotate);
Map<String, Object> options=new HashMap();
options.put("path", "/default-image.jpg");
options.put("transformation", transformation);

String image_url=ImageKit.getInstance().getUrl(options);

Chained Transformation URL:

Copy
https://ik.imagekit.io/zv3rkhsym/tr:w-200,h-300:rt-90/default-image.jpg?ik-sdk-version=java-1.0.3

Output Image:

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

Example

Copy
List<Map<String, String>> transformation=new ArrayList<Map<String, String>>();
Map<String, String> rotate=new HashMap<>();
rotate.put("rt","90");
transformation.add(rotate);
Map<String, String> scale=new HashMap<>();
scale.put("height","300");
scale.put("width","200");
transformation.add(scale);
Map<String, Object> options=new HashMap();
options.put("path", "/default-image.jpg");
options.put("transformation", transformation);

String image_url=ImageKit.getInstance().getUrl(options);

Chained Transformation URL:

Copy
https://ik.imagekit.io/zv3rkhsym/tr:rt-90:w-200,h-300/default-image.jpg?ik-sdk-version=java-1.0.3

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
Map<String, String> format=new HashMap<>();
format.put("format","jpg");
format.put("progressive","true");
format.put("effectSharpen","-");
format.put("effectContrast","1");

List<Map<String, String>> transformation= new ArrayList<>();
transformation.add(format);
Map<String, Object> options=new HashMap();
options.put("path", "/default-image.jpg");
options.put("transformation", transformation);

String image_url=ImageKit.getInstance().getUrl(options);

Transformation URL:

Copy
https://ik.imagekit.io/zv3rkhsym/tr:f-jpg,pr-true,e-sharpen,e-contrast-1/default-image.jpg?ik-sdk-version=java-1.0.3

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
List<Map<String, String>> transformation=new ArrayList<Map<String, String>>();
Map<String, String> scale=new HashMap<>();
scale.put("height","200");
scale.put("width","200");
transformation.add(scale);
Map<String, Object> options=new HashMap();
options.put("path", "/default-image.jpg");
options.put("transformation", transformation);

String image_url=ImageKit.getInstance().getUrl(options);

Transformation URL:

Copy
https://ik.imagekit.io/zv3rkhsym/tr:w-200,h-200/default-image.jpg?ik-sdk-version=java-1.0.3

Output Image:

Quality manipulation

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

Example

Copy
List<Map<String, String>> transformation=new ArrayList<Map<String, String>>();
Map<String, String> quality=new HashMap<>();
quality.put("quality","40");
transformation.add(quality);
Map<String, Object> options=new HashMap();
options.put("path", "/default-image.jpg");
options.put("transformation", transformation);

String image_url=ImageKit.getInstance().getUrl(options);

Transformation URL:

Copy
https://ik.imagekit.io/zv3rkhsym/tr:q-40/default-image.jpg?ik-sdk-version=java-1.0.3

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
List<Map<String, String>> transformation=new ArrayList<Map<String, String>>();
Map<String, String> scale=new HashMap<>();
scale.put("height","300");
scale.put("width","400");
scale.put("raw", "l-text,i-Imagekit,fs-50,l-end");
transformation.add(scale);

Map<String, Object> options=new HashMap();
options.put("src","https://ik.imagekit.io/your_imagekit_id/default-image.jpg");
options.put("transformation", transformation);

String url = ImageKit.getInstance().getUrl(options);

Sample Result URL

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

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
List<Map<String, String>> transformation=new ArrayList<Map<String, String>>();
Map<String, String> scale=new HashMap<>();
scale.put("height","300");
scale.put("width","400");
scale.put("raw", "l-image,i-default-image.jpg,w-100,b-10_CDDC39,l-end");
transformation.add(scale);

Map<String, Object> options=new HashMap();
options.put("src","https://ik.imagekit.io/your_imagekit_id/default-image.jpg");
options.put("transformation", transformation);

String url = ImageKit.getInstance().getUrl(options);

Sample Result URL

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

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
List<Map<String, String>> transformation=new ArrayList<Map<String, String>>();
Map<String, String> scale=new HashMap<>();
scale.put("height","300");
scale.put("width","400");
scale.put("raw", "l-image,i-ik_canvas,bg-FF0000,w-300,h-100,l-end");
transformation.add(scale);

Map<String, Object> options=new HashMap();
options.put("src","https://ik.imagekit.io/your_imagekit_id/default-image.jpg");
options.put("transformation", transformation);

String url = ImageKit.getInstance().getUrl(options);

Sample Result URL

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

Output Image:

Secure signed URL generation

You can use the SDK to generate a signed URL of an image, that expires in a given number of seconds.

Example

Copy
Map<String, Object> options=new HashMap();
options.put("path", "/default-image.jpg");
options.put("signed",true);
options.put("transformation", new ArrayList<Map<String, String>>());
options.put("expireSeconds",10);

String signed_image_url=ImageKit.getInstance().getUrl(options);

The above snippets create a signed URL with an expiry time of 10 seconds.

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
aspectRatioar
qualityq
cropc
cropModecm
xx
yy
focusfo
formatf
radiusr
backgroundbg
borderb
rotationrt
blurbl
namedn
progressivepr
losslesslo
trimt
metadatamd
colorProfilecp
defaultImagedi
dprdpr
effectSharpene-sharpen
effectUSMe-usm
effectContraste-contrast
effectGraye-grayscale
originalorig
rawreplaced by the parameter value

Server-side File Upload

The SDK provides a simple interface using the $imageKit->upload() or $imageKit->uploadFile() method to upload files to the ImageKit Media Library. Check all the supported parameters and details.

Example

Copy
FileCreateRequest fileCreateRequest = new FileCreateRequest(
    "your_file",            //  required, "binary", "base64" or "file url"
    "sample-image11.jpg"    //  required
);
Result result = ImageKit.getInstance().upload(fileCreateRequest);

Response

Copy
Result{
    isSuccessful=true,
    message='null',
    help='null',
    fileId='62b43109d23153217b8b8a36',
    name='sample_image_To_fa4v8vk7W.jpg',
    url='https://ik.imagekit.io/zv3rkhsym/sample_image_To_fa4v8vk7W.jpg',
    thumbnail='null',
    height=300,
    width=300,
    size=51085,
    filePath='/sample_image_To_fa4v8vk7W.jpg',
    tags='null',
    isPrivateFile=false,
    customCoordinates='null',
    fileType='image'
}

Optional Parameters

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

Example

Copy
FileCreateRequest fileCreateRequest = new FileCreateRequest(bytes, "your_file_name.jpg");
fileCreateRequest.setUseUniqueFileName(true);
fileCreateRequest.setPrivateFile(false);
JsonObject optionsInnerObject = new JsonObject();
optionsInnerObject.addProperty("add_shadow", true);
optionsInnerObject.addProperty("bg_colour", "green");
JsonObject innerObject1 = new JsonObject();
innerObject1.addProperty("name", "remove-bg");
innerObject1.add("options", optionsInnerObject);
JsonObject innerObject2 = new JsonObject();
innerObject2.addProperty("name", "google-auto-tagging");
innerObject2.addProperty("minConfidence", 5);
innerObject2.addProperty("maxTags", 95);
JsonArray jsonArray = new JsonArray();
jsonArray.add(innerObject1);
jsonArray.add(innerObject2);
fileCreateRequest.setExtensions(jsonArray);
List<String> responseFields = new ArrayList<>();
responseFields.add("thumbnail");
responseFields.add("tags");
responseFields.add("customCoordinates");
fileCreateRequest.setResponseFields(responseFields);
fileCreateRequest.setCustomCoordinates("10,10,40,40");
fileCreateRequest.setFolder("test");
List<String> tags = new ArrayList<>();
tags.add("tags-to-add-1");
tags.add("tags-to-add-2");
fileCreateRequest.setTags(tags);
fileCreateRequest.setWebhookUrl("https://webhook.site/c78d617f-33bc-40d9-9e61-608999721e2e");
fileCreateRequest.setOverwriteFile(true);
fileCreateRequest.setOverwriteAITags(true);
fileCreateRequest.setOverwriteTags(true);
fileCreateRequest.setOverwriteCustomMetadata(true);
JsonObject jsonObjectCustomMetadata = new JsonObject();
jsonObjectCustomMetadata.addProperty("test10", 10);
fileCreateRequest.setCustomMetadata(jsonObjectCustomMetadata);
Result result = ImageKit.getInstance().upload(fileCreateRequest);

Media management

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