Links

Plain Java

Real-time image 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 - https://github.com/imagekit-samples/quickstart/tree/master/java.
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
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Step 2. Add the dependency on project's build.gradle:
dependencies {
implementation 'com.github.imagekit-developer:imagekit-java:2.0.0'
}

Maven users

Step 1. Add the JitPack repository to your build file
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Step 2. Add the dependency in the POM file:
<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)
// 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

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

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:
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

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:
Image in its original dimensions (1000px * 1000px)

Common image manipulation in java App

Let’s now learn how to manipulate images using ImgeKit 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

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:
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.
Resized image (200px * 200px)
The ageKit.getInstance().getUrl 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:
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.
[
'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.

1. 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

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:
https://ik.imagekit.io/zv3rkhsym/default-image.jpg?ik-sdk-version=java-1.0.3&tr:w-200,h-200
Output Image:
Resized and cropped (200px * 300px)
Now, rotate the image by 90 degrees.

Example

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:
https://ik.imagekit.io/zv3rkhsym/tr:w-200,h-300:rt-90/default-image.jpg?ik-sdk-version=java-1.0.3
Output Image:
Resized, then rotated
Let's flip the order of transformation and see what happens.

Example

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:
https://ik.imagekit.io/zv3rkhsym/tr:rt-90:w-200,h-300/default-image.jpg?ik-sdk-version=java-1.0.3
Output Image:
Rotated, then resized

2. 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

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:
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:
Overlay image over another image

3. 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

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:
https://ik.imagekit.io/zv3rkhsym/tr:w-200,h-200/default-image.jpg?ik-sdk-version=java-1.0.3
Output Image:
Overlay image over another image

4. Quality manipulation

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

Example

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:
https://ik.imagekit.io/zv3rkhsym/tr:q-40/default-image.jpg?ik-sdk-version=java-1.0.3
Output Image:
Overlay image over another image

5. Adding overlays to images

ImageKit.io allows overlaying images or text over other images for watermarking or creating a dynamic banner using custom text.

Text overlay

Text overlay can be used to superimpose text on an image. For example:

Example

List<Map<String, String>> transformation=new ArrayList<Map<String, String>>();
Map<String, String> scale=new HashMap<>();
scale.put("height","300");
scale.put("width","300");
transformation.add(scale);
Map<String, String> overlay=new HashMap<>();
overlay.put("overlayText","ImageKit");
overlay.put("overlayTextFontSize","50");
overlay.put("overlayTextColor","0651D5");
transformation.add(overlay);
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:
https://ik.imagekit.io/zv3rkhsym/tr:w-300,h-300:ots-50,ot-ImageKit,otc-0651D5/default-image.jpg?ik-sdk-version=java-1.0.3
Output Image:
Text Overlay (300px * 300px)

Image overlay

Image overlay can be used to superimpose an image on another image. For example, we will upload a while logo image on this link into our account and use it for the overlay image.
Base Image: default-image.jpg
Overlay Image: logo-white_SJwqB4Nfe.png

Example

List<Map<String, String>> transformation=new ArrayList<Map<String, String>>();
Map<String, String> scale=new HashMap<>();
scale.put("height","300");
scale.put("width","300");
transformation.add(scale);
Map<String, String> overlay=new HashMap<>();
overlay.put("overlayImage","logo-white_SJwqB4Nfe.png");
transformation.add(overlay);
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:
https://ik.imagekit.io/zv3rkhsym/tr:w-300,h-300:oi-logo-white_SJwqB4Nfe.png/default-image.jpg?ik-sdk-version=java-1.0.3
Output Image:
Overlay image over another image

6. 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

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.
Signed URL generation

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
aspectRatio
ar
quality
q
crop
c
cropMode
cm
x
x
y
y
focus
fo
format
f
radius
r
background
bg
border
b
rotation
rt
blur
bl
named
n
overlayX
ox
overlayY
oy
overlayFocus
ofo
overlayHeight
oh
overlayWidth
ow
overlayImage
oi
overlayImageTrim
oit
overlayImageAspectRatio
oiar
overlayImageBackground
oibg
overlayImageBorder
oib
overlayImageDPR
oidpr
overlayImageQuality
oiq
overlayImageCropping
oic
overlayImageFocus
oifo
overlayText
ot
overlayTextFontSize
ots
overlayTextFontFamily
otf
overlayTextColor
otc
overlayTextTransparency
oa
overlayAlpha
oa
overlayTextTypography
ott
overlayBackground
obg
overlayTextEncoded
ote
overlayTextWidth
otw
overlayTextBackground
otbg
overlayTextPadding
otp
overlayTextInnerAlignment
otia
overlayRadius
or
progressive
pr
lossless
lo
trim
t
metadata
md
colorProfile
cp
defaultImage
di
dpr
dpr
effectSharpen
e-sharpen
effectUSM
e-usm
effectContrast
e-contrast
effectGray
e-grayscale
original
orig
raw
replaced 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.

Example

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

Response

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

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);

ImageKit Media API

The SDK provides a simple interface for all the following Media APIs to manage your files.

1. List and Search Files

This API can list all the uploaded files and folders in your ImageKit.io media library.
Refer to the List and Search File API for a better understanding of the Request & Response Structure.

Example

GetFileListRequest getFileListRequest = new GetFileListRequest();
ResultList resultList = ImageKit.getInstance().getFileList(getFileListRequest);

Applying Filters

Filter out the files with an object specifying the parameters.
String[] tags = new String[3];
tags[0] = "tag-1";
tags[1] = "tag-2";
tags[2] = "tag-3";
GetFileListRequest getFileListRequest = new GetFileListRequest();
getFileListRequest.setType("file");
getFileListRequest.setSort("ASC_CREATED");
getFileListRequest.setPath("/");
getFileListRequest.setSearchQuery("createdAt >= '2d' OR size < '2mb' OR format='png'");
getFileListRequest.setFileType("all");
getFileListRequest.setLimit("4");
getFileListRequest.setSkip("1");
getFileListRequest.setTags(tags);
ResultList resultList = ImageKit.getInstance().getFileList(getFileListRequest);
In addition, you can fine-tune your query by specifying various filters by generating a query string in a Lucene-like syntax and providing this generated string as the value of the searchQuery.
Map<String, String> options = new HashMap<>();
options.put("searchQuery", "(size < \"1mb\" AND width < 500) OR (tags IN [\"summer-sale\",\"banner\"])");
Detailed documentation can be found here for Advance Search Queries.

2. Get File Details

This API can get you all the details and attributes of the current version of the file.
Refer to the Get File Details API for a better understanding of the Request & Response Structure.

Example

Result result = ImageKit.getInstance().getFileDetail("file_id");

3. Get File Version Details

This API can get you all the details and attributes for the provided version of the file.versionID can be found in the following APIs as id within the versionInfo parameter:
Refer to the Get File Version Details API for a better understanding of the Request & Response Structure.

Example

ResultFileVersionDetails resultFileVersionDetails = ImageKit.getInstance().getFileVersionDetails('file_id','version_id');

4. Get File Versions

This API can get you all the versions of the file.
Refer to the Get File Versions API for a better understanding of the Request & Response Structure.

Example

ResultFileVersions resultFileVersions = ImageKit.getInstance().getFileVersions("file_id");

5. Update File Details

Update file details such as tags, customCoordinates attributes, remove existing AITags, and apply extensions using Update File Details API. This operation can only be performed on the current version of the file.
Refer to the Update File Details API for better understanding about the Request & Response Structure.

Example

List<String> tags = new ArrayList<>();
tags.add("tag-1");
tags.add("tag-2");
​
List<String> aiTags = new ArrayList<>();
aiTags.add("ai-tag-1");
aiTags.add("ai-tag-2");
FileUpdateRequest fileUpdateRequest = new FileUpdateRequest(fileId);
fileUpdateRequest.setTags(tags);