2013-03-27 27 views
1

我需要反转存储在double [] img中的给定长度和宽度的图像; 这是我第一次使用数组。说明是嵌套for循环,y(行)上的外部循环和x(列)上的内部循环,并反转每个水平数组。 这是我有,它不工作。试图在Java中反转存储在数组中的图像

width = ImageLibrary.getImageWidth(); 
height = ImageLibrary.getImageHeight(); 

    for(i = 0; i < width ; i++){ 
    for(j = 0; j < height ; j++){ 
     for(int k = 0; k < img.length/2; k++){ 
      double temp = img[k]; 
      img[i] = img[img.length - k - 1]; 
      img[img.length - k - 1] = temp; 
} 
    } 
    } 

我真的不确定该怎么做?当它说要扭转水平阵列时,我是否正确地做到了这一点? 谢谢

+0

请解释“反向”是什么意思?像镜像水平或垂直?或两者?或者完全不同的东西? – Ridcully 2013-03-27 19:04:21

+0

对不起,是垂直镜像我认为。说一只猫向右看的图像,现在它将被镜像到它正在向左看。 – 2013-03-27 19:06:52

回答

3

我想你要寻找的是更喜欢这个

width = ImageLibrary.getImageWidth(); 
height = ImageLibrary.getImageHeight(); 

// Loop from the top of the image to the bottom 
for (y = 0; y < height ; y++) { 

    // Loop halfway across each row because going all the way will result 
    // in all the numbers being put back where they were to start with 
    for (x = 0; x < width/2 ; x++) { 

     // Here, `y * width` gets the row, and `+ x` gets position in that row 
     double temp = img[y * width + x]; 

     // Here, `width - x - 1` gets x positions in from the end of the row 
     // Subtracting 1 because of 0-based index 
     img[y * width + x] = img[y * width + (width - x - 1)]; 
     img[y * width + (width - x - 1)] = temp; 
    } 
} 

所以现在左边是右边这将产生图像的镜像,而右侧是左侧

+0

谢谢你的回答,但不幸的是它给了我一个非常伸展和扭曲的图像 – 2013-03-27 19:12:38

+0

拉伸和扭曲?奇怪,但我会继续想着如何让它工作...... – jonhopkins 2013-03-27 19:16:53

+0

我确切地知道我做错了什么。我正在假设方形尺寸的图像...已更新的答案。让我知道如果它现在的作品:) – jonhopkins 2013-03-27 19:29:22