본문 바로가기
Back-end/JAVA & Spring

[JAVA] image resize & crop (Thumbnail)

by 꼬바리 2021. 11. 23.

Java 라이브러리를 활용해서 이미지 리사이징 및 크롭하는 것을 소개합니다.

참고로 크롭은 특정 좌표(x,y)부터 원하는 크기(width,height)로 자르는 것을 의미합니다.

 

환경 : jdk 1.6

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import javax.imageio.ImageIO;



public class EasyImage {
    private BufferedImage buffer;

    public EasyImage(File file) throws IOException {
        buffer = ImageIO.read(file);
    }

    public EasyImage(URL url) throws IOException {
        buffer = ImageIO.read(url);
    }

    public EasyImage(InputStream stream) throws IOException {
        buffer = ImageIO.read(stream);
    }

    public EasyImage(BufferedImage buffer) {
        this.buffer = buffer;
    }

    public int getWidth() {
        return buffer.getWidth();
    }

    public int getHeight() {
        return buffer.getHeight();
    }

    public EasyImage resize(int width, int height) {
        BufferedImage dest = new BufferedImage(width, height,
            BufferedImage.TYPE_INT_RGB);
        Graphics2D g = dest.createGraphics();
        g.setComposite(AlphaComposite.Src);
        g.drawImage(buffer, 0, 0, width, height, null);
        g.dispose();
        return new EasyImage(dest);
    }

    public EasyImage resize(int width) {
        int resizedHeight = (width * buffer.getHeight()) / buffer.getWidth();
        return resize(width, resizedHeight);
    }

    public EasyImage crop(int x, int y, int width, int height) {
        BufferedImage dest = new BufferedImage(width, height,
            BufferedImage.TYPE_INT_RGB);
        Graphics2D g = dest.createGraphics();
        g.setComposite(AlphaComposite.Src);
        g.drawImage(buffer, 0, 0, width, height, x, y, x + width, y + height,
            null);
        g.dispose();
        return new EasyImage(dest);
    }

    public void writeTo(OutputStream stream, String formatName)
            throws IOException {
        ImageIO.write(buffer, formatName, stream);
    }

    public boolean isSuppoprtedImageFormat() {
        return buffer != null ? true : false;
    }
}

 

 

사용예)

File f = new File("xxxxx.jpg");

EasyImage easyImage = new EasyImage(f);

if (!easyImage.isSuppoprtedImageFormat()) {

    System.out.println("not supported image type");
    return;

}

/* resize */

EasyImage resizedImage = easyImage.resize(80,80);
FileOutputStream out = new FileOutputStream(f);
resizedImage.writeTo(out, "png"); //resizedImage.writeTo(out, "jpg");

/* crop */

// EasyImage cropedImage = easyImage.crop(x,y,w,h);
// FileOutputStream out = new FileOutputStream(f);
// cropedImage.writeTo(out, "png"); //cropedImage.writeTo(out, "jpg");
728x90
반응형

댓글