DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • A Spring Boot App With Half the Startup Time
  • Implementing the Planning Pattern With Java Enterprise and LangChain4j
  • Getting Started With Agentic Workflows in Java and Quarkus
  • Building AI-Powered Java Applications With Jakarta EE and LangChain4j

Trending

  • I Reverse-Engineered 50 API Breaches. The Same Five Mistakes Keep Appearing.
  • 11 Agentic Testing Tools to Know in 2026
  • Quality Assurance in AI-Driven Business Evolution
  • Document Generation API: How to Automate Personalized Document Creation at Scale
  1. DZone
  2. Coding
  3. Java
  4. How to Generate and Compare Perceptual Image Hashes in Java

How to Generate and Compare Perceptual Image Hashes in Java

Learn how to generate a hash value for an image and compare two perceptual image hashes using an API in Java.

By 
Brian O'Neill user avatar
Brian O'Neill
DZone Core CORE ·
Apr. 30, 21 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
8.1K Views

Join the DZone community and get the full member experience.

Join For Free

Perceptual image hashing is a relatively new process used primarily in the multimedia industry for content identification and authentication. The process itself uses an algorithm to extract specific features from an image and calculate a hash value based on that information. The hash value that is generated acts as a kind of ‘fingerprint’ for the image; it is a distinct identifier that is unique to its parent image. 

As you may have guessed by the fingerprint comparison, perceptual image hashing is particularly useful for digital forensics, but it has become an important player in prohibiting online copyright infringement as well. By comparing the hash value of an original/authentic image with the hash value of a similar image, you can identify and match various images and calculate the Hamming Distance between them. For reference, Hamming Distance measures the minimum number of substitutions it takes to change one image to the other, so hash values that are closer together are more similar. 

To protect your multimedia from copyright infringement, perceptual image hashing may be the ideal technique for the job; it has proven to be effective at not only providing a unique hash value for an image, but also at resisting and detecting malicious manipulation attempts. In this brief tutorial, we will demonstrate how to use APIs in Java to generate a hash value for an image, as well as compare the similarity of two perceptual image hashes in terms of Hamming Distance. 

We will begin installing the Maven SDK by adding a reference to the repository in pom.xml:

Java
 




x


 
1
<repositories>
2
    <repository>
3
        <id>jitpack.io</id>
4
        <url>https://jitpack.io</url>
5
    </repository>
6
</repositories>


Then, we can add a reference to the dependency:

Java
 




xxxxxxxxxx
1


 
1
<dependencies>
2
<dependency>
3
    <groupId>com.github.Cloudmersive</groupId>
4
    <artifactId>Cloudmersive.APIClient.Java</artifactId>
5
    <version>v3.90</version>
6
</dependency>
7
</dependencies>



Once the installation is complete, we are ready to start using our APIs. For our first function, we will focus on generating a perceptual image hash for a specific image. To ensure the process runs smoothly, we will need to input the following parameters:

  • Image File: the image file to perform the operation on; common file formats such as PNG, JPEG, etc. are supported
  • API Key: your personal API key; if you need to obtain an API key, you can do so by registering for a free account on the Cloudmersive website. This will provide access to 800 calls/month across the entire API library.
  • Recognition Mode (optional): specify the recognition mode; possible values are Normal, Basic, and advanced. Default is Normal.

Once we have our parameters set, we are ready to call the function:

Java
 




xxxxxxxxxx
1
26


 
1
// Import classes:
2
//import com.cloudmersive.client.invoker.ApiClient;
3
//import com.cloudmersive.client.invoker.ApiException;
4
//import com.cloudmersive.client.invoker.Configuration;
5
//import com.cloudmersive.client.invoker.auth.*;
6
//import com.cloudmersive.client.RecognizeApi;
7

          
8
ApiClient defaultClient = Configuration.getDefaultApiClient();
9

          
10
// Configure API key authorization: Apikey
11
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
12
Apikey.setApiKey("YOUR API KEY");
13
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
14
//Apikey.setApiKeyPrefix("Token");
15

          
16
RecognizeApi apiInstance = new RecognizeApi();
17
File imageFile = new File("/path/to/inputfile"); // File | Image file to perform the operation on.  Common file formats such as PNG, JPEG are supported.
18
String recognitionMode = "recognitionMode_example"; // String | Optional, specify the recognition mode; possible values are Normal, Basic and Advanced.  Default is Normal.
19
try {
20
    ImageSimilarityHashResponse result = apiInstance.recognizeSimilarityHash(imageFile, recognitionMode);
21
    System.out.println(result);
22
} catch (ApiException e) {
23
    System.err.println("Exception when calling RecognizeApi#recognizeSimilarityHash");
24
    e.printStackTrace();
25
}



This will return a hash value for your input image, which we could potentially use as an input for our next function. Our second API will allow us to compare the similarity between two hash values by calculating the Hamming distance between them; as I mentioned earlier, hash values that are closer together according to the Hamming distance are more alike. Now, we can call the function with the following code:

Java
 




x


 
1
// Import classes:
2
//import com.cloudmersive.client.invoker.ApiClient;
3
//import com.cloudmersive.client.invoker.ApiException;
4
//import com.cloudmersive.client.invoker.Configuration;
5
//import com.cloudmersive.client.invoker.auth.*;
6
//import com.cloudmersive.client.RecognizeApi;
7

          
8
ApiClient defaultClient = Configuration.getDefaultApiClient();
9

          
10
// Configure API key authorization: Apikey
11
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
12
Apikey.setApiKey("YOUR API KEY");
13
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
14
//Apikey.setApiKeyPrefix("Token");
15

          
16
RecognizeApi apiInstance = new RecognizeApi();
17
ImageSimilarityHashDistanceRequest request = new ImageSimilarityHashDistanceRequest(); // ImageSimilarityHashDistanceRequest | 
18
try {
19
    ImageSimilarityHashDistanceResponse result = apiInstance.recognizeSimilarityHashDistance(request);
20
    System.out.println(result);
21
} catch (ApiException e) {
22
    System.err.println("Exception when calling RecognizeApi#recognizeSimilarityHashDistance");
23
    e.printStackTrace();
24
}



For the second function you will only need to input your API key and your image similarity request, which should look like this:

Java
 




xxxxxxxxxx
1


 
1
{
2
  "ImageHash1": "string",
3
  "ImageHash2": "string"
4
}



And that’s it! Your result from the image comparison API will be a similarity score that you can use to determine how alike or different the images are. Between these two APIs, you can automate what would normally be a time-consuming and manual process of sifting through images in a database.

Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • A Spring Boot App With Half the Startup Time
  • Implementing the Planning Pattern With Java Enterprise and LangChain4j
  • Getting Started With Agentic Workflows in Java and Quarkus
  • Building AI-Powered Java Applications With Jakarta EE and LangChain4j

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook