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
- Upload images
- Rendering images
- Applying common image manipulations
- Secure signed URL generation
- Server-side file uploading
- ImageKit Media API
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.
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 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:
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
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.
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:
- Chained Transformations
- Image Enhancement & Color Manipulation
- Resizing images
- Quality manipulation
- Adding overlays
- Signed URL
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.
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:
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:
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:
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:
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:
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:
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:
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
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:
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
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:
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
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
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 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 |
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. Check all the supported parameters and details.
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);
Media management
The SDK provides easy to use methods for all APIs. Learn more from the SDK documentation.