diff --git a/web/lib/firebase/storage.ts b/web/lib/firebase/storage.ts index 4918a99c..fcf4422d 100644 --- a/web/lib/firebase/storage.ts +++ b/web/lib/firebase/storage.ts @@ -1,8 +1,8 @@ import { ref, uploadBytesResumable, getDownloadURL } from 'firebase/storage' +import imageCompression from 'browser-image-compression' import { nanoid } from 'nanoid' import { storage } from './init' -// TODO: compress large images export const uploadImage = async ( username: string, file: File, @@ -12,6 +12,18 @@ export const uploadImage = async ( const [, ext] = file.name.split('.') const filename = `${nanoid(10)}.${ext}` const storageRef = ref(storage, `user-images/${username}/${filename}`) + + if (file.size > 20 * 1024 ** 2) { + return Promise.reject('File is over 20 MB.') + } + + if (file.size > 1024 ** 2) { + file = await imageCompression(file, { + maxSizeMB: 1, + maxWidthOrHeight: 1920, + }) + } + const uploadTask = uploadBytesResumable(storageRef, file) let resolvePromise: (url: string) => void diff --git a/web/package.json b/web/package.json index a31dbffa..4fba3359 100644 --- a/web/package.json +++ b/web/package.json @@ -34,6 +34,7 @@ "@tiptap/react": "2.0.0-beta.114", "@tiptap/starter-kit": "2.0.0-beta.190", "algoliasearch": "4.13.0", + "browser-image-compression": "2.0.0", "clsx": "1.1.1", "cors": "2.8.5", "daisyui": "1.16.4", diff --git a/yarn.lock b/yarn.lock index dea9e29b..9334b737 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4270,6 +4270,13 @@ broadcast-channel@^3.4.1: rimraf "3.0.2" unload "2.2.0" +browser-image-compression@2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/browser-image-compression/-/browser-image-compression-2.0.0.tgz#f421381a76d474d4da7dcd82810daf595b09bef6" + integrity sha512-kBlkZo13yOOfcmrPW0M0K/UdZPogIQj2gRvXIM3FktAnfW6VRq9aY2RI+F6O0x6DMj1Xm+WLGgWcFK8Fu/ddnw== + dependencies: + uzip "0.20201231.0" + browserslist@^4.0.0, browserslist@^4.14.5, browserslist@^4.16.6, browserslist@^4.18.1, browserslist@^4.20.2, browserslist@^4.20.3: version "4.20.3" resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.20.3.tgz#eb7572f49ec430e054f56d52ff0ebe9be915f8bf" @@ -11630,6 +11637,11 @@ uuid@^8.0.0, uuid@^8.3.2: resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.2.tgz#80d5b5ced271bb9af6c445f21a1a04c606cefbe2" integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg== +uzip@0.20201231.0: + version "0.20201231.0" + resolved "https://registry.yarnpkg.com/uzip/-/uzip-0.20201231.0.tgz#9e64b065b9a8ebf26eb7583fe8e77e1d9a15ed14" + integrity sha512-OZeJfZP+R0z9D6TmBgLq2LHzSSptGMGDGigGiEe0pr8UBe/7fdflgHlHBNDASTXB5jnFuxHpNaJywSg8YFeGng== + v8-compile-cache-lib@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz#6336e8d71965cb3d35a1bbb7868445a7c05264bf"