Graphics Class isn't drawing to image

Hey there! I’m relatively new to Juce and am having troubles with my graphics class. The graphics for the paint() function works fine without troubles however I want to save an image based on some info I gather from the window. As such I created an Image and then a Graphics using that image: The code is as follows:

void saveGraphAsImage()
{
//check that window size is greater than 0
if (getWidth() > 0 && getHeight() > 0)
{
// Create Image Data
juce::Image image(juce::Image::RGB, getWidth(), getHeight(), false);

    // Create graphics to draw data to image
    juce::Graphics g(image);
    g.setOpacity(1.0f);
    g.fillAll(juce::Colours::green);
    g.setColour(juce::Colours::yellow);
    g.fillEllipse(200, 200, 200, 200);

    // save image
    juce::File outputFile = File::getCurrentWorkingDirectory().getChildFile("spectrum.png");
    juce::PNGImageFormat pngFormat;
    if (auto outputStream = outputFile.createOutputStream())
        pngFormat.writeImageToStream(image, *outputStream);
}

}
I’ve tried to solve this after looking through all the documentation however no matter what I do the graphics class doesn’t do anything. I can directly edit the image and save that (for instance a for loop that draws a line or box works fine) however that defeats the point of the Graphics class altogether and I have more complex drawing needs. Any idea why my graphics is just not drawing on my image?

Try adding some curly braces around the Graphics instance like so:

juce::Image image(juce::Image::RGB, getWidth(), getHeight(), false);

{
    // Create graphics to draw data to image
    juce::Graphics g(image);
    g.setOpacity(1.0f);
    g.fillAll(juce::Colours::green);
    g.setColour(juce::Colours::yellow);
    g.fillEllipse(200, 200, 200, 200);
}

// save image
auto outputFile = File::getCurrentWorkingDirectory().getChildFile("spectrum.png");

On some platforms, the Graphics object will not update the image until its destructor runs, i.e. it goes out-of-scope.

2 Likes

Thank you! This fixed the problem.