L

이미지 서버 업로드전 썸네일작성

· 2024-10-21 (월) 12:20:25 · 4065 · 2

트래픽 감소를 위한 프론트에서 업로드 전 썸네일 작성로직입니다.

실제 사용은 이것 + 서버단의 썸네일 로직과 병행하여 사용하고 있습니다.

 

작동로직 순서

1. 업로드 전 이미지 파일(바이너리)를 프론트에서 읽는다

2. 읽은파일의 넓이를 계산하여 설정 넓이(인자 width)보다 넓은경우

3. base64를 이용하여 canvas로 그린후

4. 다시 base64를 파일로 변환하여 리턴한다.

 

사용시예시 입니다.

    let file_tmp = file[0].files[0];

    if(!thumb_width) thumb_width = 1920;

    switch( file_tmp.type){

        case 'image/png':

        case 'image/jpg':

        case 'image/jpeg':

            thumbnail(file_tmp, thumb_width, function(file_tmp){

                      //업로드 로직 작성

            }

   }

 

 

function thumbnail(file_tmp, thumb_width, callback) {

    var img = new Image();

    var reader = new FileReader();

    reader.readAsDataURL(file_tmp);

    reader.onload = function () {

        img.onload = function() {

            var width = img.width,

                height = img.height,

                canvas = document.createElement('canvas'),

                ctx = canvas.getContext("2d");

            let return_file;

            canvas.width = thumb_width;

            canvas.height = (this.height / this.width) * thumb_width;

 

            if(this.width <= thumb_width) return_file = file_tmp;

            else {

                ctx.drawImage(

                img,

                width > height ? (width - height) / 2 : 0,

                height > width ? (height - width) / 2 : 0,

                width > height ? height : width,

                width > height ? height : width,

                0, 0,

                canvas.width, canvas.height

                );

                return_file = base642file(canvas.toDataURL(), file_tmp)

            }

            callback( return_file );

        };

        img.src = reader.result;

    };

   

 

};

 

function base642file(img, org_file){

    // 파일 형식으로 변환

    const byteCharacters = atob(img.split(',')[1]);

    const byteNumbers = new Array(byteCharacters.length);

    for (let i = 0; i < byteCharacters.length; i++) {

        byteNumbers[i] = byteCharacters.charCodeAt(i);

    }

    const byteArray = new Uint8Array(byteNumbers);

    const blob = new Blob([byteArray], { type: org_file.type });

    const file = new File([blob], org_file.name, { type: org_file.type });

    return file;

}


 

 

|

댓글 2개

2024-10-22 (화) 08:36:16

감사합니다 ^^

감사합니다.

댓글을 작성하시려면 로그인이 필요합니다.

그누보드5 팁자료실

2,788건
+
제목 글쓴이 날짜 조회
24-10-22 조회 4,376
24-10-21 조회 4,066
24-10-20 조회 4,414
24-10-17 조회 4,795
24-10-15 조회 3,661
24-10-14 조회 3,725
24-10-14 조회 3,353
24-10-13 조회 3,724
24-10-11 조회 3,954
24-10-09 조회 3,923
24-10-08 조회 3,884
24-10-07 조회 4,193
24-10-07 조회 3,635
24-10-07 조회 4,230
24-10-07 조회 6,414
24-10-02 조회 4,381
24-10-01 조회 3,706
24-10-01 조회 3,959
24-09-30 조회 4,185
24-09-28 조회 3,906
24-09-26 조회 3,999
24-09-25 조회 3,961
24-09-24 조회 3,361
24-09-21 조회 3,835
24-09-19 조회 4,570
24-09-09 조회 3,872
24-09-04 조회 3,726
24-09-04 조회 4,127
24-08-31 조회 4,040
24-08-31 조회 4,008