Java:将图像旋转90度

标签 java image matrix rotation

我正在尝试编写一种将图像向右旋转 90 度的方法。我已经查看了有关此主题的其他帖子,但它们似乎都无法帮助我解决问题。我的代码似乎可以在纸面上运行,但我不知道为什么 j-unit 测试无法通过。为什么我的 j-unit 测试没有通过?

我的代码:

 /**
* intialize a picture by giving an image matrix
* @param imageMatrix two dimansionar RGBColor array
*/
public Picture(RGBColor imageMatrix[][]){
    this.width = imageMatrix.length;
    this.height = imageMatrix[0].length;
    this.imageMatrix = imageMatrix;
}

/**
 * turns this picture 90 degrees to the right
 *
 */
public void rot90DegRight(){
    int w = imageMatrix.length;
    int h = imageMatrix[0].length;
    RGBColor[][] rotatedMatrix = new RGBColor[h][w];
    for (int i = 0; i<h; i++){
        for(int j = 0; j<w; j++){
            rotatedMatrix[i][j] = imageMatrix[w-j-1][i];
        }
    }

}

这里也是 j-unit 测试用例:

@Test(timeout=1000)
public void testRot90DegRight(){
    RGBColor[][] imageMatrix = new RGBColor[100][100];
    for (int w=0; w<100; w++){
        for (int h=0; h<100; h++){
            if ((w==20) & (h==20)){
                imageMatrix[w][h] = new RGBColor(255,255,255);
            } else {
                imageMatrix[w][h] = new RGBColor(0,0,0);
            }
        }
    }
    Picture p = new Picture(imageMatrix);
    p.rot90DegRight();
    assertTrue("The white pixel was not rotated", !(p.getImageMatrix()[20][20].isWhite()));
    assertTrue("The white pixel was not rotated", (p.getImageMatrix()[79][20].isWhite()));

}

最佳答案

您创建了 rotatedMatrix 并在 rot90DegRight() 中分配了一些值,但随后简单地丢弃了结果。 您必须将旋转结果存储在某处。

添加

this.imageMatrix = rotatedMatrix;

在外部 for 循环之后可能会使其工作。

请注意,这将使其不再引用旋转后传递给构造函数的数组。

关于Java:将图像旋转90度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37214648/

相关文章:

java - 泛型方法和通配符

java - JFrame 由于所需库的限制而受到限制

java - 从 Java 代码将事件发送到 JavaFx webview 节点/元素

php - URL 链接中的 MySQL 和 HTML 数据库引用

python - Numpy 矩阵行比较

mysql - 当我尝试使用 mysql 中的数据库创建矩阵时,我在 JSP 文件中遇到 NullPointerException

python - 将字典转换为稀疏矩阵

Java 在初始化时将 var 添加到对象

html - :hover border-style:none not sticking to image within SSI

ios - 启动图像 Storyboard添加了 Imageview ,但在 Assets 文件夹中更改图像实际上并没有反射(reflect)在设备上?