본문 바로가기 메뉴 바로가기

대표이미지

[java] 이미지 로테이트 BufferedImage / Graphic2D

2021. 4. 19.
public static void RotationImage(String filepath, String filename, int rotate_val){
File orgFile = new File(filepath, filename);
BufferedImage cnvtImg ;
  try {
    if(orgFile.exists()){
      String suffix = orgFile.getName().substring(orgFile.getName().lastIndexOf('.') + 1).toLowerCase();
      String org_filename = orgFile.getName();
      if (suffix.equals("bmp") || suffix.equals("png") || suffix.equals("gif") || suffix.equals("jpg")  || suffix.equals("jpeg")) {

        cnvtImg = ImageIO.read(orgFile);
        int orgWidth = cnvtImg.getWidth();
        int orgHeight = cnvtImg.getHeight();

        BufferedImage rotatedImage = null;

        if(180 == rotate_val){
        	rotatedImage = new BufferedImage(orgWidth, orgHeight, getRGBType(org_filename)); 
        }else{
        	rotatedImage = new BufferedImage(orgHeight, orgWidth, getRGBType(org_filename)); 
        }

        Graphics2D graphics = (Graphics2D) rotatedImage.getGraphics();

        graphics.rotate(Math.toRadians(rotate_val), rotatedImage.getWidth()/2, rotatedImage.getHeight()/2);

        if( 180 != rotate_val){
        	graphics.translate((rotatedImage.getWidth() - orgWidth) /2, (rotatedImage.getHeight() - orgHeight) /2);
        }

        graphics.drawImage(cnvtImg, 0, 0, orgWidth, orgHeight, null);

        if(org_filename.indexOf(".jpg")!=-1||org_filename.indexOf(".jpeg")!=-1){
        	ImageIO.write(rotatedImage, "jpg", new FileOutputStream(new File(filepath, filename)));
        }else if(org_filename.indexOf(".png")!=-1){
        	ImageIO.write(rotatedImage, "png", new FileOutputStream(new File(filepath, filename)));
        }else if(org_filename.indexOf(".bmp")!=-1){
        	ImageIO.write(rotatedImage, "jpg", new FileOutputStream(new File(filepath, filename)));
        }else if(org_filename.indexOf(".gif")!=-1){
        	ImageIO.write(rotatedImage, "png", new FileOutputStream(new File(filepath, filename)));
        }else{
        	ImageIO.write(rotatedImage, "jpg", new FileOutputStream(new File(filepath, filename)));
        }
      }
    }
  } catch (Exception e) {
  	e.printStackTrace();
  }
}

public static int getRGBType(String thumb){
  int int_type = 0;
  	if(thumb.indexOf(".png")!=-1||thumb.indexOf(".gif")!=-1){ // 배경색이 투명인 경우가 있으므로 (transparent)
  	int_type = BufferedImage.TYPE_INT_ARGB;
  }else{
  	int_type = BufferedImage.TYPE_INT_RGB;
  }
  return int_type;
}
댓글 갯수
TOP