Java

Java image resize 크기 변환

심나라 2022. 7. 4. 11:28
728x90

1. Java 이미지 파일 사이즈 조절하는 예제 - 1

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

public class ImageResize {
	public static void main(String[] args) {
		
		String orgImaPath = "C:\\Users\\user\\Pictures\\01.jpg";	// 원본 이미지 파일명
		String newImgpath = "C:\\Users\\user\\Pictures\\01_copy.gif";	// 신규 이미지 파일명
		String imgFormat = "gif";										// 신규 이미지파일 포맷 (jpg, gif, png...) 
		int newImgWidth = 500;											// 신규 이미지 넓이
		int newImgHeight = 700;											// 신규 이미지 높이
		String position = "W";											// W:넓이기준, H:높이기준, X:설정한 수치로(비율무시)
		
		Image image;
		int oldImgWidth;
		int oldImgHeight;
		double ratio;
		int w;
		int h;
		
		try {
			// 원본 이미지 가져오기
			image = ImageIO.read(new File(orgImaPath));
			
			// 원본 이미지 사이즈 가져오기
			oldImgWidth  = image.getWidth(null);
			oldImgHeight = image.getHeight(null);
			
			if(position.equals("W")) {	// 넓이기준
				ratio = (double)newImgWidth/(double)oldImgWidth;
				w = (int)(oldImgWidth  * ratio);
				h = (int)(oldImgHeight * ratio);
			} else if(position.equals("H")) {	// 높이기준
				ratio = (double)newImgHeight/(double)oldImgHeight;
				w = (int)(oldImgWidth * ratio);
				h = (int)(oldImgHeight * ratio);
			} else {
				w = newImgWidth;
				h = newImgHeight;
			}
			
			// 이미지 리사이즈
			// Image.SCALE_DEFAULT : 기본 이미지 스케일링 알고리즘 사용
			// Image.SCALE_FAST	: 이미지 부드러움보다 속도 우선
			// Image.SCALE_REPLICATE : ReplicateScaleFilter 클래스로 구체화 된 이미지 크기 조절 알고리즘
			// Image.SCALE_SMOOTH : 속도보다 이미지 부드러움을 우선
			// Image.SCALE_AREA_AVERAGING : 평균 알고리즘 사용
			Image resizeImage = image.getScaledInstance(w, h, Image.SCALE_SMOOTH);
			
			// 새 이미지 저장하기
			BufferedImage newImage = new BufferedImage(w, h, BufferedImage.SCALE_SMOOTH);
			Graphics g = newImage.getGraphics();
			g.drawImage(resizeImage, 0, 0, null);
			g.dispose();
			ImageIO.write(newImage, imgFormat, new File(newImgpath));

		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}

 

2. Java 이미지 파일 사이즈 조절하는 예제 - 2

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

public class ImageUtil {

	public static final int RATIO = 0;
	public static final int SAME = -1;
	
	public static void resize(File src, File dest, int width, int height) throws IOException {
		
		Image srcImg = null;
		String suffix = src.getName().substring(src.getName().lastIndexOf(".") + 1).toLowerCase();
		if(suffix.equals("bmp") || suffix.equals("png") || suffix.equals("gif") 
				|| suffix.equals("jpeg") || suffix.equals("jpg")) {
			srcImg = ImageIO.read(src);
		} else {
			throw new IOException("지원하지 않는 확장자 입니다.");
		}
		
		int srcWidth = srcImg.getWidth(null);
		int srcHeight = srcImg.getHeight(null);
		
		int destWidth = -1;
		int destHeight = -1;
		
		if(width == SAME) {
			destWidth = srcWidth;
		} else if(width > 0) {
			destWidth = width;
		}
		if(height == SAME) {
			destHeight = srcHeight;
		} else if (height > 0) {
			destHeight = height;
		}
			
		if(width == RATIO && height == RATIO) {
			destWidth = srcWidth;
			destHeight = srcHeight;
		} else if(width == RATIO) {
			double ratio = ((double)destHeight) / ((double)srcHeight);
			destWidth = (int)((double)srcWidth * ratio);
		} else if(height == RATIO) {
			double ratio = ((double)destWidth) / ((double)srcWidth);
			destHeight = (int)((double)srcHeight * ratio);
		}
		
		Image imgTarget = srcImg.getScaledInstance(destWidth, destHeight, Image.SCALE_SMOOTH);
		int pixels[] = new int[destWidth * destHeight];
		PixelGrabber pg = new PixelGrabber(imgTarget, 0, 0, destWidth, destHeight, pixels, 0, destWidth);
		try {
			pg.grabPixels();
		} catch(InterruptedException e) {
			throw new IOException(e.getMessage());
		}
		
		// 이미지 리사이즈
		// Image.SCALE_DEFAULT : 기본 이미지 스케일링 알고리즘 사용
		// Image.SCALE_FAST	: 이미지 부드러움보다 속도 우선
		// Image.SCALE_REPLICATE : ReplicateScaleFilter 클래스로 구체화 된 이미지 크기 조절 알고리즘
		// Image.SCALE_SMOOTH : 속도보다 이미지 부드러움을 우선
		// Image.SCALE_AREA_AVERAGING : 평균 알고리즘 사용
		BufferedImage destImg = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
		destImg.setRGB(0, 0, destWidth, destHeight, pixels, 0, destWidth);
		
		// 새 이미지 저장
		ImageIO.write(destImg, suffix, dest);
	}
	
	
	public static void main(String[] args) {
		
		String orgImageFileName = "C:\\Users\\user\\Pictures\\01.jpg";		// 원본 이미지 파일명
		String newImageFileName = "C:\\Users\\user\\Pictures\\01_copy.jpg";	// 신규 이미지 파일명
		
		File src = new File(orgImageFileName);
		File dest = new File(newImageFileName);
		
		try {
			resize(src, dest, 100, 0);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}

이미지 크기 변환시 해상도가 떨어지는 경우 아래의 참고 사이트를 확인 해보자 

 

if (suffix.equals("bmp") || suffix.equals("png") || suffix.equals("gif")) {
    srcImg = ImageIO.read(src);
} else {
    // JPG, JPEG 인경우 ImageIcon을 활용해서 Image 생성
    // 이렇게 하는 이유는 getScaledInstance를 통해 구한 이미지를
    // PixelGrabber.grabPixels로 리사이즈 할때
    // 빠르게 처리하기 위함이다.
    srcImg = new ImageIcon(src.toURL()).getImage();
}

 

참고링크

728x90