图片旋转90度说明
Rotate image 90 degrees explanation
所以我设法通过使用我的 180 度代码并基本上弄乱了图像来使图像旋转 90 度,但我仍然对代码实际做什么以及它如何做感到非常困惑。我理解 180 度旋转,但不理解下面代码的 90 度旋转。谁能给我解释一下?
OFImage image1 = new OFImage(image);
for (int x = 0; x < image.getWidth(); ++x) {
for (int y = 0; y < image.getHeight(); ++y) {
image.setPixel(y, x, image1.getPixel(image.getWidth() - x - 1, y));
老实说,不确定如何详细描述该过程,但它只是使用数学(显然),将每个像素单独与适当的替代像素交换,以产生 90 度旋转的效果。
为了帮助我理解它,我画了 3x3 和 4x4 的网格,并标记了每个单元格,模拟像素。并简单地使用方法 "setPixel" 及其参数作为一个方程,并将每个 pixel/co-ordinate 通过它来计算结果。我建议您也这样做,因为这可能是了解该方法如何正常工作的最佳方法。
我评论了你的代码
OFImage image1 = new OFImage(image); // create a copy of `image`
for (int x = 0; x < image.getWidth(); ++x) { // loop through each column of pixels in original presumably from left to right
for (int y = 0; y < image.getHeight(); ++y) { // loop through each cell of the column presumably from top to bottom
image.setPixel(y, x, image1.getPixel(image.getWidth() - x - 1, y)); // here you have swapped the x and y coordinates and you are putting in the pixel from the copy that is at width - x - 1, y
因此,当 x = 0(列)和 y = 0(行)时,您将复制来自 (W= image.width - 1, y) 的像素(第一行的最后一个像素) 到 (0,0) 所以 (W,0) => (0,0)
然后当 x = 0 且 y = 1 时 (W, 1) => (1, 0),则 (W, 2) => (2, 0)
在循环开始时,您从最右边的列开始读取,然后写入最上面的行。
所以我设法通过使用我的 180 度代码并基本上弄乱了图像来使图像旋转 90 度,但我仍然对代码实际做什么以及它如何做感到非常困惑。我理解 180 度旋转,但不理解下面代码的 90 度旋转。谁能给我解释一下?
OFImage image1 = new OFImage(image);
for (int x = 0; x < image.getWidth(); ++x) {
for (int y = 0; y < image.getHeight(); ++y) {
image.setPixel(y, x, image1.getPixel(image.getWidth() - x - 1, y));
老实说,不确定如何详细描述该过程,但它只是使用数学(显然),将每个像素单独与适当的替代像素交换,以产生 90 度旋转的效果。
为了帮助我理解它,我画了 3x3 和 4x4 的网格,并标记了每个单元格,模拟像素。并简单地使用方法 "setPixel" 及其参数作为一个方程,并将每个 pixel/co-ordinate 通过它来计算结果。我建议您也这样做,因为这可能是了解该方法如何正常工作的最佳方法。
我评论了你的代码
OFImage image1 = new OFImage(image); // create a copy of `image`
for (int x = 0; x < image.getWidth(); ++x) { // loop through each column of pixels in original presumably from left to right
for (int y = 0; y < image.getHeight(); ++y) { // loop through each cell of the column presumably from top to bottom
image.setPixel(y, x, image1.getPixel(image.getWidth() - x - 1, y)); // here you have swapped the x and y coordinates and you are putting in the pixel from the copy that is at width - x - 1, y
因此,当 x = 0(列)和 y = 0(行)时,您将复制来自 (W= image.width - 1, y) 的像素(第一行的最后一个像素) 到 (0,0) 所以 (W,0) => (0,0) 然后当 x = 0 且 y = 1 时 (W, 1) => (1, 0),则 (W, 2) => (2, 0)
在循环开始时,您从最右边的列开始读取,然后写入最上面的行。