티스토리 뷰

728x90
반응형

 

 

자르고 싶은 이미지가 있고, 아래처럼 빨간색 박스친 곳만 이미지를 저장하고 싶을 때!

이미지에서 원하는 부분만 잘라내어 새 이미지로 저장하고 싶을 때 사용하는 방법!!

 

 

BufferedImage.getSubimage 로 구현할 수 있는데,

getSubimage에 들어가는 파라미터에 대해서 알아봅시다!!

 

*int* *x* - the X coordinate of the upper-left corner of the specified rectangular region
*int* *y* - the Y coordinate of the upper-left corner of the specified rectangular region
*int* *w* - the width of the specified rectangular region
*int* *h* - the height of the specified rectangular region

 

x, y, w, h가  getSubimage의 파라미터로 사용되고,

x는 자르고자 하는 이미지의 좌측 모서리 x 좌표,

y는 자르고자 하는 이미지의 좌측 모서리 y좌표,

w는 그 이미지의 가로 길이,

h는 그 이미지의 세로 길이네요!!

 

 

https://www.demo2s.com/java/java-bufferedimage-getsubimage-int-x-int-y-int-w-int-h.html

 

 

따라서 w, h에 기존이미지(1920X1080)의 width와 height를 벗어나는 값을 넣으면

outside Raster라는 오류가 뜨게 됩니다!!!

자르고싶은 이미지의 w, h를 정확히 알고 있으면 값을 그대로 넣어주면 되지만,

아래 빨간박스처럼 위쪽부분만 정하고, w, h는 이미지와 동일하게 설정하고 싶다면 w에는 ( 1920 - x ) 값을, h에는 ( 1080 - y ) 값을 넣어주면 되겠죠 !!

 

 

만약 w에 1920, h에 1080을 넣으면 자르려는 이미지(빨간박스)가 기존이미지(검정박스)를 벗어나기 때문에 에러가 발생하게 되는 것이죠.

 

 

 

getSubimage에 대해서 더 자세한 설명을 보려면 아래 링크를 눌러주세요 ~!

https://www.demo2s.com/java/java-bufferedimage-getsubimage-int-x-int-y-int-w-int-h.html

 

Java BufferedImage getSubimage(int x, int y, int w, int h)

Java BufferedImage getSubimage(int x, int y, int w, int h) PreviousNext Java BufferedImage getSubimage(int x, int y, int w, int h) Returns a subimage defined by a specified rectangular region. Introduction Returns a subimage defined by a specified rectangu

www.demo2s.com

 

 

이제 이미지 자르기를 도전해봅시다!!

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

// 1. 자르려하는 이미지를 불러옵니다.
BufferedImage buff = ImageIO.read(new File(file));

// 2. 자르려하는 영역을 설정하여 이미지를 자르면 끝!
BufferedImage new_buff = buff.getSubimage(minX, minY, (maxX-minX), (maxY-minY));

 

 

 

끝입니다~!

 

 

 

 

728x90
반응형
댓글