Creating an empty image using ofImage::allocate

Hi, I’m trying to create an empty image so I can edit its pixels later.

void ofApp::setup(){

    img.allocate(100, 100, OF_IMAGE_COLOR);

    for (size_t i=0; i<img.getPixels().size(); ++i)
        img.setColor(i, ofColor(255,0,0));
    
    cout << img.getPixels().size() << endl;
    
    img.update();
}

I tried this code but it just draws white image.
Why doesn’t it draw red image? how do I properly color pixels?
And I don’t understand why img.getPixels().size() returns 30000 and not 10000.
Please help.

hey! try this:

img.allocate(100, 100, OF_IMAGE_COLOR);
img.setColor(ofColor::red);

img.getPixels().size() returns the size of the buffer wich is 10000 per channel. R+G+B = 30000.

1 Like

Thanks, your code works.

But do you know why this code still draws white image?

img.allocate(100, 100, OF_IMAGE_COLOR);

img.setColor(ofColor::white);

for (int i=0; i<100*100; ++i)
    img.setColor(i, ofColor::red);

img.update();

You don’t need the for loop.
Actually you are seeing a white image with one single red pixel.
That for loop is painting pixels channel by channel which is not what you want. that for loop paints 255,0,0 at pixel 0 when i=0, then overwrites the same pixel 0 as 255,255,0 when i=1, and then when i=2 same pixel becomes 255,255,255. this runs 10000 times writing pixels 3 times which at the end leaves them all white unless the last one.

if you want to paint pixel by pixel the for loop has to jump 3 units (channels) each pass. Look at the forum for more examples.

this has to work:

void ofApp::setup(){
	img.allocate(100, 100, OF_IMAGE_COLOR);
	img.setColor(ofColor::red);
	img.update();
}
void ofApp::draw(){
	img.draw(0,0);
}
1 Like

Thank you @Jordi