[Java, Scala] Image resizing with ImageIO

Whole code

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

object ImageUtil {
  def resize(file: File): Unit = {
    val original = ImageIO.read(file)

    //Vertical and horizontal size of the original file(pixel)Get
    val originalWidth = original.getWidth.toDouble
    val originalHeight = original.getHeight.toDouble

    //Get the aspect ratio with the long side as 1
    val (widthScale, heightScale) =
      if(originalWidth > originalHeight) (1d, originalHeight / originalWidth)
      else (originalWidth / originalHeight, 1d)

    //Set the long side to 200px, maintain the aspect ratio, and determine the image size after resizing.
    val width = (200d * widthScale).toInt
    val height = (200d * heightScale).toInt

    val image = new BufferedImage(width, height, original.getType)

    val scaled = original.getScaledInstance(width, height, java.awt.Image.SCALE_AREA_AVERAGING)

    image.getGraphics.drawImage(scaled, 0, 0, width, height, null)

    ImageIO.write(image, "jpeg", new File("/tmp/resized.jpeg "))
  }
}

Rough commentary

I think that there is no problem in calculating the image size, so only the image generation part.

val image = new BufferedImage(width, height, original.getType)

The image size is determined here. An image of making a clean canvas. In the example, the image is adjusted to the size of the resized image, so the image has no margins. If you want to make a square with a margin, it looks like this.

//Make a square with the length of the long side as one side
val scale = Math.max(width, height)
val image = new BufferedImage(scale, scale, original.getType)

Next, the image data obtained by resizing the original image is acquired.

val scaled = original.getScaledInstance(width, height, java.awt.Image.SCALE_AREA_AVERAGING)

Then paste the resized image on the canvas you made first.

image.getGraphics.drawImage(scaled, 0, 0, width, height, null)

0 and 0 are the x and y coordinates of the canvas, respectively. An image to paste the image after resizing based on the specified coordinates. If there is a margin, you can adjust the coordinates to move the image to the left, right, top, bottom, or center.

Finally, output the file and finish.

ImageIO.write(image, "jpeg", new File("/tmp/resized.jpeg "))

Bonus: Change the color of the margins

If there is a margin, the color of the margin is black by default. If you want to change the color, you can paint the whole thing with your favorite color before drawImage.

//Make the margin white
image.getGraphics.setColor(Color.WHITE)

//Coordinate(0, 0)From, fill the entire height and width of the image with the specified color
image.getGraphics.fillRect(0, 0, image.getWidth, image.getHeight)

Recommended Posts

[Java, Scala] Image resizing with ImageIO
Use JDBC with Java and Scala.
Use Matplotlib from Java or Scala with Matplotlib4j
Install java with Homebrew
Run Scala with GraalVM & make it a native image
Change seats with java
Install Java with Ansible
Include image in jar file with java static method
Comfortable download with JAVA
Switch java with direnv
Download Java with Ansible
Let's scrape with Java! !!
Build Java with Wercker
Endian conversion with JAVA
Easy BDD with (Java) Spectrum?
Use Lambda Layers with Java
Java multi-project creation with Gradle
Getting Started with Java Collection
Java Config with Spring MVC
Basic Authentication with Java 11 HttpClient
Let's experiment with Java inlining
Run batch with docker-compose with Java batch
[Template] MySQL connection with Java
Rewrite Java try-catch with Optional
Install Java 7 with Homebrew (cask)
[Java] JSON communication with jackson
Java update for Scala users
Java to play with Function
Try DB connection with Java
Enable Java EE with NetBeans 9
[Java] JavaConfig with Static InnerClass
Try gRPC with Java, Maven
Let's operate Excel with Java! !!
Version control Java with SDKMAN
RSA encryption / decryption with java 8
Paging PDF with Java + PDFBox.jar
Sort strings functionally with java
Object-oriented (java) with Strike Gundam
Multi-stage selection (Java / Groovy / Scala)
[Java] Content acquisition with HttpCliient
Java version control with jenv
Troubleshooting with Java Flight Recorder
Streamline Java testing with Spock
Connect to DB with Java
Connect to MySQL 8 with Java
Error when playing with java
Using Mapper with Java (Spring)
Java study memo 2 with Progate
Getting Started with Java Basics
Post an image with POSTMAN
Seasonal display with Java switch
Use SpatiaLite with Java / JDBC
Study Java with Progate Note 1
Compare Java 8 Optional with Swift
[Introduction] Build MVC with Scala
HTML parsing with JAVA (scraping)
Run Java VM with WebAssembly
List data structure [Java / Scala]
Screen transition with swing, java
Java unit tests with Mockito