How to resize images in Groovy?

How do you resize / resize JPG images in Groovy?

+6
source share
2 answers

Or, if you do not want to load an external dependency, just do it fine:

import static java.awt.RenderingHints.* import java.awt.image.BufferedImage import javax.imageio.ImageIO def img = ImageIO.read( new File( '/tmp/image.png' ) ) def scale = 0.5 int newWidth = img.width * scale int newHeight = img.height * scale 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, 'png', new File( '/tmp/scaled.png' ) ) } 
+10
source

The imgscalr library has a simple API to enable this.

  • Download imgscalr-lib jar (currently version 4.2)
  • You can then resize the image in one call, for example Scalr.resize(imageIn, 1800)
  • By default, the aspect ratio is kept the same, the second argument is the maximum width (or height) of the new image

Here is a complete working example ...

 import org.imgscalr.Scalr import java.awt.image.BufferedImage import javax.imageio.ImageIO def imageFile = new File("C:\\resize-image\\fullsize.jpg") def imageIn = ImageIO.read(imageFile); def newFile = new File("C:\\resize-image\\resized.jpg") BufferedImage scaledImage = Scalr.resize(imageIn, 1800); ImageIO.write(scaledImage, "jpg", newFile); println "Before: Width:"+imageIn.getWidth()+" Height:"+imageIn.getHeight()+" Size: "+ imageFile.size() println "After: Width:"+scaledImage.getWidth()+" Height:"+scaledImage.getHeight() +" Size: "+ newFile.size() 

Either add imgscalr lib to your class path, or call groovy with -cp ...

groovy -cp imgscalr-lib-4.2.jar resize-image.groovy

+5
source

Source: https://habr.com/ru/post/914335/


All Articles