Skip to main content
Skip table of contents

How to create unique images with Image.getInstance()?

How can I guarantee a new bitmap every time?

I need to use the GetInstance() variant that accepts raw bitmap data:

Image.getInstance(int width, int height, int components, int bpc, byte[] data);
But if I call it repeatedly, even if the bitmap data is actually different, I get the first instance back instead of a new one. This is a very good feature with, for instance, path-based fixed images but not that good for on-the-fly image generation. How can I guarantee a new bitmap every time?

 

Posted on StackOverflow on Nov 21, 2014 by Gábor

Please take a look at the RawImages example. In this example, I create 8 images using the method you mention, one in color space gray, three in color space RGB, four in color space CMYK:

Image gray = Image.getInstance(1, 1, 1, 8, new byte[] { (byte)0x80 });
gray.scaleAbsolute(30, 30);
Image red = Image.getInstance(1, 1, 3, 8, new byte[] { (byte)255, (byte)0, (byte)0 });
red.scaleAbsolute(30, 30);
Image green = Image.getInstance(1, 1, 3, 8, new byte[] { (byte)0, (byte)255, (byte)0 });
green.scaleAbsolute(30, 30);
Image blue = Image.getInstance(1, 1, 3, 8, new byte[] { (byte)0, (byte)0, (byte)255, });
blue.scaleAbsolute(30, 30);
Image cyan = Image.getInstance(1, 1, 4, 8, new byte[] { (byte)255, (byte)0, (byte)0, (byte)0 });
cyan.scaleAbsolute(30, 30);
Image magenta = Image.getInstance(1, 1, 4, 8, new byte[] { (byte)0, (byte)255, (byte)0, (byte)0 });
magenta.scaleAbsolute(30, 30);
Image yellow = Image.getInstance(1, 1, 4, 8, new byte[] { (byte)0, (byte)0, (byte)255, (byte)0 });
yellow.scaleAbsolute(30, 30);
Image black = Image.getInstance(1, 1, 4, 8, new byte[] { (byte)0, (byte)0, (byte)0, (byte)255 });
black.scaleAbsolute(30, 30);

As you can see, each image is exactly one pixel in size, and I chose different byte[] values so that I get pixels in gray, red, green, blue, cyan, magenta, yellow and black. I also scale these image to a bigger size (otherwise it would be difficult to see them).

Now I add the images like this:

document.add(gray);
document.add(red);
document.add(green);
document.add(blue);
document.add(cyan);
document.add(magenta);
document.add(yellow);
document.add(black);
document.close();

The result does not correspond with what you claim in your question: raw_images.pdf

Raw images

Raw images

There must be another error in your code, but since you don't share any code, nobody can answer your question.

Yes, I stand corrected. I used these images as soft masks and it turned out after much searching that the original images were replicated and forcing the same masks everywhere, not the on-the-fly generated masks themselves. Mea culpa and thanks.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.