Java image upload

Overview

Cloudinary is a cloud-based service that provides an end-to-end image management solution including uploads, storage, administration, image manipulation, and delivery.

As part of its service, Cloudinary provides an API for uploading images and any other kind of files to the cloud. Images uploaded to Cloudinary are stored safely in the cloud with secure backups and revision history, utilizing Amazon's S3 service.

After you upload your images to Cloudinary, you can browse them using an API or an interactive web interface and manipulate them to reach the size and look & feel that best matches your graphic design. All uploaded images and dynamically transformed images are optimized and delivered by Cloudinary through a fast CDN with advanced caching for optimal user experience.

Cloudinary's APIs allow secure uploading images from your servers, directly from your visitors browsers or mobile applications, or fetched via remote public URLs. Comprehensive image transformations can be applied on uploaded images and you can extract images' metadata and semantic information once their upload completes.

Cloudinary's JAVA library wraps Cloudinary's upload API and simplifies the integration. JAVA methods are available for easily uploading images and raw files to the cloud. JAVA view helper methods are available for uploading images directly from a browser to Cloudinary.

This page covers common usage patterns for JAVA image upload with Cloudinary.

For a full list of JAVA image upload options, refer to All Upload Options.

Server side upload

You can upload images (or any other raw file) to Cloudinary from your Java code. Uploading is done over HTTPS using a secure protocol based on your account's API Key and API Secret parameters.

The following Java method uploads an image to the cloud:

import com.cloudinary.Cloudinary;
Cloudinary cloudinary = new Cloudinary();
cloudinary.upload(fileRef, ObjectUtils.emptyMap());

The first parameter is the file source and the second one is a map (Map<String,Object>) of additional upload parameters. The result of this method call is the deserialized server response - again, Map<String,Object>. In case of a server error or a HTTP error a RuntimeException is thrown.

For example, uploading a local image file named my_image.jpg:

File file = new File("my_image.jpg");
Map uploadResult = cloudinary.uploader().upload(file, ObjectUtils.emptyMap());

Uploading is performed synchronously. Once finished, the uploaded image is immediately available for manipulation and delivery.

An upload API call returns a JSON object with content similar to that shown in the following example:

{
 "public_id":"tquyfignx5bxcbsupr6a",
 "version":1375302801,
 "signature":"52ecf23eeb987b3b5a72fa4ade51b1c7a1426a97",
 "width":1920,
 "height":1200,
 "format":"jpg",
 "resource_type":"image",
 "created_at":"2013-07-31T20:33:21Z",
 "bytes":737633,
 "type":"upload",
 "url":
   "http://res.cloudinary.com/demo/image/upload/v1375302801/tquyfignx5bxcbsupr6a.jpg",
 "secure_url":
   "https://res.cloudinary.com/demo/image/upload/v1375302801/tquyfignx5bxcbsupr6a.jpg",
 "etag":"1adf8d2ad3954f6270d69860cb126b24"
}

The response is automatically parsed and converted into a Map.

The response includes HTTP and HTTPS URLs for accessing the uploaded image as well as additional information regarding the uploaded file: The Public ID of the image (used for building viewing URLs), resource type, width and height, image format, file size in bytes, a signature for verifying the response and more.

Public ID

Each uploaded image is assigned with a unique identifier called Public ID. It is a URL-safe string that is used to reference the uploaded resource as well as building dynamic delivery and transformation URLs.

By default, Cloudinary generates a unique, random Public ID for each uploaded image. This identifier is returned in the public_id response parameter and can be accessed via:

String publicId = (String) uploadResult.get("public_id");

In the example above, the assigned Public ID is 'tquyfignx5bxcbsupr6a'. As a result, the URL for accessing this image via our 'demo' account is the following:

http://res.cloudinary.com/demo/image/upload/tquyfignx5bxcbsupr6a.jpg

You can specify your own custom public ID instead of using the randomly generated one. The following example specifies 'sample_id' as the public ID:

Map params = ObjectUtils.asMap("public_id", "sample_id");
Map uploadResult = cloudinary.uploader().upload(new File("my_image.jpg"), params);

Using a custom public ID is useful when you want your delivery URLs to be readable and refer to the associated entity. For example, setting the public ID to a normalized user name and identifier in your local system:

Map params = ObjectUtils.asMap("public_id", "john_doe_1001");
Map uploadResult = cloudinary.uploader().upload(new File("my_image.jpg"), params);

Public IDs can be organized in folders for more structured delivery URLs. To use folders, simply separate elements in your public ID string with slashes ('/'). Here's an example:

Map params = ObjectUtils.asMap("public_id", "my_folder/my_name");
Map uploadResult = cloudinary.uploader().upload(new File("my_image.jpg"), params);

As the example below shows, your public IDs can include multiple folders:

Map params = ObjectUtils.asMap("public_id", "my_folder/my_sub_folder/my_name");
Map uploadResult = cloudinary.uploader().upload(new File("my_image.jpg"), params);

Add a parameter named use_filename and set it to true to tell Cloudinary to use the original name of the uploaded image file as the basis for its Public ID. Notice that the file name will be normalized and a set of random characters will be appended to it to ensure uniqueness. This is quite useful if you want to safely reuse the filenames of files uploaded directly by your users. If you want to override the stored file and use the filename "as is", also include a parameter named unique_filename and set it to false.

Map params = ObjectUtils.asMap("use_filename", true);
Map uploadResult = cloudinary.uploader().upload(new File("sample.jpg"), params);
// Generated public ID for example: "sample_ddzpj3"
Map params2 = ObjectUtils.asMap("use_filename", true, "unique_filename", false);
Map uploadResult2 = cloudinary.uploader().upload(new File("sample.jpg"), params2);
// Generated public ID for example: "sample"

Data uploading options

Cloudinary's Java library supports uploading files from various sources.

You can upload an image by specifying a local path of an image file. For example:

Map uploadResult = cloudinary.uploader().upload(new File("sample.jpg", ObjectUtils.emptyMap()));

If your images are already publicly available online, you can specify their remote HTTP URLs instead of uploading the actual data. In this case, Cloudinary will fetch the image from its remote URL for you. This option allows for a much faster migration of your existing images. Here's an example:

Map uploadResult = cloudinary.uploader().upload("http://www.example.com/image.jpg", ObjectUtils.emptyMap());

If you have existing images in an Amazon S3 bucket, you can point Cloudinary to their S3 URLs. Note - this option requires a quick manual setup. Contact us and we'll guide you on how to allow Cloudinary access to your relevant S3 buckets.

Map uploadResult = cloudinary.uploader().upload("s3://my-bucket/my-path/my-file.jpg", ObjectUtils.emptyMap());

Direct uploading from the browser

The upload samples mentioned above allows your server-side Java code to upload images to Cloudinary. In this flow, if you have a web form that allows your users to upload images, the image data is first sent to your server and only then uploaded to Cloudinary.

A more efficient and powerful option is to allow your users to upload images directly from the browser to Cloudinary instead of going through your servers. This method allows for faster uploading and better user experience. It also reduces load from your servers and reduces the complexity of your Java or Java EE applications.

Uploading directly from the browser is done using Cloudinary's jQuery plugin. To ensure that all uploads were authorized by your application, a secure signature must first be generated in your server-side Java code.

Direct uploading environment setup

Start by including the required JavaScript files - jQuery, Cloudinary's plugin and the jQuery-File-Upload plugin it depends on. These are available in the js folder of Cloudinary's Javascript library.

Then you can directly include the Javascript files:

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.ui.widget.js"></script>
<script type="text/javascript" src="jquery.iframe-transport.js"></script>
<script type="text/javascript" src="jquery.fileupload.js"></script>
<script type="text/javascript" src="jquery.cloudinary.js"></script>

Cloudinary's jQuery plugin requires your Cloud Name and additional configuration parameters to be available. Note: never expose your API Secret in public client side code.

To set-up Cloudinary's configuration, include the following line in your scripts section of a view:

<script>
  $.cloudinary.config("cloud_name", "your_cloud_name");
</script>

Alternatively, if you're using the cloudinary-taglib library in a Java EE JSP view context you can use the jsconfig and jsinclude tags in your view to add necessary JS code. All necessary configuration options will be taken from your instance of the Cloudinary class. For example:

<%@taglib uri="http://cloudinary.com/jsp/taglib" prefix="cl" %>
...
<cl:jsinclude/>
<cl:jsconfig/>

This is equivalent to:

<script src="javascripts/cloudinary/jquery.ui.widget.js"></script>
<script src="javascripts/cloudinary/jquery.iframe-transport.js"></script>
<script src="javascripts/cloudinary/jquery.fileupload.js"></script>
<script src="javascripts/cloudinary/jquery.cloudinary.js"></script>
<script type='text/javascript'>
  $.cloudinary.config({
    "cloud_name": "your_cloud_name",
    "api_key": "your_api_key",
    "private_cdn": false,
    "cdn_subdomain": false
  });
</script>

You can override location of JS files and also include more JS files to get more Cloudinary JS power:

<cl:jsinclude base="http://your-local-host.domain/cloudinary_js/"
              full="true"/>

This is equivalent to:

<script src="http://your-local-host.domain/cloudinary_js/jquery.ui.widget.js"></script>
<script src="http://your-local-host.domain/cloudinary_js/jquery.iframe-transport.js"></script>
<script src="http://your-local-host.domain/cloudinary_js/jquery.fileupload.js"></script>
<script src="http://your-local-host.domain/cloudinary_js/jquery.cloudinary.js"></script>
<script src="http://your-local-host.domain/cloudinary_js/canvas-to-blob.min.js"></script>
<script src="http://your-local-host.domain/cloudinary_js/jquery.fileupload-image.js"></script>
<script src="http://your-local-host.domain/cloudinary_js/jquery.fileupload-process.js"></script>
<script src="http://your-local-host.domain/cloudinary_js/jquery.fileupload-validate.js"></script>
<script src="http://your-local-host.domain/cloudinary_js/load-image.all.min.js"></script>

Direct uploading from the browser is performed using XHR (Ajax XMLHttpRequest‎) CORS (Cross Origin Resource Sharing) requests. In order to support older browsers that do not support CORS, the jQuery plugin will gracefully degrade to an iframe based solution.

This solution assumes placing cloudinary_cors.html that can be served from the root of your application, for example src/main/webapp/assets/. This file is required for iframe fallback upload and is available in the html folder of Cloudinary's Javascript library.

Direct upload file tag

Embed a file input tag in your HTML pages using the imageUploadTag method of the Uploader class available from a Cloudinary instance or as an upload tag from the taglib.

Map options = ObjectUtils.asMap("resource_type", "auto");
Map htmlOptions = ObjectUtils.asMap("alt", "sample");
String html = cloudinary.uploader().imageUploadTag("image_id", options, htmlOptions);

The following example adds a file input field to your form. Selecting or dragging a file to this input field will automatically initiate uploading from the browser to Cloudinary.

<form>
  <cl:upload resourceType="auto" fieldName="image_id" alt="sample"/>
</form>

When uploading is completed, the identifier of the uploaded image is set as the value of a hidden input field of your selected name (e.g., image_id in the example above). The identifier looks like this:

{resourceType}/{type}/v{version}/{filename}#{signature}

And may be parsed and validated like in the example below:

// 'identifier' contains the value put in the hidden input field
// which includes the signature returned from Cloudinary.
StoredFile storedFile = new StoredFile();
storedFile.setPreloadedFile(identifier);

if (!storedFile.getComputedSignature(cloudinary).equals(storedFile.getSignature())) {
  throw new Exception("Invalid upload signature");
} else {
  // Successful result
  ...
}

You can then process the identifier received by the form submission and store it for later use as if you're using a standard server side uploading.

You can also hook to the cloudinarydone event of the jQuery plugin in order retrieve and add to the form submission any other data item which you find useful and is available in the JSON response object.

$(document).ready(function() {
  $(".cloudinary-fileupload").fileupload()
    .on("cloudinarydone", function (e, data) {
      // Data contains the response from Cloudinary
      // Lets add bytes to the form to process on server side:
      var form = $("#myform");
      form.append("<input type='hidden' name='bytes' value='"+data.bytes+"'/>");
      // We can also automatically submit the form if we want.
      $.post(form.attr("action"), form.serialize());
    });
}

Having stored the image_id, you can now display a directly uploaded image in the same way you would display any other Cloudinary hosted image:

String html = cloudinary.url().format("jpg").version(version).transformation(
  new Transformation().width(120).height(80).crop("fill")).imageTag(publicId, ObjectUtils.emptyMap());

or in a view

<cl:image format="jpg" width="120" height="80" crop="fill" src="${publicId}"/>

Additional direct uploading options

When uploading directly from the browser, you can still specify all the upload options available to server-side uploading.

For example, the following call performs direct uploading that will also tag the uploaded image, limit its size to given dimensions and generate a thumbnail eagerly. Also notice the custom HTML attributes.

import java.util.Arrays;
...
Transformation incoming = new Transformation().crop("limit").width(1000).height(1000);
List<Transformation> eager = Arrays.asList(new Transformation().crop("fill").width(150).height(150));
Map options = ObjectUtils.asMap(
  "callback", customCorsLocation,
  "tags", "directly_uploaded",
  "transformation", incoming,
  "eager": eager,
  "resource_type", "auto"
);
Map htmlOptions = ObjectUtils.asMap("style", "margin-top: 30px");
String html = cloudinary.uploader().imageUploadTag("image_id", options, htmlOptions);

or

<cl:upload fieldName="image_id" callback="${customCorsLocation}" tags="directly_uploaded"
  transformation="c_limit,w_1000,h_1000" eager="c_fill,w_150,h_150" resourceType="auto"/>

Preview thumbnail, progress indication, multiple images

Cloudinary's jQuery library also enables an enhanced uploading experience - show a progress bar, display a thumbnail of the uploaded image, drag & drop support, upload multiple files and more.

Bind to Cloudinary's cloudinarydone event if you want to be notified when an upload to Cloudinary has completed. You will have access to the full details of the uploaded image and you can display a cloud-generated thumbnail of the uploaded images using Cloudinary's jQuery plugin.

The following sample code creates a 150x100 thumbnail of an uploaded image and updates an input field with the public ID of this image.

$('.cloudinary-fileupload').bind('cloudinarydone', function(e, data) {
  $('.preview').html(
    $.cloudinary.image(data.result.public_id,
      { format: data.result.format, version: data.result.version,
        crop: 'fill', width: 150, height: 100 })
  );
  $('.image_public_id').val(data.result.public_id);
  return true;
});

You can track the upload progress by binding to the following events: fileuploadsend, fileuploadprogress, fileuploaddone and fileuploadfail. You can find more details and options in the documention of jQuery-File-Upload.

The following Javascript code updates a progress bar according to the data of the fileuploadprogress event:

$('.cloudinary-fileupload').bind('fileuploadprogress', function(e, data) {
  $('.progress_bar').css('width', Math.round((data.loaded * 100.0) / data.total) + '%');
});

You can find some more examples in our Photo Album sample project.

The file input field can be configured to support simultaneous multiple file uploading. Setting the multiple HTML parameter to true allows uploading multiple files. Note - currently, only a single input field is updated with the identifier of the uploaded image. You should manually bind to the cloudinarydone event to handle results of multiple uploads. Here's an example:

Map options = ObjectUtils.emptyMap();
Map htmlOptions = ObjectUtils.asMap("multiple", true);
String html = cloudinary.uploader().imageUploadTag("image_id", options, htmlOptions);

or

<form>
  <cl:upload fieldName="image_id" resourceType="auto" multiple="true"/>
</form>

For more details about direct uploading, see this blog post: Direct image uploads from the browser to the cloud with jQuery.

Incoming transformations

By default, images uploaded to Cloudinary are stored in the cloud as-is. Once safely stored in the cloud, you can generate derived images from these originals by asking Cloudinary to apply transformations and manipulations.

Sometimes you may want to normalize and transform the original images before storing them in the cloud. You can do that by applying an incoming transformation as part of the upload request.

Any image transformation parameter can be specified as options passed to the upload call. A common incoming transformation use-case is shown in the following example, namely, limit the dimensions of user uploaded images to 1000x1000:

Map options = ObjectUtils.asMap(
  "transformation", new Transformation().width(1000).height(1000).crop("limit")
);
Map uploadResult = cloudinary.uploader().upload(new File("my_image.jpg"), options);

Another example, this time performing custom coordinates cropping and forcing format conversion to PNG:

Map options = ObjectUtils.asMap(
  "transformation",
  new Transformation().width(400).height(300).x(50).y(80).crop("limit").fetchFormat("png")
);
Map uploadResult = cloudinary.uploader().upload(new File("my_image.jpg"), options);

Named transformations as well as multiple chained transformations can be applied using the transformation key-value pair. The following example first limits the dimensions of an uploaded image and then adds a watermark as an overlay.

Transformation transformation =
  new Transformation().width(400).height(300).x(50).y(80).crop("limit").fetchFormat("png")
    .chain().overlay("my_watermark").flags("relative").width(0.5);
Map options = ObjectUtils.asMap(
  "transformation", transformation
);
Map uploadResult = cloudinary.uploader().upload(new File("my_image.jpg"), options);

Eager transformations

Cloudinary can dynamically transform images using specially crafted transformation URLs. By default, the first time a user accesses a transformation URL, the transformed images is created on-the-fly, stored persistently in the cloud and delivered through a fast CDN with advanced caching. All subsequent accesses to the same transformation would quickly deliver a cached copy of the previously generated image via the CDN.

You can tell Cloudinary to eagerly generate one or more derived images while uploading. This approach is useful when you know in advance that certain transformed versions of your uploaded images will be required. Eagerly generated derived images are available for fast access immediately when the upload call returns.

Generating transformed images eagerly is done by specifying the 'eager' upload option. This option accepts either a hash of transformation parameters or an array of transformations.

The following example eagerly generates a 150x100 face detection based thumbnail:

Transformation transformation =
  new Transformation().width(150).height(100).crop("thumb").gravity("face");
Map options = ObjectUtils.asMap(
  "eager", Arrays.asList(transformation),
  "public_id", "eager_sample"
);
Map uploadResult = cloudinary.uploader().upload(new File("my_image.jpg"), options);

Now, if you embed the same transformed image in your web view, it will already be available for fast delivery. The following tag embeds the derived image from the example above:

Transformation transformation =
  new Transformation().width(150).height(100).crop("thumb").gravity("face");
String html =
  cloudinary.url().transformation(transformation).format("jpg").imageTag("eager_sample");

or

<cl:image width="150" height="100" crop="thumb" gravity="face" format="jpg"
          src="eager_sample"/>

The following example generates two transformed versions eagerly, one fitting image into a 100x150 PNG and another applies a named transformation.

Map options = ObjectUtils.asMap(
  "eager", Arrays.asList(
    new Transformation().width(100).height(150).crop("fit").fetchFormat("png"),
    new Transformation().named("jpg_with_quality_30")
  )
);
Map uploadResult = cloudinary.uploader().upload(new File("my_image.jpg"), options);

You can apply an incoming transformation and generate derived images eagerly using the same upload call. The following example does that while also applying a chained transformation:

Transformation incoming = new Transformation().width(100).height(120)
  .crop("limit").fetchFormat("png")
  .chain().crop("crop").x(5).y(10).width(40).height(10);
Map options = ObjectUtils.asMap(
  "transformation", incoming,
  "eager", Arrays.asList(
    new Transformation().width(0.2).crop("scale"),
    new Transformation().effect("hue:30")
  )
);
Map uploadResult = cloudinary.uploader().upload(new File("my_image.jpg"), options);

For more image transformation options in Java, see Java image manipulation.

Semantic data extraction

When you upload a resource to Cloudinary, the API call will report information about the uploaded asset: width, height, number of bytes and image format. Cloudinary supports extracting additional information from the uploaded image: Exif and IPTC camera metadata, color histogram, predominant colors and coordinates of automatically detected faces. You can ask Cloudinary for this semantic data either during the upload API call for newly uploaded images, or using our Admin API for previously uploaded images.

See Cloudinary's Admin API documentation for more details: Details of a single resource.

You can tell Cloudinary to include relevant metadata in its upload API response by setting the faces, exif, colors and metadata boolean parameters to true while calling the upload API.

The following example uploads an image via a remote URL, and requests the coordinates of all detected faces in the image:

Map options = ObjectUtils.asMap("faces", true);
Map uploadResult = cloudinary.uploader().upload(
  "http://res.cloudinary.com/demo/image/upload/couple.jpg", options);

Below you can see the faces coordinates that were included in the upload response:

 {
  "public_id":"egwcvxk8idvump0jauv7",
  ...
  "faces":
  [
      [98,74,61,83],
      [139,130,52,71]
  ]
 }

Another example, this time requesting details about the main colors of the uploaded image. Each pair in the returned colors array includes the color name or its RGB representation and the percentage of the image comprising it.

Map options = ObjectUtils.asMap("colors", true);
Map uploadResult = cloudinary.uploader().upload(
  "http://res.cloudinary.com/demo/image/upload/couple.jpg", options);
{
  "public_id":"ekr5yblwesovtuf2lwgv",
  ...
  "colors":
  [
      ["#152E02",7.9],
      ["#2E4F06",6.3],
      ["#3A6604",5.6],
      ...
  ],
  "predominant":
  {
      "google":
      [
          ["yellow",40.1],
          ["green",24.6],
          ["brown",13.4],
          ["black",12.5],
          ["teal",9.4]
      ]
  }
}

You can also request Exif, IPTC, colors and faces data in a single upload call:

Map options = ObjectUtils.asMap(
  "faces", true,
  "colors", true,
  "exif", true,
  "metadata", true
);
Map uploadResult = cloudinary.uploader().upload(
  "http://res.cloudinary.com/demo/image/upload/couple.jpg", options);

See the following blog post for more details: API for extracting semantic image data - colors, faces, Exif data and more

Raw file uploading

Cloudinary's main strength is in managing images. However, you can still use Cloudinary to manage any other file format using the same simple APIs. You'll get your files stored in a highly available storage with automatic backups and revision control, and when accessed, have them delivered through a fast CDN.

You can upload a raw file to Cloudinary in much the same way.

Map options = ObjectUtils.asMap(
  "public_id", "sample_spreadsheet",
  "resource_type", "raw"
);
Map uploadResult =
  cloudinary.uploader().upload(new File("sample_spreadsheet.xls"), options);

Non-image raw files are stored in the cloud as-is. Note that while public IDs of image files do not include the file's extension, public IDs of raw files do include the original file's extension.

Here's a sample response of a raw upload call, which is slightly different from an image upload response:

 {
  "public_id":"sample_spreadsheet.xls",
  "version":1375302583,
  "signature":"8bf940a92ff0bcbde2eeab6455f7b9c0c3158baa",
  "resource_type":"raw",
  "created_at":"2013-07-31T20:29:43Z",
  "bytes":44912,
  "type":"upload",
  "url":
    "http://res.cloudinary.com/demo/raw/upload/v1375302583/sample_spreadsheet.xls",
  "secure_url":
    "https://res.cloudinary.com/demo/raw/upload/v1375302583/sample_spreadsheet.xls"
 }

Sometimes you don't know whether your users would upload image files or raw files. Automatic support of either is enabled by default, however you can explicitly specify the type and exclude uploaded files which do not belong to that type.

Map options = ObjectUtils.asMap("resource_type", "raw");
Map uploadResult =
  cloudinary.uploader().upload(new File("sample_spreadsheet.xls"), options);

Delivery URLs of raw files are built quite similarly to those of images. Just make sure to set resourceType to raw. Here's an example:

cloudinary.url().resourceType("raw").generate("sample_spreadsheet.xls");

or

<cl:url resourceType="raw" src="sample_spreadsheet.xls"/>

Update and delete images

Image uploaded to Cloudinary are stored persistently in the cloud. You can programmatically delete an uploaded image using following method:

public Map destroy(String publicId, Map options) throws IOException

For example, the following code would delete the uploaded image assigned with the public ID 'zombie':

cloudinary.uploader().destroy("zombie", ObjectUtils.emptyMap());

See our Admin API documentation for more options of listing and deleting images and files.

When you delete an uploaded image, all its derived images are deleted as well. However, images and derived images that were already delivered to your users might have cached copies at the CDN layer. If you now upload a new image with the same public ID, the cached copy might be returned instead. To avoid that, use different randomly generated public IDs for each upload or alternatively, add the version component to the delivery URLs. If none of these solutions work, you might want to force cache invalidation for each deleted image.

Forcing cache invalidation is done by setting the invalidate parameter to true either when deleting an image or uploading a new one. Note that it usually takes up to one hour for the CDN invalidation to take effect. Here's are two examples:

cloudinary.uploader().destroy("zombie", ObjectUtils.asMap("invalidate", true));
Map uploadParams = ObjectUtils.asMap(
  "public_id", "zombie",
  "invalidate", true
);
Map uploadResult = cloudinary.uploader().upload(new File("new_zombie.jpg"), uploadParams);

Refresh images

Cloudinary supports forcing the refresh of Facebook & Twitter profile pictures, using the explicit API method. The response of this method includes the image's version. Use this version to bypass previously cached CDN copies. For Facebook pictures, use the application-specific numeric ID only.

Map expResult =
  cloudinary.uploader().explicit("4", ObjectUtils.asMap("type", "facebook"));

You can also use the explicit method to generate transformed versions of an uploaded image. This is useful when Strict Transformations are allowed for your account and you wish to create custom derived images for already uploaded images.

Map options = ObjectUtils.asMap(
  "type", "upload",
  "eager", Arrays.asList(new Transformation().width(150).height(230).crop("fill")));
Map expResult = cloudinary.uploader().explicit("sample_id", options);

Rename images

You can rename images uploaded to Cloudinary. Renaming means changing the public ID of already uploaded images. The following method allows renaming a public ID:

public Map rename(String fromPublicId, String toPublicId, Map options) throws IOException;

For example, renaming an image with the public ID 'old_name' to 'new_name':

cloudinary.uploader().rename("old_name", "new_name", ObjectUtils.emptyMap());

By default, Cloudinary prevents renaming to an already taken public ID. You can set the overwrite parameter to true to delete the image that has the target public ID and replace it with the image being renamed:

cloudinary.uploader().rename("old_name", "new_name", ObjectUtils.asMap("overwrite", true));

Manage tags

Cloudinary supports assigning one or more tags to uploaded images. Tags allow you to better organize your media library.

You can use our Admin API and media library web interface for searching, listing and deleting images by tags. In addition, you can merge multiple images that share the same tag into a sprite, a multi-page PDF or an animated GIF.

See our Admin API documentation for more details regarding managing images by tags.

The following example assigned two tags while uploading.

Map uploadParams = ObjectUtils.asMap(
  "public_id", "sample_id",
  "tags", "special, for_homepage"
);
Map uploadResult = cloudinary.uploader().upload(new File("my_image.jpg"), uploadParams);

You can modify the assigned tags of an already uploaded image. The following example assigns a tag to a list of images:

Map addTagResult = cloudinary.uploader().addTag(
  "another_tag",
  {"sample_id", "de9wjix4hhnqpxixq6cw"},
  ObjectUtils.emptyMap());

The following example clears the given tag from a list of images:

Map removeTagResult = cloudinary.uploader().removeTag(
  "another_tag",
  {"sample_id", "de9wjix4hhnqpxixq6cw"},
  ObjectUtils.emptyMap());

This example clears all tags from a given list of images and assigns a different tag:

Map replaceTagResult = cloudinary.uploader().replaceTag(
  "another_tag",
  {"sample_id", "de9wjix4hhnqpxixq6cw"},
  ObjectUtils.emptyMap());

Text creation

Cloudinary allows generating dynamic text overlays with your custom text. First you need to create a text style - font family, size, color, etc. The name of the text style is its public ID and it behaves like an image of the text type.

The following command creates a text style named dark_name of a certain font, color and style:

Map textParams = ObjectUtils.asMap(
  "public_id", "dark_name",
  "font_family", "Arial",
  "font_size", 12,
  "font_color", "black",
  "opacity", "90"
);
Map textResult = cloudinary.uploader.text("some text", textParams);

The following image tag adds a text overlay using the created dark_name text style.

cloudinary.url().transformation(
  new Transformation()
    .x(5)
    .y(5)
    .gravity("south_east")
    .overlay("text:dark_name:Hello+World"))
    .imageTag("sample.jpg", ObjectUtils.emptyMap());

or

<cl:image x="5" y="5" gravity="south_east" overlay="text:dark_name:Hello+World"
          src="sample.jpg"/>

For more text style options, see Text layers creation.

More information about text overlays is available in our adding text overlays in Java documentation.

Notifications and async transformations

By default, Cloudinary's upload API works synchronously. Uploaded images processed and eager transformations are generated synchronously during the upload API call.

You can tell Cloudinary to generate eager transformations in the background and send you an HTTP notification callback when the transformations are ready. You can do that by setting the eager_async property to true and optionally setting eager_notification_url to the URL Cloudinary should send the callback to. Here's an example:

Map uploadParams = ObjectUtils.asMap(
  "eager_async", true,
  "eager_notification_url", "http://mysite/my_notification_endpoint",
  "eager", Arrays.asList(
    new Transformation().width(150).height(100).crop("thumb").gravity("face")
  )
);
Map uploadResult = cloudinary.uploader().upload(new File("my_image.jpg"), uploadParams);

Cloudinary also supports webhooks. With webhooks enabled, you can get a notification to your server when an upload is completed. This is useful when you use direct image uploading from the browser and you want to be informed whenever an image is uploaded by your users. Setting the notification_url parameter tells Cloudinary to perform an asynchronous HTTP GET request to your server when the upload is complete. For example:

Map uploadParams = ObjectUtils.asMap(
  "notification_url", "http://mysite/my_notification_endpoint"
);
Map uploadResult = cloudinary.uploader().upload(new File("my_image.jpg"), uploadParams);

See the following blog post for more details: Webhooks, upload notifications and background image processing.

All upload options

public Map upload(Object file, Map options) throws IOException;

Cloudinary's upload API call accepts the following options:

  • file - The resource to upload. Can be one of the following:
    • A local path (e.g., '/home/my_image.jpg').
    • An HTTP URL of a resource available on the Internet (e.g., 'http://www.example.com/image.jpg').
    • A URL of a file in a private S3 bucket white-listed for your account (e.g., 's3://my-bucket/my-path/my-file.jpg')
  • public_id (Optional) - Public ID to assign to the uploaded image. Random ID is generated otherwise and returned as a result for this call. The public ID may contain a full path including folders separated by '/'.
  • tags (Optional) - A tag name or an array with a list of tag names to assign to the uploaded image.
  • context - A map of key-value pairs of general textual context metadata to attach to an uploaded resource. The context values of uploaded files are available for fetching using the Admin API. For example: { "alt" => "My image", "caption" => "Profile Photo" }.
  • format (Optional) - A format to convert the uploaded image to before saving in the cloud. For example: 'jpg'.
  • allowed_formats - A format name of an array of file formats that are allowed for uploading. The default is any supported image kind and any type of raw file. Files of other types will be rejected. The formats can be image types or raw file extensions. For example: ['jpg', 'gif' , 'doc'].
  • Transformation parameters (Optional) - Any combination of transformation-related parameters for transforming the uploaded image before storing in the cloud. For example: 'width', 'height', 'crop', 'gravity', 'quality', 'transformation'.
  • eager (Optional) - A list of transformations to generate for the uploaded image during the upload process, instead of lazily creating these on-the-fly on access.
  • eager_async (Optional, Boolean) - Whether to generate the eager transformations asynchronously in the background after the upload request is completed rather than online as part of the upload call. Default: false.
  • resource_type (Optional) - Valid values: 'image', 'raw' and 'auto'. Default: 'image'.
  • type (Optional) - Allows uploading images as 'private' or 'authenticated'. Valid values: 'upload', 'private' and 'authenticated'. Default: 'upload'.
  • proxy (Optional) - Tells Cloudinary to upload images from remote URLs through the given proxy. Format: 'http://hostname:port'.
  • headers (Optional) - An HTTP header or an array of headers for returning as response HTTP headers when delivering the uploaded image to your users. Supported headers: 'Link', 'X-Robots-Tag'. For example 'X-Robots-Tag: noindex'.
  • callback (Optional) - An HTTP URL to redirect to instead of returning the upload response. Signed upload result parameters are added to the callback URL. Ignored if it is an XHR upload request (Ajax XMLHttpRequest).
  • notification_url (Optional) - An HTTP URL to send notification to (a webhook) when the upload is completed.
  • eager_notification_url (Optional) - An HTTP URL to send notification to (a webhook) when the generation of eager transformations is completed.
  • backup (Optional, Boolean) - Tell Cloudinary whether to back up the uploaded image. Overrides the default backup settings of your account.
  • return_delete_token (Boolean) - Whether to return a deletion token in the upload response. The token can be used to delete the uploaded image within 10 minutes using an unauthenticated API request.
  • faces (Optional, Boolean) - Whether to retrieve a list of coordinates of automatically detected faces in the uploaded photo. Default: false.
  • exif (Optional, Boolean) - Whether to retrieve the Exif metadata of the uploaded photo. Default: false.
  • colors (Optional, Boolean) - Whether to retrieve predominant colors & color histogram of the uploaded image. Default: false.
  • image_metadata (Optional, Boolean) - Whether to retrieve IPTC and detailed Exif metadata of the uploaded photo. Default: false.
  • phash (Optional, Boolean) - Whether to return the perceptual hash (pHash) on the uploaded image. The pHash acts as a fingerprint that allows checking image similarity. Default: false.
  • invalidate (Optional, Boolean) - Whether to invalidate CDN cache copies of a previously uploaded image that shares the same public ID. Default: false.
  • use_filename (Optional, Boolean) - Whether to use the original file name of the uploaded image if available for the public ID. The file name is normalized and random characters are appended to ensure uniqueness. Default: false.
  • unique_filename (Optional, Boolean) - Only relevant if use_filename is true. When set to false, should not add random characters at the end of the filename that guarantee its uniqueness. Default: true.
  • folder - An optional folder name where the uploaded resource will be stored. The public ID contains the full path of the uploaded resource, including the folder name.
  • overwrite (Optional, Boolean) - Whether to overwrite existing resources with the same public ID. When set to false, return immediately if a resource with the same public ID was found. Default: true.
  • discard_original_filename (Optional, Boolean) - Whether to discard the name of the original uploaded file. Relevant when delivering images as attachments (setting the 'flags' transformation parameter to 'attachment'). Default: false.
  • face_coordinates (Optional, Array) - List of coordinates of faces contained in an uploaded image. The given coordinates are used for cropping uploaded images using the face or faces gravity mode. The specified coordinates override the automatically detected faces. Each face is specified by the X & Y coordinates of the top left corner and the width & height of the face. For example: [[10,20,150,130], [213,345,82,61]].
  • custom_coordinates (Optional, Array) - Coordinates of an interesting region contained in an uploaded image. The given coordinates are used for cropping uploaded images using the custom gravity mode. The region is specified by the X & Y coordinates of the top left corner and the width & height of the region. For example: [85,120,220,310].
  • raw_convert - Set to 'aspose' to automatically convert Office documents to PDF files and other image formats using the Aspose Document Conversion add-on.
  • categorization - Set to 'imagga_tagging' to automatically detect scene categories of photos using the Imagga Auto Tagging add-on.
  • auto_tagging (0.0 to 1.0 Decimal number) - Whether to assign tags to an image according to detected scene categories with confidence score higher than the given value.
  • detection - Set to 'adv_face' to automatically extract advanced face attributes of photos using the Advanced Facial Attributes Detection add-on.
  • background_removal - Set to 'remove_the_background' to automatically clear the background of an uploaded photo using the Remove-The-Background Editing add-on.
  • moderation - Set to 'manual' to add the uploaded image to a queue of pending moderation images. Set to 'webpurify' to automatically moderate the uploaded image using the WebPurify Image Moderation add-on.
  • upload_preset - Name of an upload preset that you defined for your Cloudinary account. An upload preset consists of upload parameters centrally managed using the Admin API or from the settings page of the management console. An upload preset may be marked as 'unsigned', which allows unsigned uploading directly from the browser and restrict the directly allowed parameters to: public_id, folder, tags, context, face_coordinates and custom_coordinates.