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 "))
}
}
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 "))
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