【问题标题】:adding a border in Java [duplicate]在Java中添加边框[重复]
【发布时间】:2013-03-13 00:30:57
【问题描述】:

我正在尝试创建一个图像,通过将像素从旧位置复制到新坐标来为 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);
    }

【问题讨论】:

    标签: java


    【解决方案1】:

    如果只是为了呈现到屏幕上,并且意图不是为图像实际添加边框,而是让图像带有边框,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 并使用批量 put(...) 操作复制行数组(和边框元素)来接近它,然后将整个 ByteBuffer 的内容作为一个数组抓取到图像中。

    这是否会对性能产生任何影响尚不清楚,请在尝试优化之前和之后进行基准测试,因为生成的代码实际上可能会更慢。

    主要问题是,虽然系统数组函数允许批量复制和填充数组内容,但它没有提供实用程序来执行目标数组的偏移量;但是,NIO 包中的 Buffers 让您可以很容易地做到这一点,所以如果存在解决方案,它就在 NIO ByteBuffer 中或者它的亲属中。

    【讨论】:

      猜你喜欢
      • 2021-04-20
      • 2016-07-04
      • 1970-01-01
      • 1970-01-01
      • 2013-02-27
      • 2021-10-14
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多