Skip to content

Instantly share code, notes, and snippets.

@brooksandrew
Created April 12, 2016 19:26
Show Gist options
  • Save brooksandrew/8138798fc9cc249882152d5234edc9aa to your computer and use it in GitHub Desktop.
Save brooksandrew/8138798fc9cc249882152d5234edc9aa to your computer and use it in GitHub Desktop.
Square rectangular images and center as much as possible using ImageIO and imgscalr in Scala. Save output as new jpg.
import org.imgscalr._
import java.io.File
import javax.imageio.ImageIO
object makeSqaure extends App {
def makeSquare(img: java.awt.image.BufferedImage): java.awt.image.BufferedImage = {
val w = img.getWidth
val h = img.getHeight
val dim = List(w, h).min
img match {
case x if w == h => img
case x if w > h => Scalr.crop(img, (w-h)/2, 0, dim, dim)
case x if w < h => Scalr.crop(img, 0, (h-w)/2, dim, dim)
}
}
val myimg = ImageIO.read(new File("data/images/train/20.jpg"))
val myimgSquare = makeSquare(myimg)
ImageIO.write(myimgSquare, "jpg", new File("20square.jpg"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment