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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Merge HTML Documents in Java
  • Designing a Java Connector for Software Integrations
  • Jakarta NoSQL 1.0: A Way To Bring Java and NoSQL Together
  • How to Get Word Document Form Values Using Java

Trending

  • The Role of AI in Identity and Access Management for Organizations
  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  • How to Convert XLS to XLSX in Java
  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  1. DZone
  2. Coding
  3. Java
  4. How To Place Text and Shapes on an Image in Java

How To Place Text and Shapes on an Image in Java

This article provides two API solutions that can be used to programmatically add text and shapes to an image with ready-to-run Java code examples.

By 
Brian O'Neill user avatar
Brian O'Neill
DZone Core CORE ·
Apr. 24, 23 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
4.9K Views

Join the DZone community and get the full member experience.

Join For Free

Coding new visual elements into an image file begins with a basic understanding of how image files are normally displayed. When an image file is loaded for display on any of our devices, software from that device must first decode the file and store the result of that decoding in a temporary block of memory called a buffer. Buffers become responsible for communicating the color information stored by each individual pixel within an image (in each instance, the file is opened), and from there, that color information can be rendered by our device’s lighting (usually LCD or LED) display.

When we want to layer new text or shapes which display on top of an image, we need to access the file in memory and create our own temporary image buffer to work within. This new buffer will give us control over an entirely new layer of pixels in our image, allowing us to temporarily influence — and eventually save changes to — our image’s final display. How our image subsequently implements our new buffer depends on the original file format. If we begin with a PNG file, for example, we’ll leverage built-in transparency features to layer new content on top of the original file. If we begin with a JPG file, which doesn’t offer transparency features, we’ll end up with a single, blended image layer that effectively mixed the new and original content together. In either case, the result of the operation will retain the encoding of the original file, allowing us to easily write our resulting (slightly larger sized) file encoding to a new file entirely.

Creating a new buffer requires us to write code that accesses the image file’s encoding in memory.   Rather than writing a bunch of new code from scratch — a process that takes time we don’t always have — we can more efficiently (i.e., with minimal code) upload the image file to a specialized image processing library. Doing so allows us to influence the display of a new pixel matrix — such as the color, font, or many other styling elements — by structuring requests to specific components of the library.  

In the temporary buffer created through our image processing library, we can make requests referencing specific points on our new pixel matrix (which matches the exact pixel height and width dimensions of our original image) in much the same way we would plot points on any regular X/Y axis. We can use coordinates to easily decide where our new content should display on top of the original image and to determine what size it should be. If, for example, we started with a 1000 x 1000-pixel image, new content placed at 250 x 250 pixels in our buffer would show up towards the bottom left corner of our image. If the content we created was a simple, rectangular box, we could easily determine the relative thickness of the box’s four lines in terms of pixels as well.

Demonstration

In the remainder of this article, I’ll demonstrate two APIs that can be used to programmatically write text and draw rectangles onto image files in memory. To help you structure each API call, I’ve provided ready-to-run Java code examples, which you can easily copy and paste from. These solutions leverage the image buffering process outlined above, allowing you to communicate seamlessly with image file encoding through simple, intuitive request parameters. These solutions include the following:

  • Draw Text onto an Image
  • Draw a Rectangle onto an Image

Before we dive into each API and highlight their respective request parameters, let’s first walk through the client SDK installation step.

We can begin by adding a reference to the repository in our Maven POM file (this uses Jitpack to dynamically compile the library):

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


Following that, we can add a reference to the dependency:

XML
 
<dependencies>
<dependency>
    <groupId>com.github.Cloudmersive</groupId>
    <artifactId>Cloudmersive.APIClient.Java</artifactId>
    <version>v4.25</version>
</dependency>
</dependencies>


Draw Text Onto an Image

Creating a text layer on top of our image involves a few basic moving parts. First and foremost, we need to specify the text content we want to include, the font we want that text to be in, the size of that text, and, lastly, its color. Following that, we need to determine where the text should appear on our image — a location that can be expressed in x/y pixel coordinates relative to the exact pixel dimensions of our original image — and the height and width of the invisible “box” containing the text. With all this in mind, we can structure our “Draw Text onto an Image” request like so:

JSON
 
{
  "BaseImageBytes": "string",
  "BaseImageUrl": "string",
  "TextToDraw": [
    {
      "Text": "string",
      "FontFamilyName": "string",
      "FontSize": 0,
      "Color": "string",
      "X": 0,
      "Y": 0,
      "Width": 0,
      "Height": 0
    }
  ]
}


As we can see, request information regarding the base image bytes (or base image URL, which is recommended for particularly large files) comes first, followed by the TextToDraw object, which determines the text output.  

We can make our request using the following code:

Java
 
// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.EditApi;

ApiClient defaultClient = Configuration.getDefaultApiClient();

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

EditApi apiInstance = new EditApi();
DrawTextRequest request = new DrawTextRequest(); // DrawTextRequest | Draw text parameters
try {
    byte[] result = apiInstance.editDrawText(request);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling EditApi#editDrawText");
    e.printStackTrace();
}


Draw a Rectangle Onto an Image

Creating a rectangle on top of an image involves marginally less customization when structuring our request. This API allows us to determine the color and width of our rectangle’s borders, and it additionally allows us to determine what color (if any) we want to fill the shape with.  Beyond that, the way we place our rectangle within our image is identical to the way we placed our text box, involving X/Y pixel coordinates and specific height and width measurements.  Our request can be structured like so:

JSON
 
{
  "BaseImageBytes": "string",
  "BaseImageUrl": "string",
  "RectanglesToDraw": [
    {
      "BorderColor": "string",
      "BorderWidth": 0,
      "FillColor": "string",
      "X": 0,
      "Y": 0,
      "Width": 0,
      "Height": 0
    }
  ]
}


Once we’ve configured our request to our liking, we can expect to see a fully customized rectangular shape on our image in the location we specified.  If we perform this operation prior to our text operation, we can easily layer text on top of our rectangle as well.

We can structure our API request using the following code:

Java
 
// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.EditApi;

ApiClient defaultClient = Configuration.getDefaultApiClient();

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

EditApi apiInstance = new EditApi();
DrawRectangleRequest request = new DrawRectangleRequest(); // DrawRectangleRequest | Draw rectangle parameters
try {
    byte[] result = apiInstance.editDrawRectangle(request);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling EditApi#editDrawRectangle");
    e.printStackTrace();
}


Both operations will return encoding strings which we can write to new files with ease.  

API Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • How to Merge HTML Documents in Java
  • Designing a Java Connector for Software Integrations
  • Jakarta NoSQL 1.0: A Way To Bring Java and NoSQL Together
  • How to Get Word Document Form Values Using Java

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!