[JAVA] Efficient and fastest way to convert a buffered image to PNG/bytearray using aspose pdf image or aspose image

Hi,
Looking to convert a buffered image (created using graphics2d) to png (lossless to retain quality and have a minimal file size) which would be converetd to byte array for further processing. Wanted to know if there is away to achieve the same using aspose.pdf.image or any other aspose.imaging api that can help in this.

Hi, @maheibm
We appreciate your interest in Aspose.Imaging.
You can convert your BufferImage into PNG and save it in the byte array.

byte[] convertToPng(BufferedImage image)
{
	Image asposeImage = ImageExtensions.fromJava(image);
	try (ByteArrayOutputStream baos = new ByteArrayOutputStream(8096))
	{
		PngOptions options = new PngOptions();
		options.setColorType(PngColorType.Truecolor); // without alpha to minimize the size
		options.setCompressionLevel(9);
		options.setFilterType(PngFilterType.Adaptive);
		asposeImage.save(baos, options);
		return baos.toByteArray();
	}
}
1 Like

Thanks for the response. There is a huge heap memory utilisation while achieving using the above snippet and is much slower(8times) than objectplanet pngencoder. Could you please assist on the same.

Hello, @maheibm
Sorry for delaying :frowning:
Yes, it is expected that memory utilization grow while using ByteArrayOutputStream. For the big images, the best way is to use the file as a storage, not a byte array. And talking of speed, you should decide what is more important for you - the speed or the output size. You may export the image without these lines

options.setCompressionLevel(9);
options.setFilterType(PngFilterType.Adaptive);

Hope, I could help you with your needs.

Thanks for the response. Also is there a simplest and efficient way to get PngColorType based on bufferedimage? i see that we get color model from bufferedimage, can i obtain PngColorType using that ? please suggest as this would help me determine whether to use PngColorType.Truecolor or PngColorType.grayscale so that the file output size is reduced (for each page in a doc).

image.getColorModel().getColorSpace().getType() ?

int colorType = PngColorType.Grayscale;
if(image.getColorModel().getColorSpace().getType() == ColorSpace.TYPE_RGB)
{
colorType = PngColorType.Truecolor;
}

@maheibm
I am sorry for the delay… :frowning:
Yes, such a way to select the PngColorType allows you to minimize the final image.
Also, you can use ImageIO.write(image, “PNG”) for this purpose.