2013-03-12 88 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或它的親屬中。