public static byte [ ] compressAndWriteImageToBytes ( BufferedImage image , String formatName , float quality ) { byte [ ] bytes = null ; Iterator < ImageWriter > writers = ImageIO . getImageWritersByFormatName ( formatName ) ; if ( writers == null || ! writers . hasNext ( ) ) { throw new GeoPackageException ( "No Image Writer to compress format: " + formatName ) ; } ImageWriter writer = writers . next ( ) ; ImageWriteParam writeParam = writer . getDefaultWriteParam ( ) ; writeParam . setCompressionMode ( ImageWriteParam . MODE_EXPLICIT ) ; writeParam . setCompressionQuality ( quality ) ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; ImageOutputStream ios = null ; try { ios = ImageIO . createImageOutputStream ( baos ) ; writer . setOutput ( ios ) ; writer . write ( null , new IIOImage ( image , null , null ) , writeParam ) ; writer . dispose ( ) ; bytes = baos . toByteArray ( ) ; } catch ( IOException e ) { throw new GeoPackageException ( "Failed to compress image to format: " + formatName + ", with quality: " + quality , e ) ; } finally { closeQuietly ( ios ) ; closeQuietly ( baos ) ; } return bytes ; }
Compress and write the image to bytes in the provided format and quality