Improve image cache clearing logic (Bug#6230).