Java, 이미지 crop 과 resize by 오리대마왕

참으로 오랫만에 이미지 조작을 하려니 다 까먹었네. 기록 차원에서 남겨둔다.

이미지를 받아 (여기선 그냥 이미지 내용을 byte[] 로 받았다), 지정된 크기 이상일 경우 resize 하며 지정된 가로 세로 비율로 맞춰주는 메서드이다. 만약 가로가 길거나 세로가 길면 이미지 가운데를 기준으로 넘치는 부분을 잘라낸다.

 

public static byte[] generateImage( byte[] imageContent, int maxWidth, double xyRatio) throws IOException {

        BufferedImage originalImg = ImageIO.read( new ByteArrayInputStream(imageContent));

 

        //get the center point for crop

        int[] centerPoint = { originalImg.getWidth() /2, originalImg.getHeight() / 2 };

 

        //calculate crop area

        int cropWidth=originalImg.getWidth();

        int cropHeight=originalImg.getHeight();

 

        if( cropHeight > cropWidth * xyRatio ) {

            //long image

            cropHeight = (int) (cropWidth * xyRatio);

        } else {

            //wide image

            cropWidth = (int) ( (float) cropHeight / xyRatio) ;

        }

 

        //set target image size

        int targetWidth = cropWidth;

        int targetHeight = cropHeight;

 

        if( targetWidth > maxWidth) {

            //too big image

            targetWidth = maxWidth;

            targetHeight = (int) (targetWidth * xyRatio);

        }

 

        //processing image

        BufferedImage targetImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);

        Graphics2D graphics2D = targetImage.createGraphics();

        graphics2D.setBackground(Color.WHITE);

        graphics2D.setPaint(Color.WHITE);

        graphics2D.fillRect(0, 0, targetWidth, targetHeight);

        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

        graphics2D.drawImage(originalImg, 0, 0, targetWidth, targetHeight,   centerPoint[0] - (int)(cropWidth /2) , centerPoint[1] - (int)(cropHeight /2), centerPoint[0] + (int)(cropWidth /2), centerPoint[1] + (int)(cropHeight /2), null);

 

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        ImageIO.write(targetImage, "png", output);

 

        return output.toByteArray();

    }



사용 예)

 

public static void main(String[] args) throws IOException {

 

        String imgUrl = "http://wstatic.dcinside.com/new/interview/dc_se1.jpg";

        // width: height

        double xyRatio = 1.3;

        int maxWidth = 300;

 

        URL url = new URL(imgUrl);

 

        File f = new File("a.png");

        FileOutputStream fos = new FileOutputStream(f);

 

        fos.write(generateImage( getImageContent(url), maxWidth, xyRatio));

 

        fos.close();

 

    }

 

 

    /**

     * @param url

     * @return

     * @throws IOException

     */

    private static byte[] getImageContent(URL url) throws IOException {

        ByteArrayOutputStream bais = new ByteArrayOutputStream();

        InputStream is = null;

 

          is = url.openStream ();

          byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.

          int n;

 

          while ( (n = is.read(byteChunk)) > 0 ) {

            bais.write(byteChunk, 0, n);

          }

 

        is.close();

        return bais.toByteArray();

    }