Drawing to image with Graphics class broken on Windows with JUCE 8

This simple code to produce a red output image will not work with JUCE 8 on Windows. It will always result in an “empty” image (black image with JPEG, transparent image with PNG).

It worked well with JUCE 7 on both Windows and Mac and also works with JUCE 8 on macOS.

Image image(Image::PixelFormat::RGB, 200, 200, true);
Graphics graphicsContext(image);
graphicsContext.setColour(Colours::red);
graphicsContext.fillRect(0, 0, image.getWidth(), image.getHeight());

File outputFile("<some path>/test.jpg");
FileOutputStream stream(outputFile);
JPEGImageFormat jpegFormat;
jpegFormat.writeImageToStream(image, stream);

Have a read of the feature overview JUCE 8 Feature Overview: Direct 2D - JUCE.

With Direct2D in JUCE 8, graphics contexts do not draw to their images until they go out of scope. According to the overview, wrapping lines 2 to 4 in curly brackets should fix your example.

3 Likes

Ah that makes sense!
Thanks for your help!

I extracted it into a small function and now it works.