Created
November 18, 2013 09:28
-
-
Save aembleton/7525085 to your computer and use it in GitHub Desktop.
Implicit ImageUtil class for manipulating images
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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