[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;
}
'JAVA' 카테고리의 다른 글
[spring] context-security.xml의 /spring_security_login 비활성화 (0) | 2022.07.07 |
---|---|
[java] getter / setter 예제 (0) | 2021.07.21 |
[jar] JAVA - metadata-extractor-master 변형 (0) | 2021.02.09 |
[JAVA] (CORS)교차 출처 리소스 공유 - response 처리 (0) | 2021.01.29 |
[Spring] ResponseBody 값 반환 (0) | 2021.01.29 |