Zmiana rozmiaru obrazu w Grailach

Rozwijam Album internetowy za pomocą Grails i do przetwarzania obrazów używam wtyczki grails-image-tools. Potrzebuję funkcjonalności, aby zmienić rozmiar obrazów, jeśli rozmiar przesłanych obrazów jest zbyt duży (na przykład: więcej niż 600 * 840 ) . W tym przypadku muszę zmienić rozmiar tego obrazu do 600 * 840). Jaki jest najskuteczniejszy sposób, aby to zrobić? Wielkie dzięki.

Author: Wasim, 2008-12-12

3 answers

import java.awt.Image as AWTImage 
import java.awt.image.BufferedImage      
import javax.swing.ImageIcon 
import javax.imageio.ImageIO as IIO  
import java.awt.Graphics2D


static resize = { bytes, out, maxW, maxH -> 
    AWTImage ai = new ImageIcon(bytes).image 
    int width = ai.getWidth( null ) 
    int height = ai.getHeight( null )

    def limits = 300..2000 
    assert limits.contains( width ) && limits.contains( height ) : 'Picture is either too small or too big!'

    float aspectRatio = width / height float requiredAspectRatio = maxW / maxH

    int dstW = 0 
    int dstH = 0 
    if (requiredAspectRatio < aspectRatio) { 
        dstW = maxW dstH = Math.round( maxW / aspectRatio) 
    } else { 
        dstH = maxH dstW = Math.round(maxH * aspectRatio) 
    }

    BufferedImage bi = new BufferedImage(dstW, dstH,   BufferedImage.TYPE_INT_RGB)            
    Graphics2D g2d = bi.createGraphics() g2d.drawImage(ai, 0, 0, dstW, dstH, null, null) 

    IIO.write( bi, 'JPEG', out )
} 
 7
Author: Warrior,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-03-10 16:27:02

In BuildConfig.groovy Dodaj zależność do imgscalr

dependencies {
    compile 'org.imgscalr:imgscalr-lib:4.1'     
}

Wtedy zmiana rozmiaru obrazów staje się jednowierszowa:

BufferedImage thumbnail = Scalr.resize(image, 150);
 13
Author: Dónal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-30 20:07:45
 1
Author: Teo Choong Ping,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-01-06 08:13:27