How do you resize/reduce the size of JPG images in Groovy?
You can resize an image in Java using the getScaledInstance() function, available in the Java Image class. We'll use the BufferedImage class that extends the basic Image class. It stores images as an array of pixels.
One of the simplest ways to resize an image in the HTML is using the height and width attributes on the img tag. These values specify the height and width of the image element. The values are set in px i.e. CSS pixels.
To resize an image, you call the resize() method on it, passing in a two-integer tuple argument representing the width and height of the resized image. The function doesn't modify the used image; it instead returns another Image with the new dimensions.
Or, if you don't want to load an external dependency, just do it normally:
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' ) )
}
The imgscalr library has a simple API to enable this.
Scalr.resize(imageIn, 1800)
Here's a full 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 the imgscalr lib to your class path or call groovy with -cp...
groovy -cp imgscalr-lib-4.2.jar resize-image.groovy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With