user1993381 user1993381 - 2 months ago 8x
Java Question

Adding a border to an image in Java

I am trying to create an image that adds a border to an existing image on Java by copying the pixels from their old locations to new coordinates. So far, this is what I have done:

public static NewPic border (NewPic p, int borderWidth, Pixel borderColor) {
int w = p.getWidth();
int h = p.getHeight();

Pixel src[][] = p.getBitmap();
Pixel tgt[][] = new Pixel[h][w];

for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
tgt[y][x + y + borderWidth] = src[x][y]; // this is probably where I a messing up
return new NewPic(tgt);

Not sure what I am doing wrong in the line where I commented. I am new to Java. Can someone give me some guidance?


One way is to use a Swing based border.

Image with Border

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.*;

class ImageBorder {

    public static void main(String[] args) {
    Runnable r = new Runnable() {

        public void run() {
        JPanel gui = new JPanel(new BorderLayout());
        // to contrast the 'picture frame' border created below
        gui.setBorder(new LineBorder(Color.BLUE, 12));

        Image image = // your image here..
            new BufferedImage(400,50,BufferedImage.TYPE_INT_RGB);
        JLabel l = new JLabel(new ImageIcon(image));
        Border b1 = new BevelBorder(
            BevelBorder.LOWERED, Color.LIGHT_GRAY, Color.DARK_GRAY);
        Border b2 = new LineBorder(Color.GRAY, 12);
        Border b3 = new BevelBorder(
            BevelBorder.LOWERED, Color.LIGHT_GRAY, Color.DARK_GRAY);
        Border bTemp = new CompoundBorder(b1,b2);
        Border b = new CompoundBorder(bTemp,b3);


        JOptionPane.showMessageDialog(null, gui);
    // Swing GUIs should be created and updated on the EDT