Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

이미지 파일 업로드 시 회전 버그 해결 #367

Merged
merged 5 commits into from
Jun 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@ dependencies {
implementation 'com.navercorp.lucy:lucy-xss:1.6.3' // Lucy XSS Filter
implementation 'org.apache.commons:commons-text:1.11.0' // Apache Commons Text

// Image
implementation 'commons-io:commons-io:2.8.0'
implementation 'com.drewnoakes:metadata-extractor:2.14.0'
implementation 'org.imgscalr:imgscalr-lib:4.2'

// Test
testImplementation 'org.springframework.boot:spring-boot-starter-test' // Spring Boot Test
testImplementation 'org.springframework.security:spring-security-test' // Spring Security Test
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
package page.clab.api.global.common.file.application;

import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.MetadataException;
import com.drew.metadata.exif.ExifIFD0Directory;
import com.google.common.base.Strings;
import java.io.FileOutputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.imgscalr.Scalr;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
Expand Down Expand Up @@ -68,11 +77,75 @@ public String saveFile(MultipartFile multipartFile, String category) throws IOEx

File file = new File(savePath);
ensureParentDirectoryExists(file);
multipartFile.transferTo(file);

try {
if (isImageFile(multipartFile)) {
BufferedImage originalImage = adjustImageDirection(multipartFile);
ImageIO.write(originalImage, extension, file);
}
else {
multipartFile.transferTo(file);
}
} catch (Exception e) {
throw new IOException("이미지의 뱡향을 조정하는데 오류가 발생했습니다.", e);
}

setFilePermissions(file, savePath, extension);
return savePath;
}

private BufferedImage adjustImageDirection(MultipartFile multipartFile) throws Exception {
File tempFile = File.createTempFile("temp", null);
multipartFile.transferTo(tempFile);
int originalDirection = getImageDirection(tempFile);
BufferedImage bufferedImage = ImageIO.read(tempFile);

switch (originalDirection) {
case 1:
break;
case 3:
bufferedImage = Scalr.rotate(bufferedImage, Scalr.Rotation.CW_180, null);
break;
case 6:
bufferedImage = Scalr.rotate(bufferedImage, Scalr.Rotation.CW_90, null);
break;
case 8:
bufferedImage = Scalr.rotate(bufferedImage, Scalr.Rotation.CW_270, null);
break;
}

if (tempFile.exists() && !tempFile.delete()) {
throw new IOException("Failed to delete image file: " + tempFile.getAbsolutePath());
}

return bufferedImage;
}

public int getImageDirection(File tempFile) {
int originalDirection = 1;
try {
Metadata metadata = ImageMetadataReader.readMetadata(tempFile);
Directory directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
if (directory != null) {
originalDirection = directory.getInt(ExifIFD0Directory.TAG_ORIENTATION);
}
} catch (IOException e) {
log.error("이미지 파일을 읽는 중 IO 오류 발생: {}", e.getMessage());
} catch (ImageProcessingException e) {
log.error("이미지 파일 처리 중 오류 발생: {}", e.getMessage());
} catch (MetadataException e) {
log.error("이미지 파일의 메타데이터를 읽는 중 오류 발생: {}", e.getMessage());
} catch (Exception e) {
log.error("예기치 않은 오류 발생: {}", e.getMessage());
}
limehee marked this conversation as resolved.
Show resolved Hide resolved
return originalDirection;
}

private boolean isImageFile(MultipartFile file) {
String contentType = file.getContentType();
return contentType != null && contentType.startsWith("image/");
}

private void validateFileAttributes(String originalFilename, String extension) throws FileUploadFailException {
if (!validateFilename(originalFilename)) {
throw new FileUploadFailException("허용되지 않은 파일명 : " + originalFilename);
Expand Down
1 change: 1 addition & 0 deletions src/main/java/page/clab/api/global/config/WebConfig.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package page.clab.api.global.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package page.clab.api.global.handler;

import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.MetadataException;
import com.google.gson.stream.MalformedJsonException;
import jakarta.mail.MessagingException;
import jakarta.servlet.http.HttpServletRequest;
Expand Down Expand Up @@ -192,6 +194,8 @@ public ErrorResponse conflictException(HttpServletResponse response, Exception e
EncryptionException.class,
DecryptionException.class,
InvalidDataAccessApiUsageException.class,
ImageProcessingException.class,
MetadataException.class,
Exception.class
})
public ApiResponse serverException(HttpServletRequest request, HttpServletResponse response, Exception e) {
Expand Down