[java] 자동 이미지 크기 조절

이미지를 동적으로 크기를 조절하는 것은 웹 페이지나 애플리케이션에서 매우 유용합니다. 자바를 사용하여 자동으로 이미지 크기를 조절하는 방법을 알아봅시다.

1. BufferedImage를 사용하여 이미지 로드

이미지 크기를 조절하기 위해 먼저 BufferedImage 클래스를 사용하여 이미지를 로드해야 합니다. 아래는 이미지를 로드하는 간단한 예제입니다.

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

public class ImageResize {
    public static void main(String[] args) throws IOException {
        File input = new File("input.jpg");
        BufferedImage image = ImageIO.read(input);
    }
}

2. 이미지 크기 조절

BufferedImage를 사용하여 이미지 크기를 조절할 수 있습니다. 아래는 이미지의 가로, 세로 크기를 반으로 줄이는 예제입니다.

int newWidth = image.getWidth() / 2;
int newHeight = image.getHeight() / 2;

BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, image.getType());
Graphics2D g = resizedImage.createGraphics();
g.drawImage(image, 0, 0, newWidth, newHeight, null);
g.dispose();

3. 이미지 저장

크기가 조절된 이미지를 파일로 저장할 수 있습니다.

File output = new File("output.jpg");
ImageIO.write(resizedImage, "jpg", output);

4. 전체 코드

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageResize {
    public static void main(String[] args) throws IOException {
        File input = new File("input.jpg");
        BufferedImage image = ImageIO.read(input);

        int newWidth = image.getWidth() / 2;
        int newHeight = image.getHeight() / 2;

        BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, image.getType());
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(image, 0, 0, newWidth, newHeight, null);
        g.dispose();

        File output = new File("output.jpg");
        ImageIO.write(resizedImage, "jpg", output);
    }
}

이제 자바를 사용하여 이미지의 크기를 조절하는 방법을 알게 되었습니다. 여기서는 이미지를 반으로 줄였지만, 원하는 크기로 자유롭게 조절할 수 있습니다.