Skip to content

Commit

Permalink
<create>UploadImage.js에 아바타 S3 업로드 테스트까지 완료
Browse files Browse the repository at this point in the history
  • Loading branch information
ongheong committed Feb 26, 2024
1 parent 336cc69 commit ba5f686
Show file tree
Hide file tree
Showing 7 changed files with 125 additions and 109 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"@testing-library/jest-dom": "^6.1.4",
"@testing-library/react": "^14.1.2",
"@testing-library/user-event": "^14.5.1",
"axios": "^1.6.7",
"polished": "^4.2.2",
"react": "^18.2.0",
"react-cookie": "^6.1.1",
Expand Down
36 changes: 36 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

42 changes: 25 additions & 17 deletions test_siwon/AvatarTest.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {} from './puTest.js';
// import { v4 as uuidv4 } from 'uuid';
import { getPresignedURL } from './UploadImage.js';

//--------------------------------이미지 그리는 함수들-------------------------------------//

//이미지 그리는 함수
function combineImages(imageObjects, scale) {
// 이미지 로드를 위한 프로미스 생성
var loadPromises = imageObjects.map((imgObj) => {
Expand Down Expand Up @@ -39,6 +39,8 @@ function applyOffsets(baseX, baseY, objects, offsetsMap) {
});
}

//--------------------------------이미지 그릴 때 필요한 변수들-------------------------------------//

const BASE_X = 50;
const BASE_Y = 50;
const scale = 6;
Expand All @@ -48,6 +50,7 @@ let ctx = canvas.getContext("2d");

//버튼에 대한 변수들
const exportButton = document.querySelector('#export');
const uploadImageButton = document.querySelector('#upload-image');
const hairChangeButton = document.querySelector('#hair-change');
const hairColorChangeButton = document.querySelector('#hair-color-change');
const eyeColorChangeButton = document.querySelector('#eye-color-change');
Expand Down Expand Up @@ -89,23 +92,31 @@ let imageObjects = [
{ type: 'hair', src: "change_color/Hair/Hair_1_9.png"}
]

//함수 호출하여 캔버스에 그리는 코드
combineImages(applyOffsets(BASE_X, BASE_Y, imageObjects, offsets), scale)


//버튼 이벤트 리스너들
//-------------------------------버튼 이벤트 리스너들--------------------------------------------//

exportButton.addEventListener('click', () => {
// 캔버스 내용을 이미지로 변환
// const exportImg = canvas.toDataURL();
// //다운로드를 위한 a 태그 생성
// const link = document.createElement('a');
// link.href = exportImg;
// link.download = 'avatar-image.png';
// link.click();
const exportImg = canvas.toDataURL("image/png"); // 캔버스 내용을 PNG 이미지로 변환
setImageUrl(exportImg);
puTest(exportImg); // 변환된 이미지 데이터를 puTest 함수에 전달
//캔버스 내용을 이미지로 변환
const exportImg = canvas.toDataURL();
//다운로드를 위한 a 태그 생성
const link = document.createElement('a');
link.href = exportImg;
link.download = 'avatar-image.png';
link.click();
});

//버튼 이벤트 리스너들
uploadImageButton.addEventListener('click', () => {
const exportImg = canvas.toDataURL("image/png");
// 캔버스 내용을 PNG 이미지로 변환 --> 이미지의 Base64로 인코딩된 문자열을 얻음

getPresignedURL(exportImg); // 변환된 이미지 데이터를 getPresignedURL 함수에 전달
});


hairChangeButton.addEventListener('click', () => {
imageObjects.forEach(function(obj) {
if (obj.type === 'hair')
Expand Down Expand Up @@ -197,6 +208,3 @@ clothPantChangeButton.addEventListener('click', () => {
});
});

const myButton = document.getElementById('puCheck');
myButton.addEventListener('click', putest);

13 changes: 0 additions & 13 deletions test_siwon/ColorChange.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,8 @@
from itertools import product

# 파일 경로 배열 (idx, Hair_{idx}.png)
# file_paths = [f"Hair_{i}.png" for i in range(1, 10)]
file_paths = [f"Hair_{i}" for i in range(1, 5)]


# 적용할 색상 배열
# colors = ["#FFF5C3", "#4E342E", "#FFC0CB", "#0000FF",
# "#FF0000", "#008000", "#FFFF00", "#800080"]
colors = {
"1" : "#FFFFFF",
"2" : "#FF0000",
Expand All @@ -32,11 +27,6 @@
image = Image.open(f"default/hair/{file_path_idx}.png").convert("RGBA")
r, g, b, alpha = image.split()

# # 이미지 크기 조정
# scaled_image = image.resize((250, 200))

# 회색조로 변환
# gray_image = ImageOps.grayscale(scaled_image)
gray_image = ImageOps.grayscale(image)

# 지정된 색상으로 색조 적용
Expand All @@ -49,9 +39,6 @@
# 색상 변경된 이미지 표시
#final_image.show()

# result/Hair_{i}_{color}.png 형식으로 저장
# colored_image.save(f"Hair_{file_path_idx}_{color}.png")

final_image.save(f"change_color/Hair/{file_path_idx}_{key}.png")


Expand Down
60 changes: 60 additions & 0 deletions test_siwon/UploadImage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
//Blob 객체로 변환
function base64ToBlob(base64, mimeType) {
const byteCharacters = atob(base64);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
return new Blob([byteArray], {type: mimeType});
}

function getPresignedURL(base64Img) {
let uuid = self.crypto.randomUUID();
const base64ImgValue = base64Img.replace(/^data:image\/(png|jpg);base64,/, "");
const blob = base64ToBlob(base64ImgValue, 'image/png');
console.log(blob);

const formData = new FormData();
const fileName = {
"imageUrl": `logo-images/${uuid}/logo.png`
}
formData.append("avatarImage", blob, fileName);

const url = "http://localhost/api/v1/images/presigned-url";

axios
.post(url, fileName, {
headers: {
'accept': '*/*',
"Content-Type": "application/json",
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjIzMTM1ODk1NTcsImlhdCI6MTcwODc4OTU1Nywicm9sZXMiOlsiUk9MRV9VU0VSIl0sIm1lbWJlcklkIjoxfQ.Eh-HoCbCCGEMltKsGX03UqGwUecj2WWkSR-GmtDNKBU'
},
})
.then((res) => {
const presignedUrl = res.data;
uploadImageToS3(presignedUrl, blob)
})
.catch((err) => {
console.log(err);
})
}

async function uploadImageToS3(presignedUrl, data) {
console.log("presignedURL is ", presignedUrl);
console.log("data is ", data);
const response = await axios.put(presignedUrl, data, {
headers: {
"Content-Type": "image/png"
}
}).then(response => {
// 처리 성공
console.log(response);
})
.catch(error => {
// 오류 처리
console.log(error);
});
}

export { getPresignedURL };
77 changes: 0 additions & 77 deletions test_siwon/puTest.js

This file was deleted.

5 changes: 3 additions & 2 deletions test_siwon/test.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,18 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<title>AvatarTest</title>
</head>
<body>
<canvas id="avatarCanvas" width="300" height="300"></canvas>
<button id="export">아바타 내보내기</button>
<button id="export">아바타 이미지 다운로드</button>
<button id="upload-image">아바타 이미지 업로드</button>
<button id="hair-change">머리 바꾸기</button>
<button id="hair-color-change">머리 색 바꾸기</button>
<button id="eye-color-change">눈 색 바꾸기</button>
<button id="cloth-top-change">상의 바꾸기</button>
<button id="cloth-pant-change">하의 바꾸기</button>
<button id="puCheck">puCheck</button>
<script type="module" src="AvatarTest.js"></script>
</body>
</html>

0 comments on commit ba5f686

Please sign in to comment.