|
1 | 1 | package com.sonkim.bookmarking.common.service; |
2 | 2 |
|
| 3 | +import com.sksamuel.scrimage.ImmutableImage; |
| 4 | +import com.sksamuel.scrimage.webp.WebpWriter; |
3 | 5 | import com.sonkim.bookmarking.common.s3.service.S3Service; |
4 | 6 | import com.sonkim.bookmarking.domain.bookmark.entity.Bookmark; |
5 | 7 | import com.sonkim.bookmarking.domain.bookmark.repository.BookmarkRepository; |
|
12 | 14 | import org.springframework.transaction.event.TransactionPhase; |
13 | 15 | import org.springframework.transaction.event.TransactionalEventListener; |
14 | 16 |
|
15 | | -import java.io.InputStream; |
16 | 17 | import java.net.URL; |
17 | 18 | import java.util.Optional; |
18 | 19 |
|
@@ -42,24 +43,33 @@ public void downloadAndUploadToS3(BookmarkCreatedEvent event) { |
42 | 43 | } |
43 | 44 |
|
44 | 45 | try { |
45 | | - // S3에 업로드 후 파일 키 수령 |
46 | | - String fileKey; |
47 | | - try (InputStream in = new URL(imageUrl).openStream()) { |
48 | | - // URL에서 이미지를 byte[]로 읽어옴 |
49 | | - byte[] imageBytes = in.readAllBytes(); |
| 46 | + // 이미지 다운로드 및 로딩 |
| 47 | + ImmutableImage image = ImmutableImage.loader().fromUrl(new URL(imageUrl)); |
50 | 48 |
|
51 | | - // 파일 이름 추출 |
52 | | - String fileNameWithQuery = imageUrl.substring(imageUrl.lastIndexOf('/') + 1); |
53 | | - int queryIndex = fileNameWithQuery.indexOf('?'); |
54 | | - String originalFileName = (queryIndex != -1) ? fileNameWithQuery.substring(0, queryIndex) : fileNameWithQuery; |
| 49 | + // 리사이징 |
| 50 | + if (image.width > 600) { |
| 51 | + image = image.scaleToWidth(600); |
| 52 | + } |
| 53 | + |
| 54 | + // webP로 변환 |
| 55 | + byte[] webpImageBytes = image.bytes(WebpWriter.DEFAULT.withQ(80)); |
55 | 56 |
|
56 | | - // S3에 업로드하고 fileKey 반환 |
57 | | - fileKey = s3Service.uploadImageBytes(imageBytes, originalFileName, "bookmarks/"); |
| 57 | + // 파일 이름 생성 및 S3 업로드 |
| 58 | + String originalFileName = imageUrl.substring(imageUrl.lastIndexOf('/') + 1); |
| 59 | + int queryIndex = imageUrl.lastIndexOf('?'); |
| 60 | + if (queryIndex != -1) { |
| 61 | + originalFileName = originalFileName.substring(0, queryIndex); |
58 | 62 | } |
59 | 63 |
|
60 | | - // 해당 북마크 이미지 url 수정 |
61 | | - Optional<Bookmark> bookmarkOptional = bookmarkRepository.findById(bookmarkId); |
| 64 | + String fileNameWithoutExt = originalFileName.contains(".") |
| 65 | + ? originalFileName.substring(0, originalFileName.lastIndexOf(".")) |
| 66 | + : originalFileName; |
| 67 | + String webpFileName = fileNameWithoutExt + ".webp"; |
62 | 68 |
|
| 69 | + String fileKey = s3Service.uploadImageBytes(webpImageBytes, webpFileName, "bookmarks/"); |
| 70 | + |
| 71 | + // DB 업데이트 |
| 72 | + Optional<Bookmark> bookmarkOptional = bookmarkRepository.findById(bookmarkId); |
63 | 73 | if (bookmarkOptional.isPresent()) { |
64 | 74 | Bookmark bookmark = bookmarkOptional.get(); |
65 | 75 | bookmark.updateImageKey(fileKey); |
|
0 commit comments