net.dankito.utils.image.JavaImageUtils.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-utils Show documentation
Show all versions of java-utils Show documentation
Some basic utils needed in many projects
The newest version!
package net.dankito.utils.image
import com.drew.imaging.ImageMetadataReader
import com.drew.metadata.MetadataException
import com.drew.metadata.exif.ExifIFD0Directory
import org.slf4j.LoggerFactory
import java.io.File
import java.io.IOException
open class JavaImageUtils : IImageUtils {
companion object {
private val log = LoggerFactory.getLogger(JavaImageUtils::class.java)
}
@Throws(IOException::class)
override fun getImageOrientationInDegree(imagePath: String): Int {
return getImageOrientationInDegree(toFile(imagePath))
}
@Throws(IOException::class)
override fun getImageOrientationInDegree(imagePath: File): Int {
when (getImageOrientation(imagePath)) {
ImageOrientation.RotatedBy90Deg -> return 90
ImageOrientation.RotatedBy180Deg -> return 180
ImageOrientation.RotatedBy270Deg -> return 270
else -> return 0
}
}
@Throws(IOException::class)
override fun getImageOrientation(imagePath: String): ImageOrientation {
return getImageOrientation(toFile(imagePath))
}
@Throws(IOException::class)
override fun getImageOrientation(imagePath: File): ImageOrientation {
val exifOrientation = getExifOrientation(imagePath)
return mapExifOrientation(exifOrientation)
}
protected open fun getExifOrientation(imagePath: File): Int {
val metadata = ImageMetadataReader.readMetadata(imagePath)
try {
metadata.getFirstDirectoryOfType(ExifIFD0Directory::class.java)?.let { directory ->
return directory.getInt(ExifIFD0Directory.TAG_ORIENTATION)
}
} catch (e: MetadataException) {
log.warn("Could not get image orientation for $imagePath", e)
}
return 1 // = orientation normal
}
protected open fun mapExifOrientation(exifOrientation: Int): ImageOrientation {
when (exifOrientation) {
6 -> return ImageOrientation.RotatedBy90Deg
3 -> return ImageOrientation.RotatedBy180Deg
8 -> return ImageOrientation.RotatedBy270Deg
2 -> return ImageOrientation.FlippedHorizontally
4 -> return ImageOrientation.FlippedVertically
else -> return ImageOrientation.Normal
}
}
protected open fun toFile(imagePath: String): File {
return File(imagePath);
}
}