browser-image-compression은 자바스크립트에서 이미지의 사이즈를 줄이거나 용량을 압축해주는 라이브러리이다.
npm install browswer-image-compression --save
import imageCompression from 'browser-image-compression';
사용할땐 간단하게 imageCompression 을 호출해주고 안에 파일과 압축옵션을 넣으면 된다.
// you should provide one of maxSizeMB, maxWidthOrHeight in the options
const options: 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)
// but, automatically reduce the size to smaller than the maximum Canvas size supported by each browser.
// Please check the Caveat part for details.
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)
}
imageCompression(file: File, options: Options): Promise<File>
리턴은 Promise와 파일
그 외에도 도움을 주는 여러 함수가 있다.
imageCompression.getDataUrlFromFile(file: File): Promise<base64 encoded string>
imageCompression.getFilefromDataUrl(dataUrl: string, filename: string, lastModified?: number): Promise<File>
imageCompression.loadImage(url: string): Promise<HTMLImageElement>
imageCompression.drawImageInCanvas(img: HTMLImageElement, fileType?: string): HTMLCanvasElement | OffscreenCanvas
imageCompression.drawFileInCanvas(file: File, options?: Options): Promise<[ImageBitmap | HTMLImageElement, HTMLCanvasElement | OffscreenCanvas]>
imageCompression.canvasToFile(canvas: HTMLCanvasElement | OffscreenCanvas, fileType: string, fileName: string, fileLastModified: number, quality?: number): Promise<File>
imageCompression.getExifOrientation(file: File): Promise<number> // based on https://stackoverflow.com/a/32490603/10395024
나는 이미지 파일을 압축하고 위에 helper function을 이용해서 base64로 변환했다.
const imageHandler = async (e) => {
// 이벤트에 있는 이미지들을 압축하고 base64로 변환해서 변수에 담는다.
const newImages = await Promise.all([...e.target.files].map(async (file) =>
imageCompression.getDataUrlFromFile(await imageCompression(file, compressOptions))));
}