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

feat: 이미지 업로드 압축 #267

Merged
merged 6 commits into from
Nov 4, 2023
Merged
Show file tree
Hide file tree
Changes from 5 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
26 changes: 26 additions & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"@tanstack/react-query": "^4.36.1",
"@tanstack/react-query-devtools": "^4.36.1",
"axios": "^1.5.0",
"compressorjs": "^1.2.1",
"framer-motion": "^10.16.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
Expand Down
6 changes: 5 additions & 1 deletion src/admins/components/Form/ImageDropzone.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { useState } from "react";
import { v4 as uuidv4 } from "uuid";

import { useApi } from "@/hooks/useApi";
import { fileToWebPFile } from "@/libs/compressor";

/** 5MB */
const MAX_SIZE_BYTES = 5 * 1024 * 1024;
Expand Down Expand Up @@ -33,14 +34,17 @@ export default function ImageDropzone({
try {
setIsLoading(true);

const webPFile = await fileToWebPFile(file);

const path = await fileApi.uploadImage({
path: uploadPath,
filename: uuidv4(),
file,
file: webPFile,
});

if (path) onUpload(path);
} catch (e) {
console.error(e);
notifications.show({
message: "이미지를 올리는데 실패했어요. 다시 시도해보세요",
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import styled from "@emotion/styled";

export const HeaderTop = styled.div`
display: flex;
justify-content: space-between;
width: 100%;
`;

export const HeaderBottom = styled.div`
display: flex;
flex-direction: column;
margin-top: 0.5rem;
width: 100%;
`;
80 changes: 55 additions & 25 deletions src/admins/features/animes/components/EditVoiceActorsModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import useCreateVoiceActor from "../hooks/useCreateVoiceActor";
import useVoiceActors from "../hooks/useVoiceActors";

import CreateSubCategoryButton from "./CreateSubCategoryButton";
import { HeaderBottom, HeaderTop } from "./EditVoiceActorsModal.style";

interface SelectedActor {
id: number;
Expand All @@ -37,10 +38,11 @@ export default function EditVoiceActorsModal({
const [selectedActors, setSelectedActors] = useState<SelectedActor[]>(
selectedActorsInitial,
);
const [searchKeyword, setSearchKeyword] = useState("");

useEffect(() => {
setSelectedActors(selectedActorsInitial);
}, []);
}, [selectedActorsInitial]);

const handleCheckboxChange = (
actorId: number,
Expand Down Expand Up @@ -74,6 +76,12 @@ export default function EditVoiceActorsModal({
onAdd(actorsToAdd);
};

const filteredVoiceActors = searchKeyword
? voiceActors?.filter((actor) =>
actor.name.toLowerCase().includes(searchKeyword.toLowerCase()),
)
: voiceActors;

if (isLoadingActors)
return (
<Modal title="성우 관리" size="xl" opened onClose={onClose}>
Expand All @@ -83,7 +91,7 @@ export default function EditVoiceActorsModal({
</Modal>
);

const rows = voiceActors?.map((actor) => {
const rows = filteredVoiceActors?.map((actor) => {
const selectedActor = selectedActors.find((item) => item.id === actor.id);

return (
Expand Down Expand Up @@ -117,28 +125,50 @@ export default function EditVoiceActorsModal({
});

return (
<Modal title="성우 관리" size="xl" opened onClose={onClose}>
<Table.ScrollContainer minWidth={500} type="native">
<Table>
<Table.Thead>
<Table.Tr>
<Table.Th>ID</Table.Th>
<Table.Th>이름</Table.Th>
<Table.Th>선택</Table.Th>
<Table.Th>배역</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>{rows}</Table.Tbody>
</Table>
</Table.ScrollContainer>
<Flex justify="flex-end" gap="sm">
<CreateSubCategoryButton
label="+ 새 성우"
modalTitle="새 성우 등록"
onCreate={(name) => createVoiceActorMutation.mutate(name)}
/>
<Button onClick={handleSubmit}>확인</Button>
</Flex>
</Modal>
<Modal.Root size="xl" opened onClose={onClose}>
<Modal.Overlay />
<Modal.Content>
<Modal.Header style={{ flexDirection: "column" }}>
<HeaderTop>
<Modal.Title>성우 관리</Modal.Title>
<Modal.CloseButton />
</HeaderTop>
<HeaderBottom>
<div>
<TextInput
placeholder="성우 이름 검색"
onChange={(event) =>
setSearchKeyword(event.currentTarget.value)
}
mb="md"
/>
</div>
<Flex justify="flex-end" gap="sm">
<CreateSubCategoryButton
label="+ 새 성우"
modalTitle="새 성우 등록"
onCreate={(name) => createVoiceActorMutation.mutate(name)}
/>
<Button onClick={handleSubmit}>확인</Button>
</Flex>
</HeaderBottom>
</Modal.Header>
<Modal.Body>
<Table.ScrollContainer minWidth={500} type="native">
<Table>
<Table.Thead>
<Table.Tr>
<Table.Th>ID</Table.Th>
<Table.Th>이름</Table.Th>
<Table.Th>선택</Table.Th>
<Table.Th>배역</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>{rows}</Table.Tbody>
</Table>
</Table.ScrollContainer>
</Modal.Body>
</Modal.Content>
</Modal.Root>
);
}
31 changes: 31 additions & 0 deletions src/libs/compressor/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import Compressor from "compressorjs";

/**
* 파일을 webP 포멧으로 변환합니다
* @param {File} file - 이미지 파일
* @param {number} quality - 변환후 이미지 품질 `기본 0.8` `0 ~ 8 사이 값`
* @returns {Promise<File>}
*/
export async function fileToWebPFile(
file: File,
quality: number = 0.8,
): Promise<File> {
return new Promise((resolve, reject) => {
new Compressor(file, {
quality,
mimeType: "image/webp",
maxWidth: 880,
height: 620,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

만약 크기가 1200x800 이미지를 넣으면 880x620로 변환되는건가요??

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

엇 height는 무조건 고정으로 들어가겠네요
max로 할경우 변환돼요

height

The height of the output image. If not specified, the natural height of the original image will be used, or if the width option is set, the height will be computed automatically by the natural aspect ratio.
출력 이미지의 높이입니다. 지정하지 않으면 원본 이미지의 자연 높이가 사용되거나 너비 옵션이 설정된 경우 자연 종횡비에 따라 높이가 자동으로 계산됩니다.

success(result) {
const webPFile = new File([result], file.name, {
type: "image/webp",
});
resolve(webPFile);
},
error(err: Error) {
console.error(err.message);
reject(err);
},
});
});
}