Asynchronicity when drawing to Image [SOLVED]

Hi, this might be something obvious I’m missing, but I’m trying to save images to disk and they always turn out empty. Consider the following code:

// create image
juce::Image image (juce::Image::RGB, WIDTH, HEIGHT, true);

// create graphics context for image and fill it green
juce::Graphics g (image);
g.fillAll (juce::Colours::green);

// save image to disk
juce::File file ("/path/to/image.png");
juce::PNGImageFormat pngFormat;
juce::FileOutputStream outputStream (file);
pngFormat.writeImageToStream (image, outputStream);

Now I would expect the saved image to be green. It is, however, black (transparent if I do ARGB).

I tried caching this image and drawing it later in paint() for debugging but now it gets weird. When I save the image like this:

saveImageToDrawLater = image; // this will be drawn as a GREEN image later in paint()

However,

saveImageToDrawLater = image.createCopy(); // this will be drawn as a BLACK image later in paint()

… Whats going on? It’s almost like the image gets painted only at some point later and is then only ready for the next call of paint?

The destructor of the Graphics object may flush pending drawing operations to the image, depending on the drawing backend. Therefore, it’s good practice to make sure that the Graphics instance has been destroyed before accessing the image through other means, including before writing it to file. In the example you provided, I expect that putting some {curly braces} around the two lines I quoted will fix the issue.

Hi reuk, this solves it. Thank you!

1 Like