npm i react-image-file-resizer
설치
import Resizer from 'react-image-file-resizer'
const resizeImage = async (file, maxWidth, maxHeight, quality) => {
return new Promise((resolve, reject) => {
Resizer.imageFileResizer(
file,
maxWidth,
maxHeight,
'JPEG',
quality,
0,
(uri) => {
const binaryString = atob(uri.split(',')[1])
const len = binaryString.length
const bytes = new Uint8Array(len)
for (let i = 0; i < len; ++i) {
bytes[i] = binaryString.charCodeAt(i)
}
const blob = new Blob([bytes], {type: 'image/jpeg'})
const resizedFile = new File([blob], file.name, {type: file.type})
resolve(resizedFile)
},
'base64'
)
})
}
export default resizeImage
const resizedFile = await resizeImage(file, 500, 500, 100)
이미지를 resize하는 라이브러리입니다.
직접적인 사이즈를 조절하고 싶다면 Next Js나 Gatsby를 통한 프레임워크를 사용하거나 백엔드를 통해 CDN을 적용하면됩니다.
위 라이브러리를 통해서 Max값을 적용하여 이미지의 사이즈가 너무 커지지 않도록만 했습니다.
파라미터값으로는 file, maxWidth, maxHeight, quality 4가지가 있으며
업로드 파일, Max 넓이, Max 높이, 크기가 조정된 새 이미지의 품질 입니다.
실제로 사이트를 보면 파라미터 값을 보면
import Resizer from "react-image-file-resizer";
Resizer.imageFileResizer(
file, // Is the file of the image which will resized.
maxWidth, // Is the maxWidth of the resized new image.
maxHeight, // Is the maxHeight of the resized new image.
compressFormat, // Is the compressFormat of the resized new image.
quality, // Is the quality of the resized new image.
rotation, // Is the degree of clockwise rotation to apply to uploaded image.
responseUriFunc, // Is the callBack function of the resized new image URI.
outputType, // Is the output type of the resized new image.
minWidth, // Is the minWidth of the resized new image.
minHeight // Is the minHeight of the resized new image.
);
위처럼 나와있으므로 참고해서 사용하면 됩니다.
라이브러리 | 장점 | 단점 |
---|---|---|
browser-image-compression | 압축 가능 | 이미지 크기 조정 불가 |
browser-image-resizer | 이미지 크기 조절 가능 | 이미지 압축 불가 |
react-image-file-resizer | 이미지 크기 조절 가능 압축 가능 | React에서만 사용 가능 |