2013-03-27 25 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