Images

suggest change

Kotlin on the JVM uses the image APIs from the JDK. You don't need a library to read, create, edit and save images:

This article covers:

On Android these classes don't exist. Android uses android.graphics.Bitmap, BitmapFactory and Canvas instead.

Creating an image and drawing on it

import java.awt.BasicStroke
import java.awt.Color
import java.awt.Font
import java.awt.RenderingHints
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO

fun main() {
    val img = BufferedImage(400, 200, BufferedImage.TYPE_INT_ARGB)
    val g = img.createGraphics()
    try {
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON)

        g.color = Color(0xF0F4FF)
        g.fillRect(0, 0, img.width, img.height)

        g.color = Color(0x3366CC)
        g.fillOval(20, 20, 160, 160)

        g.color = Color.RED
        g.stroke = BasicStroke(6f)
        g.drawLine(200, 30, 380, 170)

        g.color = Color(0, 0, 0, 128) // 50% transparent black
        g.fillRoundRect(220, 120, 150, 50, 20, 20)

        g.color = Color.WHITE
        g.font = Font(Font.SANS_SERIF, Font.BOLD, 24)
        g.drawString("Kotlin", 250, 153)
    } finally {
        g.dispose()
    }

    val out = File("drawing.png")
    val ok = ImageIO.write(img, "png", out)
    println("written=$ok size=${out.length() > 0} ${img.width}x${img.height}")
}

Output:

written=true size=true 400x200

The resulting drawing.png is a 400x200 image with a blue circle, a red line and a semi-transparent label with the text "Kotlin". The other examples in this article read it.

Reading images

import java.io.File
import javax.imageio.ImageIO

fun main() {
    println("read:  " + ImageIO.getReaderFormatNames().map { it.lowercase() }.distinct().sorted())
    println("write: " + ImageIO.getWriterFormatNames().map { it.lowercase() }.distinct().sorted())

    val img = ImageIO.read(File("drawing.png"))
        ?: error("not a supported image")
    println("${img.width}x${img.height} type=${img.type} alpha=${img.colorModel.hasAlpha()}")

    val notImage = File("notes.txt").apply { writeText("hello") }
    println("text file: ${ImageIO.read(notImage)}")
}

Output:

read:  [bmp, gif, jpeg, jpg, png, tif, tiff, wbmp]
write: [bmp, gif, jpeg, jpg, png, tif, tiff, wbmp]
400x200 type=6 alpha=true
text file: null

Pixels

getRGB(x, y) returns a pixel as an ARGB Int: alpha in the top 8 bits, then red, green and blue. Extension functions make the bit manipulation readable:

import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO

fun Int.alpha() = (this ushr 24) and 0xFF
fun Int.red() = (this shr 16) and 0xFF
fun Int.green() = (this shr 8) and 0xFF
fun Int.blue() = this and 0xFF
fun argb(a: Int, r: Int, g: Int, b: Int) = (a shl 24) or (r shl 16) or (g shl 8) or b

fun main() {
    val img = ImageIO.read(File("drawing.png"))

    val p = img.getRGB(100, 100) // inside the blue circle
    println("pixel=%08X a=%d r=%d g=%d b=%d".format(p, p.alpha(), p.red(), p.green(), p.blue()))

    // Grayscale, pixel by pixel
    val gray = BufferedImage(img.width, img.height, BufferedImage.TYPE_INT_ARGB)
    for (y in 0 until img.height) {
        for (x in 0 until img.width) {
            val c = img.getRGB(x, y)
            val l = (0.299 * c.red() + 0.587 * c.green() + 0.114 * c.blue()).toInt()
            gray.setRGB(x, y, argb(c.alpha(), l, l, l))
        }
    }
    ImageIO.write(gray, "png", File("gray.png"))
    println("gray pixel=%08X".format(gray.getRGB(100, 100)))

    // Bulk access: one call reads the whole image into an IntArray
    val w = img.width
    val h = img.height
    val pixels = img.getRGB(0, 0, w, h, null, 0, w)
    for (i in pixels.indices) {
        val c = pixels[i]
        pixels[i] = argb(c.alpha(), 255 - c.red(), 255 - c.green(), 255 - c.blue())
    }
    val inverted = BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB)
    inverted.setRGB(0, 0, w, h, pixels, 0, w)
    ImageIO.write(inverted, "png", File("inverted.png"))
    println("inverted pixel=%08X".format(inverted.getRGB(100, 100)))

    // Count colors
    val counts = img.getRGB(0, 0, w, h, null, 0, w).toList().groupingBy { it }.eachCount()
    println("distinct colors: ${counts.size}")
    counts.entries.sortedByDescending { it.value }.take(3).forEach { (c, n) ->
        println("  %08X  %d pixels".format(c, n))
    }
}

Output:

pixel=FF3366CC a=255 r=51 g=102 b=204
gray pixel=FF626262
inverted pixel=FFCC9933
distinct colors: 245
  FFF0F4FF  50971 pixels
  FF3366CC  19788 pixels
  FF787A7F  6333 pixels

Resizing, rotating and flipping

import java.awt.RenderingHints
import java.awt.geom.AffineTransform
import java.awt.image.AffineTransformOp
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
import kotlin.math.roundToInt

fun BufferedImage.resized(w: Int, h: Int): BufferedImage {
    val type = if (colorModel.hasAlpha()) BufferedImage.TYPE_INT_ARGB else BufferedImage.TYPE_INT_RGB
    val out = BufferedImage(w, h, type)
    val g = out.createGraphics()
    try {
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC)
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)
        g.drawImage(this, 0, 0, w, h, null)
    } finally {
        g.dispose()
    }
    return out
}

// Fit inside maxW x maxH, keep aspect ratio, never upscale
fun BufferedImage.thumbnail(maxW: Int, maxH: Int): BufferedImage {
    val scale = minOf(maxW.toDouble() / width, maxH.toDouble() / height, 1.0)
    val w = (width * scale).roundToInt().coerceAtLeast(1)
    val h = (height * scale).roundToInt().coerceAtLeast(1)
    return resized(w, h)
}

fun BufferedImage.rotated90(): BufferedImage {
    val out = BufferedImage(height, width, BufferedImage.TYPE_INT_ARGB)
    val g = out.createGraphics()
    try {
        g.translate(height, 0)
        g.rotate(Math.PI / 2)
        g.drawImage(this, 0, 0, null)
    } finally {
        g.dispose()
    }
    return out
}

fun BufferedImage.flippedHorizontally(): BufferedImage {
    val tx = AffineTransform.getScaleInstance(-1.0, 1.0)
    tx.translate(-width.toDouble(), 0.0)
    return AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR).filter(this, null)
}

fun main() {
    val img = ImageIO.read(File("drawing.png"))

    val thumb = img.thumbnail(150, 150)
    println("thumbnail: ${thumb.width}x${thumb.height}")
    ImageIO.write(thumb, "png", File("thumb.png"))

    val small = img.thumbnail(1000, 1000)
    println("no upscale: ${small.width}x${small.height}")

    val r = img.rotated90()
    println("rotated: ${r.width}x${r.height}")
    ImageIO.write(r, "png", File("rotated.png"))

    val f = img.flippedHorizontally()
    println("flipped: ${f.width}x${f.height} %08X -> %08X"
        .format(img.getRGB(30, 100), f.getRGB(f.width - 1 - 30, 100)))
    ImageIO.write(f, "png", File("flipped.png"))
}

Output:

thumbnail: 150x75
no upscale: 400x200
rotated: 200x400
flipped: 400x200 FF3366CC -> FF3366CC

Cropping

import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO

fun main() {
    val img = ImageIO.read(File("drawing.png"))

    // Crop: getSubimage shares pixels with the original
    val view = img.getSubimage(20, 20, 160, 160)
    println("crop: ${view.width}x${view.height}")
    view.setRGB(0, 0, 0xFFFF0000.toInt())
    println("original changed: %08X".format(img.getRGB(20, 20)))

    // Independent copy of a region
    val copy = BufferedImage(160, 160, BufferedImage.TYPE_INT_ARGB)
    copy.createGraphics().apply { drawImage(img.getSubimage(20, 20, 160, 160), 0, 0, null); dispose() }
    copy.setRGB(1, 1, 0xFF00FF00.toInt())
    println("original unchanged: %08X".format(img.getRGB(21, 21)))
}

Output:

crop: 160x160
original changed: FFFF0000
original unchanged: FFF0F4FF

getSubimage() doesn't copy pixels. The result is a view that shares memory with the original, so changing it changes the original, and the original can't be garbage collected while the view exists. Draw the subimage onto a new BufferedImage when you need an independent copy.

JPEG, quality and transparency

import java.awt.Color
import java.awt.image.BufferedImage
import java.io.ByteArrayOutputStream
import java.io.File
import javax.imageio.IIOImage
import javax.imageio.ImageIO
import javax.imageio.ImageWriteParam

fun writeJpeg(img: BufferedImage, file: File, quality: Float) {
    val writer = ImageIO.getImageWritersByFormatName("jpeg").next()
    val params = writer.defaultWriteParam.apply {
        compressionMode = ImageWriteParam.MODE_EXPLICIT
        compressionQuality = quality // 0.0 (smallest) .. 1.0 (best)
    }
    ImageIO.createImageOutputStream(file).use { out ->
        writer.output = out
        writer.write(null, IIOImage(img, null, null), params)
    }
    writer.dispose()
}

// JPEG has no alpha channel: paint the image onto an opaque background first
fun BufferedImage.toRgb(background: Color = Color.WHITE): BufferedImage {
    if (!colorModel.hasAlpha()) return this
    val out = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
    val g = out.createGraphics()
    try {
        g.color = background
        g.fillRect(0, 0, width, height)
        g.drawImage(this, 0, 0, null)
    } finally {
        g.dispose()
    }
    return out
}

fun main() {
    val img = ImageIO.read(File("drawing.png"))

    val ok = ImageIO.write(img, "jpg", File("direct.jpg"))
    println("write ARGB as jpg: $ok")

    val rgb = img.toRgb()
    println("write RGB as jpg: ${ImageIO.write(rgb, "jpg", File("default.jpg"))}, ${File("default.jpg").length() > 0}")

    for (q in listOf(0.2f, 0.5f, 0.9f, 1.0f)) {
        val f = File("q$q.jpg")
        writeJpeg(rgb, f, q)
        println("quality $q -> ${f.length()} bytes")
    }
    println("png -> ${File("drawing.png").length()} bytes")

    // Encode to bytes in memory, e.g. for an HTTP response
    val bytes = ByteArrayOutputStream().use { bos ->
        ImageIO.write(img, "png", bos)
        bos.toByteArray()
    }
    println("png in memory: ${bytes.size} bytes, header=${bytes.take(4).joinToString(" ") { "%02X".format(it) }}")
    val back = ImageIO.read(bytes.inputStream())
    println("decoded back: ${back.width}x${back.height}")
}

Output:

write ARGB as jpg: false
write RGB as jpg: true, true
quality 0.2 -> 3739 bytes
quality 0.5 -> 5113 bytes
quality 0.9 -> 9415 bytes
quality 1.0 -> 19852 bytes
png -> 5835 bytes
png in memory: 5835 bytes, header=89 50 4E 47
decoded back: 400x200

Image size without decoding

Decoding a large photo takes a lot of memory: a 6000x4000 image needs 96 MB as TYPE_INT_ARGB. To check the size or format of an upload, read only the header with an ImageReader:

import java.io.File
import javax.imageio.ImageIO

data class ImageInfo(val format: String, val width: Int, val height: Int)

// Reads only the header, does not decode the pixels
fun imageInfo(file: File): ImageInfo? {
    ImageIO.createImageInputStream(file).use { input ->
        if (input == null) return null
        val readers = ImageIO.getImageReaders(input)
        if (!readers.hasNext()) return null
        val reader = readers.next()
        try {
            reader.input = input
            return ImageInfo(reader.formatName.lowercase(), reader.getWidth(0), reader.getHeight(0))
        } finally {
            reader.dispose()
        }
    }
}

fun main() {
    for (name in listOf("drawing.png", "q0.9.jpg", "thumb.png", "rotated.png", "notes.txt", "missing.png")) {
        val f = File(name)
        val info = if (f.exists()) imageInfo(f) else null
        println("%-12s %s".format(name, info ?: "not an image"))
    }
}

Output:

drawing.png  ImageInfo(format=png, width=400, height=200)
q0.9.jpg     ImageInfo(format=jpeg, width=400, height=200)
thumb.png    ImageInfo(format=png, width=150, height=75)
rotated.png  ImageInfo(format=png, width=200, height=400)
notes.txt    not an image
missing.png  not an image

The format is detected from the content, not the file extension. Use this to reject uploads that are too big before calling ImageIO.read(): a small, highly compressed file can declare huge dimensions and exhaust memory when decoded (a "decompression bomb").

Watermarks and semi-transparent drawing

AlphaComposite controls how drawn pixels blend with the pixels already in the image. FontMetrics measures text so you can position it:

import java.awt.AlphaComposite
import java.awt.Color
import java.awt.Font
import java.awt.GraphicsEnvironment
import java.awt.RenderingHints
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO

fun BufferedImage.withWatermark(text: String, logo: BufferedImage): BufferedImage {
    val out = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB)
    val g = out.createGraphics()
    try {
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON)
        g.drawImage(this, 0, 0, null)

        // Logo in the bottom-right corner at 40% opacity
        g.composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f)
        g.drawImage(logo, width - logo.width - 10, height - logo.height - 10, null)

        // Text centered horizontally and vertically
        g.composite = AlphaComposite.SrcOver
        g.font = Font(Font.SANS_SERIF, Font.BOLD, 32)
        g.color = Color(255, 255, 255, 180)
        val fm = g.fontMetrics
        val x = (width - fm.stringWidth(text)) / 2
        val y = (height - fm.height) / 2 + fm.ascent
        g.drawString(text, x, y)
        println("text box: width=${fm.stringWidth(text)} height=${fm.height} at ($x, $y)")
    } finally {
        g.dispose()
    }
    return out
}

fun main() {
    println("headless: ${GraphicsEnvironment.isHeadless()}")
    val img = ImageIO.read(File("drawing.png"))
    val logo = BufferedImage(48, 48, BufferedImage.TYPE_INT_ARGB).apply {
        createGraphics().apply {
            color = Color.ORANGE
            fillOval(0, 0, 48, 48)
            dispose()
        }
    }
    val marked = img.withWatermark("SAMPLE", logo)
    ImageIO.write(marked, "png", File("watermarked.png"))
    println("logo pixel: %08X".format(marked.getRGB(400 - 10 - 24, 200 - 10 - 24)))
}

Output (the text size depends on the fonts installed on the system):

headless: true
text box: width=132 height=42 at (134, 112)
logo pixel: FFAE994C

Running on a server

The example above was run with java -Djava.awt.headless=true -jar app.jar. Headless mode tells AWT that there is no display, keyboard or mouse. BufferedImage, Graphics2D and ImageIO work fine in headless mode, while creating windows throws HeadlessException.

On Linux servers and in Docker containers without a display the JDK switches to headless mode automatically, but setting the property explicitly avoids surprises. Drawing text needs fonts: slim images like Alpine may have none installed, which causes errors as soon as you call drawString or getFontMetrics. Install fontconfig and a font package such as ttf-dejavu in the image.

Different threads can process different images at the same time, but a single BufferedImage or Graphics2D must not be used from several threads at once. Image processing is CPU-bound, so run it on Dispatchers.Default when you use coroutines, see Dispatchers and threads.

WebP and other formats

The JDK can't read WebP, so ImageIO.read() returns null for .webp files. TwelveMonkeys is a set of ImageIO plugins that add formats. Plugins register themselves through the service loader, so you only add the dependency and keep using ImageIO:

// build.gradle.kts
dependencies {
    implementation("com.twelvemonkeys.imageio:imageio-webp:3.15.3")
}
import java.io.File
import javax.imageio.ImageIO

fun main() {
    println("webp readable: ${"webp" in ImageIO.getReaderFormatNames()}")
    val img = ImageIO.read(File("photo.webp"))
    println("${img.width}x${img.height}")
    ImageIO.write(img, "png", File("from-webp.png"))
}

Output without the dependency:

webp readable: false
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.awt.image.BufferedImage.getWidth()" because "img" is null

Output with the dependency:

webp readable: true
400x200

Summary

Task Use
New image BufferedImage(w, h, TYPE_INT_ARGB)
Draw shapes and text createGraphics(), then dispose()
Read a file ImageIO.read(file), returns null for unknown formats
Write a file ImageIO.write(img, "png", file), check the Boolean result
Read and write pixels getRGB / setRGB, bulk versions for speed
Resize drawImage(img, 0, 0, w, h, null) with bicubic interpolation
Crop getSubimage() (shares pixels)
Rotate and flip Graphics2D.rotate(), AffineTransformOp
JPEG quality ImageWriter with ImageWriteParam
Size without decoding ImageReader.getWidth(0) / getHeight(0)
Semi-transparent drawing AlphaComposite
WebP, PSD, ICO TwelveMonkeys ImageIO plugins

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents