개발/스프링

21. 스프링 프레임 워크 - 썸네일 이미지[자바 웹을 다루는 기술]

괴발자-K 2022. 5. 30. 11:12

쇼핑몰 등 에서 이미지를 나타날 때 썸네일 이미지를 사용하는 경우가 있습니다.

이미지의 개수가 많아 원본이지의 경우는 표시할 경우 오랜 시간이 걸릴 수 있습니다. 

그래서 썸네일을 이용해서 목록에 축소된 이미지를 등록하여 신속하게 나타 낼 수 있습니다.

 

pom.xml

<!-- 썸네일 이미지  -->
    <dependency>
       <groupId>net.coobird</groupId>
       <artifactId>thumbnailator</artifactId>
       <version>0.4.8</version>
    </dependency>

썸네일 라이브러리를 추가

 

FileDownController.java

package com.myspring.pro28.ex02;

..........

@Controller
public class FileDownloadController {
    
	//파일 저장 위치를 지정
	private static String CURR_IMAGE_REPO_PATH = "c:\\spring\\image_repo";
	
	
	//다운로드할 이미 파일 이름을 전달
	@RequestMapping("/download")
	protected void download(@RequestParam("imageFileName") String imageFileName,
			                 HttpServletResponse response) throws Exception{
		OutputStream out = response.getOutputStream();
		String filePath = CURR_IMAGE_REPO_PATH + "\\" + imageFileName;
		//다운로드한 파일 객체를 생성
		File image = new File(filePath);
		int lastIndex = imageFileName.lastIndexOf(".");
		String fileName = imageFileName.substring(0,lastIndex);
		//원본 이미지 파일 이름과 같은 이름의 썸네일 파일에 대한 File 객체를 생성
		File thumbnail = new File(CURR_IMAGE_REPO_PATH+"\\"+"thumnail"+"\\"+fileName+".png");
		
		//원본 이미지 파일을 가로세로가 50픽셀인 png형식의 썸네일 이미지 파일로 생성
		if(image.exists()) {
			thumbnail.getParentFile().mkdirs();
			Thumbnails.of(image).size(50, 50).outputFormat("png").toFile(thumbnail);
		}

		
		//생성된 썸네일 파일을 브라우저로 전송
		FileInputStream in = new FileInputStream(thumbnail);
		byte[] buffer = new byte[1024 * 8];
		
		//버퍼를 이용해 한 번에 8kbyte씩 브라우저에 전송
		while(true) {
			int count = in.read(buffer);
			if(count == -1) break;
			out.write(buffer,0,count);
		}
		in.close();
		out.close();
	
	}
}

이미지 가로세로 크기를 조정한 png 썸네일을 생성한 후 파일로 저장하는 구문 입니다.

 

/form으로 요청 시 선택한 이미지를 업로드 했을 때 원본 이미지 파일이 아닌, 가로 세로 크기를 조정한 썸네일 

이미지로 업로드가 되어 브라우저에 바로 출력이 됩니다.

그리고 썸네일 이미지 파일을 따로 생성되지 않습니다.