gpt4 book ai didi

java - 将图片旋转90度时我做错了什么

转载 作者:行者123 更新时间:2023-12-01 13:53:20 26 4
gpt4 key购买 nike

我完全被这个问题难住了。这是我将数组旋转 90 度的逻辑:

示例:

1 2 3 4 5.....   ^
2 6 8 7 4..... |
6 4 9 8 0..... | .....THEN..... ------>
8 3 0 5 9..... |

所以如果我想将其旋转 90 度,我想要的是从最底行向上读取数组,然后在右侧添加宽度。所以数组将是

8 6 2 1
3 4 6 2
0 9 8 3
5 8 7 4
9 0 4 5

现在我将此逻辑应用于我的像素数组并将图片旋转 90 度

这是我的 Java 方法代码:

public void rotate90(){

Pixel[][] rotated = new Pixel[Iwidth][Iheight];

int Ch = Iheight-1, Cw = 0;

while (Cw < Iwidth){
while (Ch > -1){
rotated[Cw][Iheight - Ch - 1] = new Pixel(Image[Ch][Cw].getRed(), Image[Ch][Cw].getGreen(), Image[Ch][Cw].getBlue());
Ch--;
}
Cw++;
Ch = Iheight-1;
}

Image = rotated;


int temp = Iheight;
Iheight = Iwidth;
Iwidth = temp;
}

当我调用该方法时,它使图片乱码,但图片的宽度和高度被切换/交换。

但是当它让我着迷时,如果我尝试调用该方法两次,那么图片将正确旋转 180 度

如果我尝试调用该方法四次,图片将保持原样。

任何人都可以阐明我错过了什么或做错了什么吗?

<小时/>

我发现了问题,我无法回答自己的问题,所以这是我的代码的问题:

而不是放置

imageWriter.println(Iwidth + " " + Iheight);

我有一个

imageWriter.println(Iheight + " " + Iwidth);

在我的写作方法中愚蠢的我 -____-

感谢@Marcelo 和@rolfl 的帮助。发现问题了。

我的代码一直都是正确的,我有一个愚蠢的 1 行代码让我搞砸了

最佳答案

嗯,马塞洛比我先一步,但我的程序实际上运行了......

首先,要么实现一个 clone() 方法,要么为 Pixel 创建一个新的构造函数,它需要“复制”现有的 Pixel。

这种旋转作为位置的函数更容易处理......我在这里使用字符串值而不是像素来工作

public static void main(String[] args) {
final int width = 5, height = 3;
String[][] values = new String[height][width];
for (int c = 0; c < width; c++) {
for (int r = 0; r < height; r++) {
values[r][c] = String.format("%3d", r * width + c);
}
}

for (String[] row : values) {
System.out.println(Arrays.toString(row));
}

System.out.println();

int nheight = width;
int nwidth = height;

String[][] rotate = new String[nheight][nwidth];
for (int c = 0; c < nwidth; c++) {
for (int r = 0; r < nheight; r++) {
rotate[r][c] = values[height - 1 - c][r];
}
}

for (String[] row : rotate) {
System.out.println(Arrays.toString(row));
}
}

它产生输出

[  0,   1,   2,   3,   4]
[ 5, 6, 7, 8, 9]
[ 10, 11, 12, 13, 14]

[ 10, 5, 0]
[ 11, 6, 1]
[ 12, 7, 2]
[ 13, 8, 3]
[ 14, 9, 4]

关于java - 将图片旋转90度时我做错了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19795135/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com