在 Java 中为图像添加边框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15351604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:19:34  来源:igfitidea点击:

Adding a border to an image in Java

javaimageawtborder

提问by user1993381

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:

我正在尝试创建一个图像,通过将像素从旧位置复制到新坐标,为 Java 上的现有图像添加边框。到目前为止,这就是我所做的:

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?

不确定我在评论的那一行做错了什么。我是 Java 新手。有人可以给我一些指导吗?

回答by Andrew Thompson

One way is to use a Swing based border.

一种方法是使用基于 Swing 的边框。

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() {

        @Override
        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);
        l.setBorder(b);

        gui.add(l);

        JOptionPane.showMessageDialog(null, gui);
        }
    };
    // Swing GUIs should be created and updated on the EDT
    // http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
    SwingUtilities.invokeLater(r);
    }
}

回答by syb0rg

You could create a BorderedBufferedImagethat accepts an intfor borderThickness, a Color for the borderColor, and a BufferedImage.

您可以创建一个BorderedBufferedImage接受intfor borderThickness、 Color for theborderColor和 a 的BufferedImage

This websitemight also offer some help:

这个网站也可能提供一些帮助:

import java.awt.*;
import javax.swing.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;
import javax.swing.BorderFactory; 

class testImagePanel{
    public static void main(String[] args){

    BufferedImage image = null;
    ImagePanel imagePanel = null;

    try{
        image = ImageIO.read(new File("Pictures/pl.jpg"));
        imagePanel = new ImagePanel(image);
    }catch(IOException  e){
         System.err.println("Trying to read in image "+e);
    }

    JFrame frame = new JFrame("Example");
    frame.add(imagePanel);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);   

    }
}

public class ImagePanel extends JPanel {

BufferedImage image;
Dimension size;

public ImagePanel(BufferedImage image) {
    this.image = image;
    this.size = new Dimension();
    size.setSize(image.getWidth(), image.getHeight());
    this.setBackground(Color.WHITE);
    this.setBorder(BorderFactory.createLineBorder(Color.RED, 1));
}

@Override
protected void paintComponent(Graphics g) {
    // Center image in this component.
    int x = (getWidth() - size.width)/2;
    int y = (getHeight() - size.height)/2;
    g.drawImage(image, x, y, this);
}
@Override
public Dimension getPreferredSize() { return size; }
}

回答by Manav

I used following logic to add border to any image:

我使用以下逻辑为任何图像添加边框:

BufferedImage source = ImageIO.read(original);
int borderedImageWidth = width + (borderLeft * 2);
int borderedImageHeight = height + (borderTop * 2);
BufferedImage img = new BufferedImage(borderedImageWidth, borderedImageHeight, BufferedImage.TYPE_3BYTE_BGR);
img.createGraphics();
Graphics2D g = (Graphics2D) img.getGraphics();
g.setColor(Color.YELLOW);
g.fillRect(0, 0, borderedImageWidth, borderedImageHeight);
g.drawImage(source, borderLeft, borderTop, width + borderLeft, height + borderTop, 0, 0, width, height, Color.YELLOW, null);
File output = File.createTempFile("output", ".png");
ImageIO.write(img, "png", outputFile);

This will draw an image over a yellow rectangle whose size is greater then the image, thus providing a border to image.

这将在尺寸大于图像的黄色矩形上绘制图像,从而为图像提供边框。

回答by Richard

I know this thread is from 2013 but I came across this, and I have a solution that preserves what OP was trying to do:

我知道这个帖子是 2013 年的,但我遇到了这个,我有一个解决方案可以保留 OP 试图做的事情:

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 + borderWidth * 2][w + borderWidth * 2];

   for (int x = 0; x < w + borderWidth; x++) 
   {
      for (int y = 0; y < h + borderWidth; y++) 
      {
         if (x >= borderWidth && x < w - borderWidth && y >= borderWidth && y < h - borderWidth)
         {
            tgt[x][y] = src[x - borderWidth][y - borderWidth];
         }
         else
         {
            tgt[x][y] = borderColor;
         }
      }
   }
   return new NewPic(tgt);
}

回答by JaRo

Clean Java simplest way:

清理Java最简单的方法:

String imagePath = "this/is/your/image.jpg";
BufferedImage myPicture = ImageIO.read(new File(imagePath));
Graphics2D g = (Graphics2D) myPicture.getGraphics();
g.setStroke(new BasicStroke(3));
g.setColor(Color.BLUE);
g.drawRect(10, 10, myPicture.getWidth() - 20, myPicture.getHeight() - 20);
ImageIO.write(myPicture, "jpg", new File(imagePath));