I'm trying to save a byte array of RGB values as a png image as follows:
byte imgArray = ...;
int canvasSize = 512;
ColorModel c = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY), null, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
Image image = Toolkit.getDefaultToolkit().createImage(
new MemoryImageSource(canvasSize, canvasSize, c, imgArray, 0, canvasSize));
BufferedImage bimage = new BufferedImage(canvasSize, canvasSize, BufferedImage.TYPE_BYTE_GRAY);
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(image, 0, 0, null); //This is what takes all the time
ImageIO.write(bimage, "PNG", new File(uniqueFileName));
I'm using a FixedThreadpool to save multiple images simultaneously. The more threads I use (up to the number of free cores I have on my computer), the longer the saving process takes. Running on 6 threads takes almost twice as long as running on one thread.
Why is this taking so much longer with multiple threads? Memory swaps? Can I avoid the problem?
Also, if there is a better way for me to be saving a png from an array, please let me know.
Edited to show pictures are being saved as distinct images, not overwriting each other.