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.
Join the DZone community and get the full member experience.
Join For FreeCoding 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):
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Following that, we can add a reference to the dependency:
<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:
{
"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:
// 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:
{
"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:
// 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.
Opinions expressed by DZone contributors are their own.
Comments