Skip to content

Instantly share code, notes, and snippets.

@zzzfree
Last active December 14, 2015 15:09
Show Gist options
  • Save zzzfree/5105932 to your computer and use it in GitHub Desktop.
Save zzzfree/5105932 to your computer and use it in GitHub Desktop.
ImageResize
import javax.swing.ImageIcon
import java.awt.Color
import java.awt.image.BufferedImage
import java.awt.image.ColorModel
import java.awt.image.WritableRaster
import java.awt.Graphics2D
import javax.imageio.*
import java.awt.*
import java.awt.geom.*
def resize(f,s ){
BufferedImage srcBufImage = ImageIO.read(new FileInputStream(f));
BufferedImage bufTarget = null;
int width, height
float u
if(srcBufImage.getWidth() > srcBufImage.getHeight()){
u = s / srcBufImage.getWidth()
}
else{
u = s / srcBufImage.getHeight()
}
width = u * srcBufImage.getWidth()
height = u * srcBufImage.getHeight()
double sx = (double) width / srcBufImage.getWidth()
double sy = (double) height / srcBufImage.getHeight()
int type = srcBufImage.getType();
if(type == BufferedImage.TYPE_CUSTOM){
ColorModel cm = srcBufImage.getColorModel()
WritableRaster raster = cm.createCompatibleWritableRaster(width,height)
boolean alphaPremultiplied = cm.isAlphaPremultiplied()
bufTarget = new BufferedImage(cm, raster, alphaPremultiplied, null)
}else
bufTarget = new BufferedImage(width, height, type)
Graphics2D g = bufTarget.createGraphics()
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY)
g.drawRenderedImage(srcBufImage, AffineTransform.getScaleInstance(sx, sy))
g.dispose()
return bufTarget
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment