com.jtransc.imaging.ImagePropsDecoder.kt Maven / Gradle / Ivy
package com.jtransc.imaging
import com.jtransc.io.indexOf
import com.jtransc.io.readUpToBytes
import com.jtransc.util.open
import com.jtransc.util.toIntOrNull2
import java.io.ByteArrayInputStream
import java.io.File
import java.io.InputStream
data class ImageInfo(
var width: Int = 0,
var height: Int = 0,
var bitsPerPixel: Int = 0
)
interface ImagePropsDecoder {
fun tryDecodeHeader(s: InputStream): ImageInfo?
companion object {
val decoders = listOf(
PNGImagePropsDecoder,
JPEGImagePropsDecoder,
SVGImagePropsDecoder,
GIFImagePropsDecoder
)
fun tryDecodeHeader(file: File): ImageInfo? {
return tryDecodeHeader(file.readBytes())
}
fun tryDecodeHeader(data: ByteArray): ImageInfo? {
for (decoder in decoders) {
try {
val res = decoder.tryDecodeHeader(ByteArrayInputStream(data)) ?: continue
return res
} catch (e: Throwable) {
e.printStackTrace()
}
}
return null
}
}
}
object GIFImagePropsDecoder : ImagePropsDecoder {
override fun tryDecodeHeader(s: InputStream): ImageInfo? {
val header = s.readUpToBytes(0x10).open()
val magic = header.readStringz(6, Charsets.UTF_8)
if (!magic.startsWith("GIF")) return null
val width = header.readU16_LE()
val height = header.readU16_LE()
return ImageInfo(width, height, bitsPerPixel = 8)
}
}
object SVGImagePropsDecoder : ImagePropsDecoder {
val svgStartParser = Regex("