旋转位图像素 [英] Rotate Bitmap pixels
问题描述
我想在那里旋转像素存储在阵列 INT像素[]
A位图。我得到了下面的方法:
I'm trying to rotate a Bitmap where the pixels are stored in an Array int pixels[]
. I got the following method:
public void rotate(double angle) {
double radians = Math.toRadians(angle);
double cos, sin;
cos = Math.cos(radians);
sin = Math.sin(radians);
int[] pixels2 = pixels;
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++) {
int centerx = this.width / 2, centery = this.height / 2;
int m = x - centerx;
int n = y - centery;
int j = (int) (m * cos + n * sin);
int k = (int) (n * cos - m * sin);
j += centerx;
k += centery;
if (!((j < 0) || (j > this.width - 1) || (k < 0) || (k > this.height - 1)))
try {
pixels2[(x * this.width + y)] = pixels[(k * this.width + j)];
} catch (Exception e) {
e.printStackTrace();
}
}
pixels = pixels2;
}
但它只是给我疯狂的结果。有谁知道哪里出错?
But it just gives me crazy results. Does anyone know where the error is?
推荐答案
行
int[] pixels2 = pixels;
应该是数组复制,但你只是复制引用。使用 pixels.clone()
。其实,你只需要一个新的空数组,所以新INT [pixels.lenght]
就足够了。最后,你需要 System.arraycopy
来新的内容复制到旧数组。
is supposed to copy the array, but you are just copying the reference to it. Use pixels.clone()
. In fact, you just need a new, empty array, so new int[pixels.lenght]
is enough. In the end you need System.arraycopy
to copy the new content into the old array.
有在code其他问题 - 你是混合行和列。仿佛该图像是由行通过柱存储行,其他如同柱一些前pressions写入。如果行由行(我的假设),那么这是没有意义的: X *宽+ Y
。它应该阅读 Y *宽+ X
- 你跳过是
行下来,然后移动 X
到右侧列。所有的一切,我有这个code,它的工作原理确定:
There are other problems in your code -- you are mixing up rows and columns. Some expressions are written as though the image is stored row by row, others as if column by column. If row-by-row (my assumption), then this doesn't make sense: x*width + y
. It should read y*width + x
-- you are skipping y
rows down and then moving x
columns to the right. All in all, I have this code that works OK:
import static java.lang.System.arraycopy;
public class Test
{
private final int width = 5, height = 5;
private int[] pixels = {0,0,1,0,0,
0,0,1,0,0,
0,0,1,0,0,
0,0,1,0,0,
0,0,1,0,0};
public Test rotate(double angle) {
final double radians = Math.toRadians(angle),
cos = Math.cos(radians), sin = Math.sin(radians);
final int[] pixels2 = new int[pixels.length];
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++) {
final int
centerx = this.width / 2, centery = this.height / 2,
m = x - centerx,
n = y - centery,
j = ((int) (m * cos + n * sin)) + centerx,
k = ((int) (n * cos - m * sin)) + centery;
if (j >= 0 && j < width && k >= 0 && k < this.height)
pixels2[(y * width + x)] = pixels[(k * width + j)];
}
arraycopy(pixels2, 0, pixels, 0, pixels.length);
return this;
}
public Test print() {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++)
System.out.print(pixels[width*y + x]);
System.out.println();
}
System.out.println();
return this;
}
public static void main(String[] args) {
new Test().print().rotate(-45).print();
}
}
这篇关于旋转位图像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!