이미지 리사이징(browser-image-compression)

니나노개발생활·2021년 8월 3일
0

💡ah-ha

목록 보기
32/51
post-thumbnail

사실 처음에는 굳이 리사이징이 필요한가? 라고 생각했다.
화면에 보여주는 사이즈만 fix해주면 크게 상관없지않나? 라는 멍청한 생각이였다.
리사이징을 하는 이유는 뷰에 그려주는 문제가 아니라 해당 이미지가 로드될 때의 성능을 위해서였는데..
생각해보면 용량이 클수록 클라이언트에 뿌려주는 시간이 길테도 그럼 유저는 불편함을 느낄테고 이를 줄여주는 것을 생각했다면 리사이징이 바로 떠올랐을텐데 정말 1차원적인 생각이였다..ㅠㅠ
구글링해보니 aws의 lambda도 많이 나오던데 파일 업로드 전 미리보기에서부터 리사이징된 파일을 띄워 로딩 시간을 줄이고 싶어서 패키지를 사용해보았다.

browser-image-compression github

사용 방법

  • 설치
yarn add browser-image-compression
  • 임포트
import imageCompression from "browser-image-compression";
  • 코드
    프로젝트에서는 preview도 있고 업로드 부분도 있기 때문에 아래 코드는 preview 부분!
    (때문에 options를 함수 밖으로 빼준 것!)
//const options = { 
  //maxSizeMB: number,          // (default: Number.POSITIVE_INFINITY)
  //maxWidthOrHeight: number,   // compressedFile will scale down by ratio to a point that width or height is smaller than maxWidthOrHeight (default: undefined)
  //onProgress: Function,       // optional, a function takes one progress argument (percentage from 0 to 100) 
  //useWebWorker: boolean,      // optional, use multi-thread web worker, fallback to run in main-thread (default: true)

  // following options are for advanced users
  //maxIteration: number,       // optional, max number of iteration to compress the image (default: 10)
  //exifOrientation: number,    // optional, see https://stackoverflow.com/a/32490603/10395024
  //fileType: string,           // optional, fileType override
  //initialQuality: number      // optional, initial quality value between 0 and 1 (default: 1)
//}

const options = {
    maxSizeMB: 1,
    maxWidthOrHeight: 1920,
    useWebWorker: true
  }
//+ input(type=file)의 onChange 함수
const chgPreview = async (e) => {
  //원본
  const imageFile = e.target.files[0];
  console.log('originalFile instanceof Blob', imageFile instanceof Blob); // true
  console.log(`originalFile size ${imageFile.size / 1024 / 1024} MB`);
  //리사이징
  try {
    const compressedFile = await imageCompression(imageFile, options);
    console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true
    console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`);
    
    const imageUrl = URL.createObjectURL(compressedFile);
    setFileUrl(imageUrl)
  } catch (error) {
    window.alert('앗, 이미지 업로드에 오류가 있어요! 관리자에게 문의해주세요😿')
  }
}

☝🏻 위 코드의 콘솔을 보면

  • 1-2번째 줄 : 원본
    3-4번째 줄 : 리사이징 파일
  • 이렇게 파일의 크기 확인이 가능하다!
profile
깃헙으로 이사중..

0개의 댓글