Kotlin utility functions for Java AWT BufferedImage
val image = BufferedImages.load("large-cat-2000x2000.png")
image = image.subimage(500, 500, 1000, 1000)
val g = image.createBestQualityGraphics()
try {
g.drawImage...
g.fillRect...
}
finally {
g.dispose()
}
image = image.resize(100, 100) // This is way faster than AWT!
image = image.toJpeg()
image.save("small-cat.jpg")
- Easily create, load, save, send images
- Fast resize
- High-quality graphics instantiation
- JPEG / PNG conversion
- Subimage not failing on out-of-borders
- Get image size (for content-length) without loading the whole image
- Only two image types - JPEG and transparent PNG, no need to deal with different AWT types
- Functions are
java.awt.image.BufferedImage
class extensions
- We assume that PNG is transparent, i.e. always have alpha-channel.
Simply clone com.minogin.graphics.BufferedImages.kt to your project
com.minogin.graphics.ImageType
Either JPEG or PNG.
Could be detected: of(awtType: Int)
, of(f: File):
, of(filePath: String)
Could be converted: toAWT()
, toContentType()
, toImageWriter()
, toImageWriteParam(writer: ImageWriter)
BufferedImages companion object
BufferedImages.create(width: Int, height: Int, type: ImageType): BufferedImage
BufferedImages.load(inputStream: InputStream, type: ImageType): BufferedImage
BufferedImages.load(file: File, type: ImageType = ImageType.of(file)): BufferedImage
BufferedImages.load(path: String, type: ImageType = ImageType.of(path)): BufferedImage
All functions load image to Int instead of Byte buffer
BufferedImages.send(imagePath: String, response: HttpServletResponse)
Useful for Spring MVC controllers
java.awt.image.BufferedImage extensions
fun resize(targetWidth: Int, targetHeight: Int, type: ImageType = getImageType()): BufferedImage
fun scaleToNewWidth(targetWidth: Int, type: ImageType = getImageType()): BufferedImage
fun scaleToNewHeight(newHeight: Int, type: ImageType = getImageType()): BufferedImage
Way faster than AWT getScaledInstance(...)
data class ImageSize(val width: Int, val height: Int)
fun getImageSize(inputStream: InputStream): ImageSize
fun getImageSize(path: String): ImageSize
fun subimage(x: Int, y: Int, w: Int, h: Int): BufferedImage
Doesn't fail on out of border values
fun createBestQualityGraphics(): Graphics2D
Creates graphics with high quality hints applied (for text rendering either).
fun toJpeg(): BufferedImage
fun toPng(): BufferedImage
fun save(file: File, type: ImageType = getImageType())
fun save(path: String, type: ImageType = getImageType())
fun send(response: HttpServletResponse, type: ImageType = getImageType())
Better use BufferedImages.send(...)
as it doesn't buffer the whole image to determine its size.
Useful for Spring MVC controllers.
fun getImageType(): ImageType
fun isEqualTo(img: BufferedImage): Boolean
Pixel by pixel images comparison.
https://github.com/minogin/buffered-images
Please contact me at [email protected] or at GitHub