Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you resize images in Groovy?

Tags:

image

groovy

jpeg

How do you resize/reduce the size of JPG images in Groovy?

like image 300
Chris Avatar asked Apr 27 '12 12:04

Chris


People also ask

How do you resize an image in Java?

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.

How do I resize an image in an element?

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.

How do I manually resize an image in Python?

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.


2 Answers

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' ) )
}
like image 153
tim_yates Avatar answered Oct 09 '22 11:10

tim_yates


The imgscalr library has a simple API to enable this.

  • Download the imgscalr-lib jar (currently version 4.2)
  • You can then resize an image in one call, eg Scalr.resize(imageIn, 1800)
  • By default the aspect ratio is kept the same, the 2nd argument is the maximum widght (or height) of the new Image

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

like image 27
Chris Avatar answered Oct 09 '22 12:10

Chris