2013-03-12 90 views
1

我正尝试通过将像素从旧位置复制到新坐标来创建一个图像,该图像将边框添加到Java上的现有图像。我的解决方案正在工作,但我想知道是否有更高效/更短的方法来做到这一点。在Java中添加边框

/** Create a new image by adding a border to a specified image. 
* 
* @param p 
* @param borderWidth number of pixels in the border 
* @param borderColor color of the border. 
* @return 
*/ 
    public static NewPic border(NewPic p, int borderWidth, Pixel borderColor) { 
    int w = p.getWidth() + (2 * borderWidth); // new width 
    int h = p.getHeight() + (2 * borderWidth); // new height 

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

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

     } 
    } 

    return new NewPic(tgt); 
    } 

回答

2

如果只是呈现在屏幕上,而目的不是边界实际添加到图像,但具有存在与边框,the component that is displaying your image can be configured with a border屏幕上的图像。

component.setBorder(BorderFactory.createMatteBorder(
           4, 4, 4, 4, Color.BLACK)); 

会在黑色中显示一个4像素(在每个边缘上)边框。但是,如果意图是真正重新绘制图像,那么我会通过抓取每个行数组,然后使用ByteBuffer并使用批量操作在行数组(和边框元素)中进行复制来接近它,然后将整个ByteBuffer的内容作为数组抓取回图像。

这是否使性能有任何不同是未知的,在优化之前和之后进行基准测试,因为结果代码实际上可能会变慢。

主要问题是虽然系统数组函数允许批量复制和填充数组内容,但它不提供一个实用程序来将其转换为目标数组上的偏移量;但是,NIO软件包中的缓冲区允许您轻松完成此操作,因此如果存在解决方案,则位于NIO ByteBuffer或它的亲属中。