Back to Java
2026-04-266 min read

Border Around Image (Java)

Learn Border Around Image (Java) step by step with clear examples and exercises.

Title: Border Around Image (Java)

Why This Matters

In this Java lesson, we will learn how to add a border around an image. This skill is essential for various applications like web development, mobile app development, and desktop application development where you need to manipulate images dynamically. Adding a border can help in creating visually appealing interfaces and improving user experience.

By the end of this lesson, you will understand how to use the BufferedImage class from the java.awt.image package to add borders around images with different colors, widths, and even custom patterns.

Prerequisites

To follow this lesson, you should have a basic understanding of Java programming concepts such as:

  • Variables and data types
  • Control structures (if-else, for, while)
  • Arrays
  • File I/O operations
  • Exception handling
  • Classes and objects
  • Methods
  • Interfaces and the Graphics2D interface

Core Concept

To add a border around an image in Java, we will use the BufferedImage class from the java.awt.image package. This class represents a mutable image data buffer and provides methods for creating, accessing, and modifying the pixels of the image.

The basic steps to add a border are:

  1. Load the original image using ImageIO.read(File).
  2. Create a new BufferedImage with the desired dimensions (including the border).
  3. Copy the original image into the new one, leaving space for the border.
  4. Fill the border area with the desired color or pattern.
  5. Save the modified image using ImageIO.write(BufferedImage, format, File).

Creating a Border

To fill the border area with a specific color, you can use the Graphics2D object's fillRect() method. For custom patterns, you can create an Image object and use it to fill the border area using the drawImage() method.

Centering the Original Image

When drawing the original image, make sure to calculate the x and y coordinates correctly so that it is centered in the new image. The center of the original image can be found by dividing its width and height by 2.

Worked Example

Let's add a red border (10 pixels wide) around an image named input_image.png and save it as output_image.png.

import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;

public class AddBorderExample {
public static void main(String[] args) throws IOException {
BufferedImage originalImage = ImageIO.read(new File("input_image.png"));
int borderWidth = 10;
int width = originalImage.getWidth() + (borderWidth * 2);
int height = originalImage.getHeight() + (borderWidth * 2);
BufferedImage borderImage = new BufferedImage(width, height, originalImage.getType());

Graphics2D g = borderImage.createGraphics();
g.setColor(Color.RED);
g.fillRect(0, 0, width, height); // Fill the background with red

int x = (borderWidth / 2) + originalImage.getWidth() / 2;
int y = (borderWidth / 2) + originalImage.getHeight() / 2;
g.drawImage(originalImage, x, y, null); // Draw the original image centered

g.dispose();

File outputFile = new File("output_image.png");
ImageIO.write(borderImage, "png", outputFile);
}
}

In this example, we load an image named input_image.png, create a new BufferedImage with a border width of 10 pixels, and fill the background with red. We then draw the original image centered in the new image. Finally, we save the modified image as output_image.png.

Custom Pattern Border

To add a custom pattern border, you can create an Image object representing the pattern and use it to fill the border area. Here's an example:

import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;

public class CustomPatternBorderExample {
public static void main(String[] args) throws IOException {
BufferedImage pattern = ImageIO.read(new File("pattern.png"));
int borderWidth = 10;
int width = originalImage.getWidth() + (borderWidth * 2);
int height = originalImage.getHeight() + (borderWidth * 2);
BufferedImage borderImage = new BufferedImage(width, height, originalImage.getType());

Graphics2D g = borderImage.createGraphics();
g.drawImage(pattern, 0, 0, borderWidth, borderWidth, null); // Draw the pattern on the top-left corner
g.drawImage(pattern, width - borderWidth, 0, borderWidth, borderWidth, null); // Draw the pattern on the bottom-right corner
g.drawImage(originalImage, (borderWidth / 2), (borderWidth / 2), null); // Draw the original image centered

g.dispose();

File outputFile = new File("output_image.png");
ImageIO.write(borderImage, "png", outputFile);
}
}

In this example, we create an Image object representing a pattern named pattern.png. We then draw the pattern on both the top-left and bottom-right corners of the new image and center the original image inside it.

Common Mistakes

  1. Forgetting to set the background color: If you don't fill the background with a color, the original image might be visible through the border, causing unexpected results.
  2. Incorrectly calculating the new image dimensions: Make sure to add twice the border width to both the width and height of the original image when creating the new BufferedImage.
  3. Not centering the original image: When drawing the original image, make sure to calculate the x and y coordinates correctly so that it is centered in the new image.
  4. Not disposing the Graphics2D object: After using the Graphics2D object, don't forget to call g.dispose(). This helps in freeing up system resources.
  5. Using an unsupported image format for the pattern: Make sure that the pattern image format is supported by the ImageIO class (e.g., PNG, JPEG, GIF).
  6. Not handling exceptions properly: Always wrap your code in a try-catch block to handle potential exceptions when reading and writing files.

Practice Questions

  1. Write a Java program that adds a blue border (5 pixels wide) around an image named input_image.jpg and saves it as output_image.jpg.
  2. Modify the example provided to add a green border (7 pixels wide) around an image named input_image.png and save it as output_image.png.
  3. Write a Java program that adds a border of alternating colors (red, blue, red, ...) around an image named input_image.jpg and saves it as output_image.jpg. The border width should be 5 pixels.
  4. Modify the custom pattern border example to use a different pattern image named custom_pattern.png.

FAQ

  1. Why do I need to dispose the Graphics2D object? Disposing the Graphics2D object helps in freeing up system resources, which can improve performance and prevent memory leaks.
  2. Can I add a border around an image using a different color for each side (top, bottom, left, right)? Yes, you can achieve this by filling rectangles with different colors on the respective sides before drawing the original image.
  3. How can I create a pattern for the border? To create a pattern for the border, you can use any image editing software to create an image with the desired dimensions and save it as a supported format (e.g., PNG). Then, load this pattern image in your Java program and draw it on the respective sides of the new image.
  4. What if I want to add text inside the border? To add text inside the border, you can create a Font object and use the drawString() method of the Graphics2D object to draw the text at the desired position. Make sure to consider the text's size and position when calculating the dimensions of the new image.
  5. How can I ensure that the border is always visible around the image? To ensure that the border is always visible, you can set the background color of the new image to a contrasting color or make the border width larger than the minimum required to cover any potential overlapping pixels with the original image.
Border Around Image (Java) | Java | XQA Learn