2012-12-25 20 views
0

我想在傳遞到圖像後更改像素,並且它們仍應更改圖片。更改指針指向的對象,但對象不會在我的圖像類中更改

int main(int argc, char* argv[]){ 

    Image theImage(4, 8);//width/height 
    Pixel aPixel(2,1); 
    Pixel* p = &aPixel; 
    theImage.setPixel(p); 

    aPixel.setBlue(100);//change the blue (RGB) value of the pixel, but Pixel color doesnt change 

    theImage.saveAsPixelMap("/Users/dan/Desktop/test.ppm"); 
    return 0; 
} 

我以爲像素會改變顏色,因爲持有的imageCLASS指針,當指針仍然指向相同的像素,其顏色發生變化,不應該在Pixel`s顏色的圖像變化?

Here's像素構造:

Pixel::Pixel(int tx, int ty){ 
    red = 255; 
    green = 0; 
    blue = 0; 
    x = tx; 
    y = ty; 
    hasBeenChanged = false; 
} 

和對setPixel方法

void Image::setPixel(Pixel *aPixel){ 
    int tX = aPixel->getX(); 
    int tY = aPixel->getY(); 
    imageData.at(tY).at(tX)->setRed(aPixel->getRed());//value 0 - 255 
    imageData.at(tY).at(tX)->setGreen(aPixel->getGreen()); 
    imageData.at(tY).at(tX)->setBlue(aPixel->getBlue()); 
} 

爲imageData看起來像這樣

std::vector< std::vector<Pixel*> > imageData; 

和saveAsPixelmap方法。

void Image::saveAsPixelMap(char aPath[]){ 

    std::ofstream myfile; 
    myfile.open(aPath); 

    myfile << "P3\n" << this->getWidth() <<" "<< this->getHeight() <<"\n255\n"; 
    std::vector < Pixel* > row; 
    for (int y = 0; y < this->getHeight(); y++){ 
    row = imageData.at(y); 
    for (int x = 0; x < this->getWidth(); x++){ 

     myfile << row.at(x)->getRed() << " "; 
     myfile << row.at(x)->getGreen() << " "; 
     myfile << row.at(x)->getBlue() << " "; 
     std::cout <<"rot: "<< imageData.at(y).at(x)->getRed(); 

    } 
    } 
    std::cout << "\n Writing File to " << aPath << "\n \n"; 
    myfile.close(); 
} 

OK,it's大量的代碼,請問我,如果你需要的東西更多的信息,或者我的問題不夠清楚。任何提示如何解決這個大加讚賞

回答

1

你實現的概念是不同的東西你描述:

  • 描述的是, Image
  • 實現的是純副本語義(從給定像素讀取並將值放到其他像素中)

您需要某種類型的Image類的方法,它返回一個像素 - 它可以被改變。

例子:

class Image { 
// .. 
Pixel & get_pixel(int x, int y) { /* */ } 
} 

然後你可以改變像素(之後):

image.get_pixel(2,1).setBlue(100) 
+0

啊確定我真的很傻,只改變了現有像素的顏色,並沒有通過新的創建了Pixel。我想我必須改變一點。 – dan

+0

我改變了setPixel方法並刪除了複製語義。感謝提示。我也會想,如果get_pixel在將來可能有用,謝謝。 – dan

1

setPixel方法應採取的引用指針:

void Image::setPixel(Pixel *& aPixel) { .. } 
+0

快速現貨!大多數時候,人們在C++中通過引用錯誤傳遞。 +1 – nikhil

+0

它可悲的沒有工作,但下一張海報告訴我,我做錯了是的。 – dan

+0

Image :: setPixel不會更改指針的值。沒有優勢或需要傳遞參考。 –

相關問題