1

我正在尝试垂直镜像我在 Java 中拥有的像素图;这是我的代码:

Dimension coords = pixmap.getSize();
for (int x = 0; x < coords.width; x++) {
    for (int y = 0; y < coords.height; y++) {
        Color newest = pixmap.getColor(-x, y);
        pixmap.setColor(x, y, 
            new Color(newest.getRed(),
                      newest.getGreen(),
                      newest.getBlue()));
    }
}

“pixmap”是这个实例方法的参数,它本质上是加载的图像。这是我尝试翻转图像时遇到的运行时错误:

线程“AWT-EventQueue-0”java.lang.ArrayIndexOutOfBoundsException 中的异常:坐标超出范围!

有小费吗?谢谢!

**编辑**

我将代码更改为:

Dimension coords = pixmap.getSize();
for (int x = 0; x < coords.width; x++) {
    for (int y = 0; y < coords.height; y++) {
        Color newest = pixmap.getColor(x, y);
        if (x < coords.width / 2) {
            pixmap.setColor(((((coords.width/2) - x) * 2) + x), y, 
            new Color(newest.getRed(),
                      newest.getGreen(),
                      newest.getBlue()));
        } else {
        pixmap.setColor((x - (((x - (coords.width/2)) * 2))), y, 
            new Color(newest.getRed(),
                      newest.getGreen(),
                      newest.getBlue()));
        }
    }
}

而且我仍然遇到同样的越界异常;不知道我在这段代码上哪里出错了^

4

2 回答 2

1

另一种解决方案是使用具有负垂直比例的 Graphics2D 为您进行翻转...请注意,这必须与 translate (0, -height) 结合使用才能使图像回到中间。

public static void main(String[] args) throws IOException {
    BufferedImage image = ImageIO.read(new File("test.jpg"));

    BufferedImage mirrored = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);

    Graphics2D graphics = (Graphics2D)mirrored.getGraphics();
    AffineTransform transform = new AffineTransform();
    transform.setToScale(1, -1);
    transform.translate(0, -image.getHeight());
    graphics.setTransform(transform);
    graphics.drawImage(image, 0, 0, null);

    ImageIO.write(mirrored, "jpg", new File("test-flipped.jpg"));
}
于 2015-12-03T05:32:54.373 回答
1

Java 给你一个数组越界异常。您正在尝试访问给定数组大小中不存在的像素。

颜色最新 = pixmap.getColor(-x, y);

这很可能是问题所在。
像素图是一个二维数组。虽然我不熟悉这个类,但它可能看起来像这样:

//or whatever your screen is
int pixels[900][900];

话虽如此,您的代码正在尝试访问负 x 值坐标数组。

编辑:

Dimension coords = pixmap.getSize();
for (int x = 0; x < coords.width; x++) {
for (int y = 0; y < coords.height; y++) {
    pixmap.setColor(x, y, 
        new Color(newest.getRed(),
                  newest.getGreen(),
                  newest.getBlue()));
}
   }

我将假设此代码将绘制图像,因此

Dimension coords = pixmap.getSize();
for (int x = 0; x < coords.width; x++) {
for (int y = 0; y < coords.height; y++) {
    pixmap.setColor(coords.width-x, y, 
        new Color(newest.getRed(),
                  newest.getGreen(),
                  newest.getBlue()));
}
   }

应该绘制在 x 轴上翻转的图像。您可能可以从这里解决剩下的问题

于 2015-12-03T04:52:17.973 回答