你如何在Groovy中调整图像大小?

时间:2012-04-27 12:54:22

标签: image groovy jpeg

如何在Groovy中调整大小/缩小JPG图像的大小?

2 个答案:

答案 0 :(得分:10)

或者,如果您不想加载外部依赖项,只需正常执行:

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' ) )
}

答案 1 :(得分:5)

imgscalr 库有一个简单的API来启用此功能。

  • 下载imgscalr-lib jar (currently version 4.2)
  • 然后,您可以在一次通话中调整图片大小,例如Scalr.resize(imageIn, 1800)
  • 默认情况下,纵横比保持不变,第二个参数是新图像的最大宽度(或高度)

这是一个完整的工作示例......

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()

将imgscalr lib添加到类路径或使用-cp ...

调用groovy
  

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