想要在前端项目中压缩图片,然后再上传到后端保存,就需要一个压缩工具的帮助,暂时有两个依赖库可以选择:image-conversion和yireen/squoosh-browser,看了官方仓库地址和更新时间等详情,发现还是yireen/squoosh-browser最新一些,所以就选择了yireen/squoosh-browser。
@yireen/squoosh-browser地址:@yireen/squoosh-browser - npm
@yireen/squoosh-browsergithub地址:GitHub - myeveryheart/squoosh-browser: An image compression tool run in browser while @squoosh/lib can not.
image-conversion地址:image-conversion - npm
安装
执行命令:
pnpm install @yireen/squoosh-browser
使用
创建一个工具文件,然后添加下面内容:
import Compress from '@yireen/squoosh-browser'
import {defaultPreprocessorState,defaultProcessorState,encoderMap,EncoderState
} from '@yireen/squoosh-browser/dist/client/lazy-app/feature-meta'/*** 图片压缩编码器枚举*/
export enum CompressEncoderEnum {// eslint-disable-next-line no-unused-varsmozJPEG = 'mozJPEG',// eslint-disable-next-line no-unused-varsavif = 'avif',// eslint-disable-next-line no-unused-varswebP = 'webP'
}/*** 判断文件类型是否为图片格式* @param fileType*/
export const isImage = (fileType: string): boolean => {return /(png|jpg|jpeg|gif|webp|awebp|avif|svg\+xml|svg|x-icon|vnd.microsoft.icon)$/.test(fileType)
}/*** 判断是否需要压缩的图片格式* @param imageType*/
export const isNeedCompress = (imageType: string): boolean => {return /(png|jpg|jpeg|webp|avif)$/.test(imageType)
}/*** 压缩图片* @param file* @param encoder*/
export const compressImage = async (file: File, encoder: CompressEncoderEnum) => {if (isNeedCompress(file.type)) {const compress = new Compress(file, {encoderState: {type: encoder,options: encoderMap[encoder].meta.defaultOptions} as EncoderState,processorState: defaultProcessorState,preprocessorState: defaultPreprocessorState})return compress.process()}return file
}