테스트 사이트 - 개발 중인 베타 버전입니다

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

· 1년 전 · 853 · 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개

1년 전

감사합니다 ^^

감사합니다.

게시글 목록

번호 제목
23798
23797
23792
23791
23785
23781
23770
23766
23764
23761
23747
23732
23724
23718
23706
23700
23697
23686
23682
23681
23680
23678
23665
23644
23643
23639
23637
23630
23626
23616