Problem with ofColor::setColor

I am just trying to get started with writing colors to the pixels of an image directly. I try to initialize an ofImage, then loop through each pixel and write it to have a random color. But this doesn’t work for me. What is wrong with the following code?

  
  
ofImage img;  
img.allocate(128, 128, OF_IMAGE_COLOR);  
for (int i=0; i<128; i++) {  
    for (int j=0; j<128; j++) {  
        img.setColor(i, j, ofColor(ofRandom(255), ofRandom(255), ofRandom(255)));  
    }  
}  
  

but when I draw img in the draw loop it just contains nonsense (I guess whatever happens to be in the memory at that time. But I am expecting to see a field of random colors. Is this a bug or am I doing something wrong? Thanks!

You need to make sure you update the image before you draw it:

  
  
img.allocate(128, 128, OF_IMAGE_COLOR);    
for (int i=0; i<128; i++) {    
    for (int j=0; j<128; j++) {    
        img.setColor(i, j, ofColor(ofRandom(255), ofRandom(255), ofRandom(255)));    
    }    
}    
img.update();  
  
  

the ofImage is really two things: pixels in RAM and a texture on the graphics card. When you call setColor() you’re changing the pixels in RAM, but that doesn’t get loaded onto the graphics card until you call image.update(). This is so that there isn’t traffic to the graphics card every time you change the image which makes your application faster at the expense of it being a little trickier. Hope that helps some.

Perfect explanation, thanks!