Java program to resize a photo into a square with margins

Introduction

What I wanted to do

――When posting a photo to Instagram, I want to make it a square with a margin --Large images are recompressed on the server side, so I want to resize them. --The smartphone app is annoying because I wanted to edit it on my PC before posting. ――It seems to be in an existing desktop application, but I also made it for studying

environment

code

What can you do

--Resize image within 1080 * 1350 with aspect ratio maintained --1080 * 1080 Fit in a square and add a margin (white or black) (optional) --If you don't need a margin, f -- w for white margins, b for black margins --If you give options and original image directory on the command line, output as PNG --If it is a folder, all the image files in it will be targeted. --Output is in the same directory as the original image, prefixed with resized_

Full text

image-resizer.java


package main;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.AreaAveragingScaleFilter;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.imageio.ImageIO;


import javafx.application.Application;
import javafx.stage.Stage;

public class Main extends Application {

	public static boolean makeSquare = true;;
	
	public static ArrayList<File> dirFiles = new ArrayList<File>();
	public static BufferedImage inputImage;
	public static double maxWidth = 1080;
	public static double maxHeight = 1350;
	
	public static int outputWidth;
	public static int outputHeight;

	public static int[] startCoodinate = {0, 0};
	public static Color background;
	
	public static String outputPreffix = "resized_";
	public static File output;
	public static String extension = "png";
	public static List<String> readble = Arrays.asList("jpeg", "jpg", "gif", "png", "bmp");
	
	
	public static void main(String[] args) {
		launch(args);
	}

	@Override
	public void start(Stage primaryStage) throws Exception {
        Parameters params = getParameters();
		List<String> args = params.getRaw();
		
		switch(args.get(0)) {
		case "f":
			makeSquare = false;
			break;
		case "w":
			background = Color.white;
			break;
		case "b":
			background = Color.black;
			break;
		default:
			System.out.println("Input 'f', 'w' or 'b' as 1st argument.");
			System.exit(0);
		}
		
		if (args.size() > 1) {
			for (int i = 1; i < args.size(); i++) {
				System.out.println("Processing " + args.get(i) + ".");
				if (checkDirectory(args.get(i))) {
					for (File f: dirFiles) {
						System.out.println("Processing " + f.getName() + ".");
						initialize(f);
						scaleImage(inputImage, output, outputWidth, outputHeight);
					}
					dirFiles.clear();
				} else {
					try {
						initialize(new File(args.get(i)));
						scaleImage(inputImage, output, outputWidth, outputHeight);
					} catch (Exception e){
						System.out.println(new File(args.get(i)).getName() + " could not be loaded.");
					}
				}
			}
			System.exit(0);
		} else {
			System.out.println("Input file or directory name as 2nd and later arguments.");
			System.exit(0);
		}
	}
	
	public static void initialize(File input) throws Exception {
		inputImage = ImageIO.read(input);
	    calculateSize(inputImage);
	        
	    String fileNameWithoutExtension = input.getName().substring(0, input.getName().lastIndexOf(".") + 1);
	    output = new File(input.getParent(), outputPreffix + fileNameWithoutExtension + extension);
	}
	
	public static void calculateSize(BufferedImage org) {
		if (makeSquare) {
			maxHeight = maxWidth;
		}
		double scale = Math.min(maxWidth / org.getWidth(), maxHeight / org.getHeight());
		outputWidth = (int)(org.getWidth() * scale);
		outputHeight = (int)(org.getHeight() * scale);
		if (makeSquare) {
			startCoodinate[0] = (int)Math.max(0, (maxWidth - outputWidth) / 2);
			startCoodinate[1] = (int)Math.max(0, (maxHeight - outputHeight) / 2);
		}
	}
	
	public static boolean checkDirectory(String dir) {
		File inputDir = new File(dir);
		if(inputDir.isDirectory()) {
			for (File f: inputDir.listFiles()) {
				if (readble.contains(f.getName().substring(f.getName().lastIndexOf(".") + 1).toLowerCase())) {
					dirFiles.add(f);
				} else {
					System.out.println(f.getName() + " was skipped. Only JPG, GIF, PNG, BMP are supported.");
				}
			}
		}
		return inputDir.isDirectory();
	}
	
	public static void scaleImage(BufferedImage org, File out, int width, int height){
        try {
            ImageFilter filter = new AreaAveragingScaleFilter(width, height);
            ImageProducer p = new FilteredImageSource(org.getSource(), filter);
            Image dstImage = Toolkit.getDefaultToolkit().createImage(p);
            
            if (makeSquare) {
            	outputWidth = (int)maxWidth;
            	outputHeight = (int)maxHeight;
            }
            BufferedImage dst = new BufferedImage((int)outputWidth , (int)outputHeight, BufferedImage.TYPE_INT_ARGB);
        	Graphics2D g = dst.createGraphics();
        	g.setColor(background);
        	g.fillRect(0, 0, dst.getWidth(), dst.getHeight());
            g.drawImage(dstImage, Math.max(0, startCoodinate[0]), Math.max(0, startCoodinate[1]), null);
            g.dispose();
			ImageIO.write(dst, extension, out);
			System.out.println(out.getName() + " was successed.");
		} catch (IOException e) {
			System.out.println(out.getName() + " could not be written.");
		}
    }

}

For ease of use

--Easy to use the following batch file on Windows machines --More specifically, it is easier to put cmd / c" C: \ * \ image-resizer.bat " in the taskbar.

image-resizer.bat


@echo off
setlocal
set /p dir="Target file or folder (multiple can be specified): "
set /p makeSqare="Would you like to add a margin to make it square?(y/n): "
if %makeSqare%==y (
    set /p firstAug="Margin color is white or black(w/b): "
)
if %makeSqare%==n (
    set firstAug=f
)
echo Starts processing
java -jar image-resizer.jar %firstAug% %dir%
echo The resized PNG is saved in the same folder as the original image
pause

reference

Comment from saka1029 of Image Resize --Qiita

Recommended Posts

Java program to resize a photo into a square with margins
[Introduction to Java] How to write a Java program
[Photo Organizer] [java] [windows] Move selected photos to a folder with 2 clicks
Try debugging a Java program with VS Code
I tried to break a block with java (1)
Until you run a Java program with the AWS SDK local to Windows
Submit a job to AWS Batch with Java (Eclipse)
Export pdf with a single program (Java / Perl / VBA)
Try building Java into a native module with GraalVM
[Java] How to start a new line with StringBuilder
I tried to create a java8 development environment with Chocolatey
I tried to modernize a Java EE application with OpenShift.
Java to play with Function
How to divide a two-dimensional array into four with ruby
[Beginner] Try to make a simple RPG game with Java ①
[Beginner] I made a program to sell cakes in Java
I want to make a list with kotlin and java!
I want to make a function with kotlin and java!
Connect to DB with Java
Connect to MySQL 8 with Java
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
To write a user-oriented program (1)
A memo to start Java programming with VS Code (2020-04 version)
How to reduce the load on the program even a little when combining characters with JAVA
How to register as a customer with Square using Tomcat
How to deal with the type that I thought about writing a Java program for 2 years
A story that I struggled to challenge a competition professional with Java
Try to speed up Java console program startup with GraalVM native-image
Connecting to a database with Java (Part 1) Maybe the basic method
Replace with a value according to the match with a Java regular expression
Build a Java project with Gradle
Java to learn with ramen [Part 1]
[Java] Points to note with Arrays.asList ()
How to make a Java container
Dare to challenge Kaggle with Java (1)
I tried to interact with Java
[Java] How to create a folder
Java, arrays to start with beginners
How to make a Java array
A standalone Java app that sends logs to CloudWatch Logs with slf4j / logback
[Personal memo] How to interact with a random number generator in Java
[Java] How to turn a two-dimensional array with an extended for statement
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (PowerMockito edition)
I want to create a dark web SNS with Jakarta EE 8 with Java 11
Create a program to post to Slack with GO and make it a container
Hanashi stumbled a little on path trying to study Java with VScode
I want to ForEach an array with a Lambda expression in Java
How to SSH into Ubuntu from a terminal with public key authentication
How to make an app with a plugin mechanism [C # and Java]
I tried to make a program that searches for the target class from the process that is overloaded with Java
How to make a Java calendar Summary
How to compile Java with VsCode & Ant
[Java] How to compare with equals method
Introduction to algorithms with java --Search (depth-first search)
A program that calculates factorials from 2 to 100
[Java] How to measure program execution time
How to make a Discord bot (Java)
How to print a Java Word document
Split a string with ". (Dot)" in Java
Deserialize XML into a collection with spring-boot
Easy to trip with Java regular expressions