Compress Image via CPI iFlow

sometimes we have requirement to process binary stream like image files and via some groovy library, the iflow can fulfill tasks like compress a huge image into a smaller one.

This is not a majory function of iflow, whereas as long as you have a similar requirement or you are interested how iflow is dealing with binary stream, you are more than welcome to go through the rest of the blog.

The iflow can be download from github: link

Groovy script compress image

import groovy.transform.Field
import static java.awt.RenderingHints.*
import java.awt.image.BufferedImage
import javax.imageio.ImageIO
/* ************************************************************************ Program : CompressImage.groovy Create Date : Oct-26-2021 Author : Stephen Xue Parameters : message --> message reference from framework; testFlag--> true for test mode; default for production code mode; Function : 1. Compress Image Source: BINARY Target: BINARY *************************************************************************/
Message processData(Message message, def testFlag = null) { def body = message.getBody(byte[]); //def body = message.getBody() as String; InputStream is = new ByteArrayInputStream(body); def img = is ); def type = message.getHeaders().get('Content-Type').toString().split("/")?.getAt(1); def scale = message.getProperties().get('scale') as float; int newWidth = img.width * scale; int newHeight = img.height * scale; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); new BufferedImage( newWidth, newHeight, img.type ).with { i -> createGraphics().with { setRenderingHint( KEY_INTERPOLATION, VALUE_INTERPOLATION_BICUBIC ); drawImage( img, 0, 0, newWidth, newHeight, null ); dispose(); } ImageIO.write( i, type, outputStream); } message.setBody(outputStream); return message

the scale is read from property configuration parameter.

This is the iflow process

if the input parameter ‘compress’ is false, it will go through the normal way without compress;

if the input parameter ‘compress’ is true, it will compress the image via the ‘scale’ configured;

These three parameters needs to be configrued

URL is the image http url.

  1. without compress

here an image of Chinese actress,fbb has been usd as an example. actually fbb is one of my favorate movie stars.

the direct link is here.

this is the image without any compression

2. With Compress

this is the effect with 0.6 scale compress

for a better comparison, this is a 0.1 scale compress

i have tested, the source code can process png files as well.

with groovy, we can

  • parse image binary stream
  • compress image

feel free to download the iflow from github: link