public static byte [ ] scaleImage ( byte [ ] imageBytes , String outputFormat , Integer targetSize ) throws Exception { InputStream is = null ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; byte [ ] imageInBytes = null ; BufferedImage image = null ; BufferedImage resizedImage = null ; try { is = new ByteArrayInputStream ( imageBytes ) ; image = ImageIO . read ( is ) ; resizedImage = Scalr . resize ( image , targetSize ) ; ImageIO . write ( resizedImage , outputFormat , baos ) ; imageInBytes = baos . toByteArray ( ) ; } catch ( Exception e ) { throw new Exception ( "Error on resizing an image: " + e . getMessage ( ) ) ; } finally { IOUtils . closeQuietly ( is ) ; IOUtils . closeQuietly ( baos ) ; if ( image != null ) { image . flush ( ) ; } if ( resizedImage != null ) { resizedImage . flush ( ) ; } } return imageInBytes ; }
Scales an image by the given dimensions