Skip to content

Instantly share code, notes, and snippets.

@aembleton
Created November 18, 2013 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aembleton/7525085 to your computer and use it in GitHub Desktop.
Save aembleton/7525085 to your computer and use it in GitHub Desktop.
Implicit ImageUtil class for manipulating images
package util
import java.awt.image.BufferedImage
import java.awt.{Color, Image}
/**
* Created with IntelliJ IDEA.
* User: arthur
* Date: 17/11/13
* Time: 22:26
* To change this template use File | Settings | File Templates.
*/
object ImageUtil {
implicit class ImageImprovements(val i: BufferedImage) {
def scaleToWidth (width:Int) = {
val height = (i.getHeight.toDouble*(width.toDouble/i.getWidth.toDouble)).toInt
val scaledImage = i.getScaledInstance(width, height, Image.SCALE_SMOOTH)
val imageBuff = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
val graphics = imageBuff.createGraphics
graphics.drawImage(scaledImage,0,0,Color.black,null)
graphics.dispose
imageBuff
}
def getCentreCut (width:Int, height:Int) = {
val x = centre(i.getWidth,width)
val y = centre(i.getHeight,height)
i.getSubimage(x,y,smallest(width,i.getWidth),smallest(height,i.getHeight))
}
def minimumDimensions(width:Int,height:Int) = {
if (width > i.getWidth || height > i.getHeight) {
val imageBuff = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
val graphics = imageBuff.createGraphics
graphics.drawImage(i, centre(width,i.getWidth),centre(height,i.getHeight),Color.black,null)
graphics.dispose()
imageBuff
} else {
i
}
}
private[ImageImprovements] def centre (oldDim:Int, newDim:Int) = {
if (oldDim > newDim) {
(oldDim - newDim)/2
}else {
0
}
}
private[ImageImprovements] def smallest (a:Int, b:Int) = {
if (a < b) {
a
} else {
b
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment