private BufferedImage putIntoImageCache(BufferedImage bim, int width, int height, boolean allowScaling) {
        // create new Image cache if needed.
        if (image == null) {
            image = new ImageCache(library);
        }

        boolean setIsScaledOnImageCache = false;
        if (allowScaling && scaleImages && !image.isScaled()) {
            boolean canScale = checkMemory(
                    Math.max(width, bim.getWidth()) *
                            Math.max(height, bim.getHeight()) *
                            Math.max(4, bim.getColorModel().getPixelSize()));
            if (canScale) {
                // To limit the number of image file cache writes this scaling
                //  algorithem works with the buffered image in memory
                bim = ImageCache.scaleBufferedImage(bim, width, height);
                setIsScaledOnImageCache = true;
            }
        }

        // The checkMemory call above can make us lose our ImageCache
        synchronized (imageLock) {
            if (image == null) {
                image = new ImageCache(library);
            }
            // cache the new image
            if (setIsScaledOnImageCache)
                image.setIsScaled(true);
            image.setImage(bim);

            // read the image from the cache and return to caller
            bim = image.readImage();
        }
        return bim;
    }