+ImageFileFormat::loadFrom will fail if Image is not a PNG

The following code will fail if the URL points to a JPEG file.
Because internally ImageFileFormat::loadFrom will try different formats. If the image format isn’t PNG it will try to read it as a JPEG. However to do so it will try to rewind the position of the inputStream. But as the inputstream is a WebInputStream this is impossible (at least the implementation does not seem to allow it) and thus it will fail to read the JPEG as it already advanced a few bytes into the stream.

std::unique_ptr<InputStream> response(url.createInputStream(false);
Image thumbnail = ImageFileFormat::loadFrom(*response);

What will work is to first read the response into a MemoryBlock and create a MemoryInputStream. This works because the MemoryInputStream is positionable.

URL url;
std::unique_ptr<InputStream> response(url.createInputStream(false);
MemoryBlock block;
response->readIntoMemoryBlock(block);
MemoryInputStream mis(block, false);
Image thumbnail = ImageFileFormat::loadFrom(mis);

We have recently moved on to using a new version of JUCE and the old version did work with the first snippet.

So i would suggest looking into this because this is a hard problem to spot if you are not aware of this.

Thanks for sharing your insights on handling image files! Even though it’s been a few years since you posted this, your workaround for loading JPEG files without running into issues is still valuable. It’s always helpful to have alternative solutions, especially when dealing with tricky problems like this.

By the way, if anyone needs to compress their images before processing them, I recommend checking out this compress image tool. It’s a handy tool for reducing file sizes without compromising too much on quality.

Thanks again for sharing your expertise, and I’m sure your suggestion has helped many developers over the years