[Java / Kotlin] Resize considering the orientation of the image

Overview

--When you create an image with the iPhone camera, the orientation of the image is saved in EXIF orientation. --EXIF can be confirmed with imagemagic's ʻidentify` command.

$ identify -verbose IMG_1046.png | grep Orient
  Orientation: TopLeft

--EXIF needs to be considered when resizing the image. --I use a library because it is difficult to implement by myself.

Library to use

Implementation

build.gradle


dependencies {
    ...
    implementation "com.sksamuel.scrimage:scrimage-core:4.0.4"
    ...
}

ImageResizer.kt


object ImageResizer {
    enum class ImageFormat {
        JPEG,
        PNG;

        companion object {
            fun fromName(formatName: String): ImageFormat? {
                return when (formatName) {
                    "jpg", "jpeg" -> JPEG
                    "png" -> PNG
                    else -> null
                }
            }
        }
    }

    /**
     *Long side[size]And resize
     *
     *The long side is[size]If it is smaller than, do not resize
     */
    fun resize(inputStream: InputStream, size: Int, formatName: String): File {
        //Read the original file
        val original = ImmutableImage.loader().fromStream(inputStream)
        val originalWidth = original.width.toDouble()
        val originalHeight = original.height.toDouble()

        if (originalWidth <= size && originalHeight <= size) {
            //If the long side is smaller than size, do not resize
            return createImageTempFile(original, formatName)
        }

        val resizedWidth: Double
        val resizedHeight: Double
        if (originalWidth > originalHeight) {
            resizedWidth = size.toDouble()
            resizedHeight = size * originalHeight / originalWidth
        } else {
            resizedHeight = size.toDouble()
            resizedWidth = size * originalWidth / originalHeight
        }

        val resized = original.fit(resizedWidth.roundToInt(), resizedHeight.roundToInt())
        return createImageTempFile(resized, formatName)
    }

    private fun createImageTempFile(image: ImmutableImage, formatName: String): File {
        val format = ImageFormat.fromName(formatName)
            ?: throw BadRequestException("The image format $formatName is not supported ")
        val outFile = createTempFile(suffix = ".$formatName")
        when (format) {
            ImageFormat.JPEG -> image.output(JpegWriter(), outFile)
            ImageFormat.PNG -> image.output(PngWriter(), outFile)
        }
        return outFile
    }
}

This will create a resized image with the correct orientation (EXIF orientation will be lost from the resized image)

Remarks

--Thumbnailator is famous as a Java thumbnail creation library, but it didn't seem to consider EXIF orientation. - https://github.com/coobird/thumbnailator/issues/108

reference

Recommended Posts

[Java / Kotlin] Resize considering the orientation of the image
Please note the division (division) of java kotlin Int and Int
The illusion of object orientation
[Java] Delete the elements of List
[Java version] The story of serialization
Generics of Kotlin for Java developers
The origin of Java lambda expressions
Display text on top of the image
Get the result of POST in Java
About the version of Docker's Node.js image
Check the contents of the Java certificate store
Examine the memory usage of Java elements
[Java] Get the day of the specific day of the week
Memo: [Java] Check the contents of the directory
About the classification and concept of Immutable / Mutable / Const / Variable of Java and Kotlin.
Compare the elements of an array (Java)
[day: 5] I summarized the basics of Java
What are the updated features of java 13
Easily measure the size of Java Objects
Looking back on the basics of Java
Output of the book "Introduction to Java"
The story of writing Java in Emacs
[Java] Check the number of occurrences of characters
[Java] [Spring] Test the behavior of the logger
[Java] Get MimeType from the contents of the file with Apathce Tika [Kotlin]
Let's refer to C ++ in the module of AndroidStudio other project (Java / kotlin)
The story of low-level string comparison in Java
[Java] Handling of JavaBeans in the method chain
JAVA: jar, aar, view the contents of the file
The story of making ordinary Othello in Java
[Android] [Java] Manage the state of CheckBox of ListView
About the description order of Java system properties
The order of Java method modifiers is fixed
[Java] Access the signed URL of s3 (signed version 2)
The story of learning Java in the first programming
Measure the size of a folder in Java
[Java] Get the length of the surrogate pair string
[Java] The confusing part of String and StringBuilder
[Note] Java: Measures the speed of string concatenation
I compared the characteristics of Java and .NET
[Java] Be careful of the key type of Map
Feel the passage of time even in Java
Calculate the similarity score of strings with JAVA
Try similar search of Image Search using Java SDK [Search]
Try the free version of Progate [Java II]
I touched on the new features of Java 15
The date time of java8 has been updated
Change the location folder of Docker image & container
[Java] How to get the authority of the folder
Import files of the same hierarchy in Java
First touch of the Files class (or Java 8)
Java Welcome to the Swamp of 2D Arrays
Try the free version of Progate [Java I]
[Java] Overview of Java
[Java] How to get the URL of the transition source
Get the URL of the HTTP redirect destination in Java
[Read Effective Java] Chapter 3 Item 12 "Considering Implementation of Comparable"
How to write Scala from the perspective of Java
The comparison of enums is ==, and equals is good [Java]
[Java] Check the JDK version of the built war file
[For beginners] Quickly understand the basics of Java 8 Lambda